views:

258

answers:

3

In PHP using GD or imagemagick how can I uplaod a photo from a URL, I want to build a function that I can pass in a few parameters and uplaod the image, I can currentyl uplaod a big image, resize it smaller, then resize some more thumbnails off it and save all into there locations from 1 image but I would like to add the ability to get an image from a URL and then run my code on it to resize and make thumbs.

Would I use curl or something else any example or ideas would be greatly appreciated

+2  A: 

Depending on your PHP configuration, fopen may or may not allow for it directly: http://php.net/manual/en/function.fopen.php

Alternatively, you can open a socket (http://php.net/manual/en/book.sockets.php) and write / read HTTP (http://www.faqs.org/rfcs/rfc2616.html) directly. I wouldn't use curl unless you're VERY careful about permissions (especially execute), or can guarantee noone malicious will have access to the tool, as you'll effectively open a potential avenue of attack (well, strictly speaking, you already are, but this has a few different ways it can be abused)

James
A: 
$img = '';
$fp = fopen($url, 'rb');
if($fp) {
    while($buf = fread($fp, 1024)) {
        $img .= $buf;
    }    
}
fclose($fp);

// assuming url fopen wrappers are enabled

Rob
This works, but `file_get_contents` is preferable by far
Justin Johnson
+4  A: 
$image = @ImageCreateFromString(@file_get_contents($imageURL));

if (is_resource($image) === true)
{
    // image is valid, do your magic here
}

else
{
    // not a valid image, show error
}

The @ on both functions are there to prevent PHP from throwing errors if the URL is not a valid image.

Alix Axel
should probably add the `FILE_BINARY` flag...
Rob
@Rob: FILE_BINARY: This **is the default setting** and cannot be used with FILE_TEXT. Not to mention it applies only to PHP 6.
Alix Axel
This looks awsome if it works how I want it to, So in this case does $image actually have the file on my servers memory, just like if I were to upload with a form post?
jasondavis
@jasondavis: No, `$image` is in fact already an opened GD image resource, you just have to use the `image*` functions to resize and display / save the image (if everything goes well, of course).
Alix Axel
great ill try it tommorrow, thanks
jasondavis