Skip to content

Instantly share code, notes, and snippets.

@por
Created April 27, 2011 15:08
Show Gist options
  • Save por/944410 to your computer and use it in GitHub Desktop.
Save por/944410 to your computer and use it in GitHub Desktop.
Scrup FTP Handler
<?
/**
* Scrup FTP handler
* https://github.com/rsms/scrup
*/
$DOMAIN = "http://scrup.domain.com";
$MAXSIZE = 2097152; // 2 MB
$FTP_SERVER = "scrup.domain.com";
$FTP_USER = "scrup";
$FTP_PASSWORD = "secret";
function http_response($msg='', $st='400 Bad Request') {
header('HTTP/1.1 '.$st);
exit($msg);
}
function d($d) {
echo "<pre>";
var_dump($d);
echo "</pre>";
}
// Build path and url
// Construct 'unique' filename
$filename = substr( base_convert( md5( strval(microtime()) . ' ' . $_SERVER['REMOTE_ADDR'] ), 16, 36 ), 0, 12 ) . '.png';
// Construct url
$url = $DOMAIN . $filename;
// Here we should probably check if the file actually already exists
// ...
// Open FTP connection
$ftp_connection = ftp_connect($FTP_SERVER);
$ftp_result = ftp_login($ftp_connection, $FTP_USER, $FTP_PASSWORD);
if ( (!$ftp_connection) || (!$ftp_result) ) {
trigger_error('FTP connection failed', E_USER_ERROR);
}
// Temp file
$temp = tmpfile();
$srcf = fopen('php://input', 'r');
$size = stream_copy_to_stream($srcf, $temp, $MAXSIZE);
// No input?
if ($size === 0) {
http_response('Empty input');
} elseif ($size >= $MAXSIZE) {
http_response('Request entity larger than or equal to ' . $MAXSIZE . ' B', '413 Request Entity Too Large');
}
// Set head back to 0
fseek($temp, 0);
// Here we should probably check if the file is indeed a .png
// ...
// Initate the upload
$upload = ftp_nb_fput($ftp_connection, $filename, $temp, FTP_BINARY);
while ($upload == FTP_MOREDATA) {
// Continue upload...
$upload = ftp_nb_continue($ftp_connection);
}
if ($upload != FTP_FINISHED) {
echo "There was an error uploading the file...";
exit();
}
fclose($temp);
# Respond with the url
header('HTTP/1.1 201 Created');
header('Content-Type: text/plain; charset=utf-8');
header('Content-Length: '.strlen($url));
echo $url;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment