nerdarama
nerdarama

Reputation: 493

Save image from webpage using php

I know my question is quite similar to this question and I'm using the answer to the problem as my solution but I can't get it to work.

I'm using Immediatenet.com to generate a thumbnail of any given URL (example: google). And then using cURL to save the image in a folder on my server.

I'm not sure if the problem lies in the fact that the URL isn't actually an image URL (ie example.com/image.jpg) or a .html/.php URL or that I'm simply not doing it right. I've never used cURL before so it's distinctly possible that I'm not doing it right.

I'm saving the path to the image into a MySQL database which works just fine. However, the image doesn't actually save in the folder specified. The permissions are set correctly on the folder, so I don't think it's a permissions problem. I also set allow_url_fopen to On just to make sure.

My code is below. Can anyone point me in the right direction for this one?

$url = $_POST['url'];
$url_new = 'http://immediatenet.com/t/m?Size=1024x768&URL='.$url;
$img = "/users/images/".$url.".jpg";
$ch = curl_init($url_new);
$fp = fopen($img, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Upvotes: 1

Views: 1045

Answers (2)

Barmar
Barmar

Reputation: 782488

If $url contains forward slashes (as most URLs do), these will be treated as directory delimiters in the $img pathname. You either need to replace the slashes with some other character, or create all the necessary directories.

$img = "/users/images/".str_replace('/', '_', $url).".jpg";

Upvotes: 2

Sorin Trimbitas
Sorin Trimbitas

Reputation: 1497

Are you sure $img = "/users/images/".$url.".jpg"; is valid? .. do you really have a users folder in your root?

Please correct that if not and it should be ok.

Upvotes: 0

Related Questions