note 74349 deleted from function.stream-copy-to-stream by nlopess

From: Date: Fri, 06 Apr 2007 19:35:17 +0000
Subject: note 74349 deleted from function.stream-copy-to-stream by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-125156@lists.php.net to get a copy of this message
Note Submitter: lucky760at yahoodotcom ---- I'm really glad this function was added. It makes downloading Internet files into local files much cleaner. On http://www.VideoSift.com I am implementing a simple member feature to upload an image as an avatar instead of simply storing a URL. We will allow two methods: 1) uploading from the user's local machine; 2) downloading from a web URL. This is how I'm accomplishing #2. It also demonstrates resizing an image to a new width. <?php function download_avatar(User &$i_user, $i_url) { // do a simple syntax check first if (!preg_match('@^https?://.{10,}@i', $i_url)) return FALSE; set_time_limit(30); // open the URL $remote = @fopen($i_url, 'r'); if (!$remote) return FALSE; // create a temporary local file $tmpfile = tempnam(NULL, $i_user->nick); $local = @fopen($tmpfile, 'w'); if (!$local) return FALSE; // copy up to MAX_UPLOAD_SIZE bytes into the local tmp file // the limit is important as a malicious user could specify // the URL for a ginormous file $written = stream_copy_to_stream($remote, $local, MAX_UPLOAD_SIZE); fclose($remote); fclose($local); do { $failure = TRUE; // there were no bytes read - fail if (!$written) break; // get the info of the image (jpg/gif/png allowed) and create an image; // if we didn't download a valid file we fail $size_info = @getimagesize($tmpfile); switch ($size_info[2]) { case 1: $full = imagecreatefromgif($tmpfile); break; case 2: $full = imagecreatefromjpeg($tmpfile); break; case 3: $full = imagecreatefrompng($tmpfile); break; } if (!isset($full)) break; $resize_height = (AVATAR_WIDTH / $size_info[0]) * $size_info[1]; // create the resized image $thumb = imagecreatetruecolor(AVATAR_WIDTH, $resize_height); imagecopyresampled($thumb, $full, 0, 0, 0, 0, AVATAR_WIDTH, $resize_height, $size_info[0], $size_info[1]); // save our avatar file as a jpg, now with our desired width $outfile = somehow_determine_the_file_path(); if (!imagejpeg($thumb, $outfile, JPG_QUALITY)) break; imagedestroy($thumb); imagedestroy($full); } while ($failure = FALSE); // delete the temp file unlink($tmpfile); return !$failure; } ?> I'll leave it as an exercise for you to handle resizing images that are too tall.

« previous php.notes (#125156) next »