PHP uploads recipe

  toucheatout  2008-03-04 13:16  

Simple upload with onsuccess/onerror redirection

Filename is chosen with the IP as suffix, which is unsufficient in the general case and left as an example.
<?php
if(!empty($_FILES['file_uploaded']['tmp_name']) &&
   is_uploaded_file($_FILES['file_uploaded']['tmp_name'])) {

  if(move_uploaded_file($_FILES['file_uploaded']['tmp_name'],
   'img/upload.' . $_SERVER['REMOTE_ADDR'])) {
          header('Location: upload.php?res=success&filename=upload.' .
                  $_SERVER['REMOTE_ADDR']);
        }
        else
        {
          header('Location: upload.php?res=failure&filename=upload.' .
          $_SERVER['REMOTE_ADDR']);
        }
}
?>

Refinements:

Check filesize (2Mo here)

<?php
  if(filesize($_FILES['file_uploaded']['tmp_name']) < 204800) {
?>

Get image dimension infos, check image type is PNG

<?php
  list($width, $height, $type, $attr) =
    getimagesize($_FILES['file_uploaded']['tmp_name']);

  if($type == IMAGETYPE_PNG) {
?>

Other constants are defined in PHP, for instance IMAGETYPE_JPEG, IMAGETYPE GIF, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_BMP, IMAGETYPE_ICO, ... (Look up all the constants in the php manpage for Image))

 
Informatics


yro.slashdot.org - Your Rights online


nytimes.com New York Times - International


Informatic headlines