Created
April 8, 2009 13:14
-
-
Save hubgit/91760 to your computer and use it in GitHub Desktop.
Store data in TinyURL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// http://search.cpan.org/dist/WWW-WebStore-TinyURL/ | |
// http://asserttrue.blogspot.com/2009/02/data-urls-to-tinyurls-and-vice-versa.html | |
$file = $argv[1]; | |
print "Posting...\n"; | |
$tinyurl = post_data($file); | |
print $tinyurl . "\n"; | |
print "Fetching...\n"; | |
fetch_data($tinyurl); | |
function post_data($file){ | |
$data = rawurlencode(base64_encode(file_get_contents($file))); | |
$context = array('http' => array('method' => 'POST', 'content' => 'url=' . $data)); | |
return file_get_contents('http://tinyurl.com/api-create.php', NULL, stream_context_create($context)); | |
} | |
function fetch_data($url){ | |
preg_match('!^http://tinyurl\.com/(.+)!', $url, $matches); | |
$id = preg_replace('/\W/', '', $matches[1]); | |
$curl = curl_init(); | |
$curl_params = array( | |
CURLOPT_URL => $url, | |
CURLOPT_HEADER => TRUE, | |
CURLOPT_CUSTOMREQUEST => 'HEAD', | |
CURLOPT_TIMEOUT => 10, | |
CURLOPT_CONNECTTIMEOUT => 10, | |
CURLOPT_NOBODY => TRUE, | |
CURLOPT_FOLLOWLOCATION => FALSE, | |
CURLOPT_RETURNTRANSFER => TRUE, | |
); | |
curl_setopt_array($curl, $curl_params); | |
$response = curl_exec($curl); | |
list($header, $data) = explode("\n\n", $response, 2); | |
preg_match('/Location: (.*?)\n/', $header, $matches); | |
file_put_contents($id, base64_decode(rawurldecode(trim($matches[1])))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment