Getting image from url php using curl or fopen

Rakesh Sharma      No Comments  

Getting image from url php using curl or fopen

Getting image from url php using curl or fopen

Sometimes we need to get image from remote or from url to done our task. In Getting image from url php using curl or fopen article we will explore how it could be done. In php we use curl or file functions to make http request(cURL is a library that lets you make HTTP requests in php and file_get_contents() is the preferred way to read the contents of a file into a string). so both method we can use to get file or image from url or remote server
see how we can get or download image from url and save it into directory using curl or file_get_contents. for this i am describing both method to get image from remote server and download or save it into directory.

Getting image from url using curl :-

$profile_Image = 'http://0.gravatar.com/avatar/a879d103e7fa5a06b4b8a07f336a111c?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G'; //image url
$userImage = 'myimg.jpg'; // renaming image
$path = '';  // your saving path
$ch = curl_init($profile_Image);
$fp = fopen($path . $userImage, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);

For more about curl :- curl official docs

Getting image from url using file_get_contents :-

$profile_Image = 'http://0.gravatar.com/avatar/a879d103e7fa5a06b4b8a07f336a111c?s=32&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D32&r=G'; //image url
$userImage = 'myimg.jpg'; // renaming image
$path = '';  // your saving path
$thumb_image = file_get_contents($profile_Image);
if ($http_response_header != NULL) {
    $thumb_file = $path . $userImage;
    file_put_contents($thumb_file, $thumb_image);
}

Note :- if you want use db also use $userImage to save image name in db. Now we can see saved image in given path.
Now you can get image from remote or url using curl or fopen functions. Now you are done with getting image from url php using curl or fopen.