Created
June 1, 2010 11:32
-
-
Save leejarvis/420831 to your computer and use it in GitHub Desktop.
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 | |
function trimit(&$val) { | |
$val = trim($val); | |
} | |
function trim_array_contents(&$arr) { | |
array_walk($arr, 'trimit'); | |
} | |
function ask($question) { | |
echo $question; | |
$ans = trim(fgets(STDIN)); | |
return 'y' == strtolower($ans[0]); | |
} | |
function write($store, $filename, $contents) { | |
echo "\tGot $filename ..\n"; | |
echo "What would you like to save this as? (hit enter to use $filename): "; | |
$outfile = trim(fgets(STDIN)); | |
if ( empty($outfile) ) $outfile = $filename; | |
$fh = fopen($store.'/'.$outfile, 'w'); | |
fwrite($fh, $contents); | |
fclose($fh); | |
echo "\tSaved $outfile ..\n"; | |
} | |
function read($url) { | |
$uri = parse_url($url); | |
$sock = fsockopen($uri['host'], 80, $errn, $errs, 10); | |
if (! $sock) { | |
echo "Unable to connect.\n\t$errs\n"; | |
return null; | |
} | |
$query = "GET ".$uri['path']." HTTP/1.1\r\n". | |
"Host: ".$uri['host']."\r\n\r\n"; | |
$contents = ""; | |
fwrite($sock, $query); | |
while(! feof($sock)) | |
$contents .= fgets($sock); | |
list($head, $body) = explode("\r\n\r\n", $contents, 2); | |
$img_types = array('gif', 'jpeg', 'png', 'svg+xml', 'tiff'); | |
$reg = implode('|', $img_types); | |
if (! preg_match('/Content-Type: image\/'.$reg.'/', $head, $matches) ) { | |
echo "\tPath is not an image\n"; | |
return null; | |
} | |
return $body; | |
} | |
/** Program Flow */ | |
if (! isset($argv[1]) ) | |
die("Usage: ".$argv[0]." <file>\n"); | |
$file = $argv[1]; | |
$path = realpath($file); | |
if (! file_exists($path) ) | |
die("File '$file' not found. Exiting ..\n"); | |
echo "Please specify a location to store images: "; | |
$store = trim(fgets(STDIN)); | |
if (! file_exists($store) ) { | |
if ( ask("This directory does not exist. Would you like to create it?: ") ) { | |
if (! mkdir($store, 0777, true) ) | |
die("Unable to make directory ..\n"); | |
} else { | |
echo "Exiting ..\n"; | |
exit; | |
} | |
echo "Created directory - $store\n"; | |
} | |
$lines = file($file); | |
trim_array_contents($lines); | |
foreach($lines as $url) { | |
echo "Downloading $url ..\n"; | |
if ( ($contents = read($url)) !== null) { | |
$filename = parse_url($url, PHP_URL_PATH); | |
write($store, basename($filename), $contents); | |
} else { | |
echo "\tSkipping ..\n"; | |
} | |
} | |
echo "Done\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment