Skip to content

Instantly share code, notes, and snippets.

@man4toman
Last active October 4, 2018 11:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save man4toman/30a19bbb855cd008b76216a7e2a7be9b to your computer and use it in GitHub Desktop.
Some methods for get/leech and save images from url.
<?php
/*
* Method 1: use file_put_contents, but it disabled in many shared hosts
*/
$url = "http://site.ltd/test-image.jpg";
file_put_contents("/path/to/folder/" . basename($url), file_get_contents($url));
/*
* Method 2: use file_get_contents, it disabled in many shared hosts too!
*/
$content = file_get_contents("http://site.ltd/test-image.jpg");
$fp = fopen("/path/to/folder/new-image-name.jpg", "w");
fwrite($fp, $content);
fclose($fp);
/*
* Method 3: use fopen with curl
*/
$ch = curl_init("http://site.ltd/test-image.jpg");
$fp = fopen("/path/to/folder/new-image-name.jpg", "wb");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
/*
* Method 4: use fopen and download images from remote server
*/
$in = fopen("http://site.ltd/test-image.jpg", "rb");
$out = fopen("/path/to/folder/new-image-name.jpg", "wb");
while ($chunk = fread($in,8192)){
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment