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
 
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
C

Coding Monkey

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

Latest Articles