Skip to content

Instantly share code, notes, and snippets.

@CodeNegar
Created September 11, 2012 12:54
Show Gist options
  • Save CodeNegar/3698235 to your computer and use it in GitHub Desktop.
Save CodeNegar/3698235 to your computer and use it in GitHub Desktop.
php: get and save remote file
<?php
/*
Get and save remote file PHP script
http://egza.org/
*/
error_reporting(E_ALL);
if(!isset($_GET['url'])){
die("url parameter is required.");
}
$file_name = basename($_GET['url']);
$file_name = str_replace(array('/', '\\', '*', ':', '?', '<', '>', '|', '"'), "", $file_name );
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
file_put_contents($file_name, egza_get_file($_GET['url']));
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
echo 'File saved as: <br /><b><a href="' . current_url() . $file_name . '">' . $file_name . '<a></b><br />';
echo 'in '.$total_time.' seconds.';
function current_url() {
$page_url = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$page_url .= "s";
}
$page_url .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$page_url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$page_url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$url_parts = explode('?', $page_url);
return dirname($url_parts[0]) . '/';
}
function egza_get_file($url) {
$url_stuff = parse_url($url);
$port = isset($url_stuff['port']) ? $url_stuff['port']:80;
$fp = fsockopen($url_stuff['host'], $port);
$query = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
$query .= 'Host: ' . $url_stuff['host'];
$query .= "\n\n";
$buffer = "";
fwrite($fp, $query);
while ($line = fread($fp, 1024)) {
$buffer .= $line;
}
preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
return substr($buffer, - $parts[1]);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment