PDA

View Full Version : Calling PHP experts.


webit
13th February 2006, 08:58
PHP Guru’s

Can anyone post the code to achieve the following?

A function which takes the URL of an image over http: and saves that image to disk. I think it can be done with the PHP graphics library but I need to look into it further.

For example:

doit(‘http://www.site.com/images/tsblogo_square.jpg’) ;

function doit(URL)
{
// code to write the image at the URL to a folder on disk….
}

Thanks
DC

Sapphire-Limited
13th February 2006, 12:30
Hello,

Maybe you need to use the 'fget' function.

Here's a link:

http://uk.php.net/manual-lookup.php?pattern=fget

Regards
Gareth
Sapphire Document Solutions

Coding Monkey
13th February 2006, 12:40
Unless I'm mistaken, fgets only shows the image, it does not copy it onto a part of the HD.

Robert
13th February 2006, 17:54
Do you mean the disk on the server? Have a look at "copy" http://uk.php.net/manual/en/function.copy.php and specify a URL as the first argument.

Dread
15th February 2006, 04:58
Piece of cake...

<?
function grab_image($url){
ob_start(); // start the output buffer
readfile($url); // grab the image data
$image = ob_get_contents(); // take the image and store in varible
ob_end_clean(); // clean buffer

$filename = array_pop(explode('/', $url)); // get the name of the file

if(file_exists($filename)){ // check if the file exists
echo "A file with that name already exists!";
}else{
// store image
$fp = fopen($filename, "w");
fwrite($fp, $image);
fclose($fp);
}
}
?>


I wish this forum had PHP highlighting.....

Coding Monkey
15th February 2006, 07:07
You need to change ob_end_clean() to ob_clean() as otherwise it outputs nothing.

Smaller version......


function grab_image($file){
preg_match("/\/(([\w\-]+)(\.([\w]{1,})))$/", $file, $matches);
$newfile = "{$matches['2']}".mt_rand()."{$matches['3']}";
if (!copy($file, $newfile)) {
echo 'Failed';
}
}
grab_image("http://codingmonkeys.biz/images/logo.jpg");

Dread
15th February 2006, 07:17
You need to change ob_end_clean() to ob_clean() as otherwise it outputs nothing.


Its not suppose to output anything, it just grabs the data of the image so it can be stored. I did test it ya know :P

As with everything in php, theres hundreds of different ways to do the same task.

Coding Monkey
15th February 2006, 07:20
Yeah, I tested it too, and it didn't output anything via fwrite unless I changed it to ob_clean. I had just blank, empty files via PHP 5.1. I thought it was incorrect, thus tested it. Wasn't just being an arse

Dread
15th February 2006, 07:26
hmmm, well my example worked on my server...

Could it possibly be a difference in php versions? im on 5.0.4 or possibly a php.ini setting?

webit
15th February 2006, 19:04
Thanks guys - I'll give them a go and let you know what happens. Thanks for your time.