Twitter self-hosted image service/url shortener
<? | |
// Twitter self-hosted image service/url shortener by Ryan Petrich | |
// Installation: | |
// 1. Paste this script into the top of your HTTP root's index.php (rename index.html to index.php if it doesn't exist) | |
// 2. Add the following to your HTTP root's .htaccess file (create .htaccess if it doesn't exist): | |
// ErrorDocument 404 /index.php | |
// 3. Create a "s" subfolder and give it 777 permissions | |
// 4. Add the following as the custom URL for URL shortening in Twitter for iPhone's settings: | |
// http://yourdomain.com/?d=%@&p=password | |
// 5. Add the following as the custom URL for Image service: | |
// http://yourdomain.com/?password | |
$password = 'password'; | |
function genRandomString($length) { | |
$characters = '0123456789abcdefghijklmnopqrstuvwxyz'; | |
$string = ''; | |
for ($p = 0; $p < $length; $p++) { | |
$string .= $characters[mt_rand(0, strlen($characters))]; | |
} | |
return $string; | |
} | |
function randomFileName() { | |
$filename = genRandomString(4); | |
while (file_exists("s/$filename.url") || file_exists("s/$filename.png") || file_exists("s/$filename.jpg")) | |
$filename = genRandomString(5); | |
return $filename; | |
} | |
if (($_GET['p'] == $password) && isset($_GET['d']) && ($_GET['d'] != '%@')) { | |
// Shortening a URL | |
$filename = randomFileName(); | |
$fh = fopen("s/$filename.url", 'w') or die("can't open file"); | |
fwrite($fh, $_GET['d']); | |
fclose($fh); | |
echo 'http://'.$_SERVER['SERVER_NAME'].'/'.$filename; | |
exit(); | |
} | |
$url = $_SERVER['REQUEST_URI']; | |
if ($url == "/?$password") { | |
// Uploading media | |
$filetype = $_FILES['media']['type']; | |
if ($filetype == 'image/png') | |
$filetype = '.png'; | |
else if ($filetype == 'image/jpeg') | |
$filetype = '.jpg'; | |
else | |
die('bad filetype'); | |
$filename = randomFileName(); | |
move_uploaded_file($_FILES['media']['tmp_name'], 's/'.$filename.$filetype); | |
echo '<mediaurl>http://'.$_SERVER['SERVER_NAME'].'/'.$filename.'</mediaurl>'; | |
exit(); | |
} | |
if (strpos($url, '.') == false) { | |
$url = substr($url, 1); | |
// Shortened URL | |
if (file_exists("s/$url.url")) { | |
$contents = file("s/$url.url"); | |
header('HTTP/1.1 301 Moved Permanently'); | |
header('Location: '.$contents[0]); | |
exit(); | |
} | |
// Uploaded media (PNG) | |
if (file_exists("s/$url.png")) { | |
header('Content-Type: image/png'); | |
header('Content-Length: ' . filesize("s/$url.png")); | |
ob_clean(); | |
flush(); | |
readfile("s/$url.png"); | |
exit(); | |
} | |
// Uploaded media (JPEG) | |
if (file_exists("s/$url.jpg")) { | |
header('Content-Type: image/jpeg'); | |
header('Content-Length: ' . filesize("s/$url.jpg")); | |
ob_clean(); | |
flush(); | |
readfile("s/$url.jpg"); | |
exit(); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment