Calling PHP experts.

webit

Free Member
Jul 13, 2005
1,124
7
Brighton, UK
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
 
Unless I'm mistaken, fgets only shows the image, it does not copy it onto a part of the HD.
 
Upvote 0
Piece of cake...
Code:
<?
function grab_image&#40;$url&#41;&#123;
	ob_start&#40;&#41;; // start the output buffer
	readfile&#40;$url&#41;; // grab the image data
	$image = ob_get_contents&#40;&#41;; // take the image and store in varible
	ob_end_clean&#40;&#41;; // clean buffer
	
	$filename = array_pop&#40;explode&#40;'/', $url&#41;&#41;; // get the name of the file
	
	if&#40;file_exists&#40;$filename&#41;&#41;&#123; // check if the file exists
		echo "A file with that name already exists!";
	&#125;else&#123;
		// store image
		$fp = fopen&#40;$filename, "w"&#41;;
		fwrite&#40;$fp, $image&#41;;
		fclose&#40;$fp&#41;;
	&#125;
&#125;
?>

I wish this forum had PHP highlighting.....
 
Upvote 0
You need to change ob_end_clean() to ob_clean() as otherwise it outputs nothing.

Smaller version......

Code:
function grab_image&#40;$file&#41;&#123;
        preg_match&#40;"/\/&#40;&#40;&#91;\w\-&#93;+&#41;&#40;\.&#40;&#91;\w&#93;&#123;1,&#125;&#41;&#41;&#41;$/", $file, $matches&#41;;
        $newfile = "&#123;$matches&#91;'2'&#93;&#125;".mt_rand&#40;&#41;."&#123;$matches&#91;'3'&#93;&#125;";
        if &#40;!copy&#40;$file, $newfile&#41;&#41; &#123;
                echo 'Failed';
        &#125;
&#125;
grab_image&#40;"http&#58;//codingmonkeys.biz/images/logo.jpg"&#41;;
 
Upvote 0
MacMyDay said:
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.
 
Upvote 0
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
 
Upvote 0
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?
 
Upvote 0

Latest Articles