-1

Possible Duplicate:
PHP resize and upload an image

I have a website where user's can upload photos. Now, I am starting to realize that some of the photos need to be re-sized and converted. I know how to upload and move photos, but how do I re-size them if they are too big and convert them to JPEG's if they aren't?

Here is my PHP:

if ($_FILES['media']['size'] != 0) {
    $target= UPLOADPATH . $media;
    move_uploaded_file($_FILES['media']['tmp_name'], $target);
    $query= "INSERT INTO posts (user_id, story, media, date, view, type)
                        VALUES ('$user_id', '$story', '$media', now(), '$view', '1')";
    mysqli_query($connect, $query) or die('error with query 2');
}
Salman A
  • 262,204
  • 82
  • 430
  • 521
Matt
  • 163
  • 3
  • 10
  • [resize](http://stackoverflow.com/questions/6608586/php-resize-and-upload-an-image) and [convert to jpg](http://stackoverflow.com/questions/6889543/converting-bmp-to-jpg-in-php) – Matt Ellen Jan 06 '13 at 20:51

1 Answers1

3

Here is one suggestion:

Make some rules about the files you will accept (e.g. JPEG and PNG, smaller than 2MB, max 5 mega-pixels). Store the "acceptable" files in a convenient location, perhaps outside the document root.

Do not re-size the images on upload. Re-size the images on-demand, using phpThumb** for example.

This approach will prove better than re-sizing images on upload in the long run: you will never need to process all (possibly hundreds of) images when:

  • Your website layout changes
  • You project requirements change
    • You add a lightbox style slideshow and suddenly you need thumbnails for it
  • You need to serve different resolutions to different devices
  • You need to process images (e.g. write your company name on images)
    • Your company name changes
  • You are told that all thumbnails need to be changed to square

** When using phpThumb, I recommend spending some time going through its configuration. Especially the security and caching related settings. Also a good idea to create a white-list of output image resolutions.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • However, heavily caching images is recommended. Images and sizes which are not likely to change are best cached for longer periods of time. – Madara's Ghost Jan 06 '13 at 21:09
  • True, that is worth mentioning. phpThumb has that feature. – Salman A Jan 06 '13 at 21:11
  • Well and if you cache then this is perfect for DDOS attacking and "requesting the platter full" attacking and what not. Which brings back to the point that you should keep original and resize on upload. – hakre Jan 06 '13 at 21:15
  • I added a note about white listing image sizes. – Salman A Jan 06 '13 at 21:23