Resize uploaded image - PHP

Tom picture Tom · May 5, 2011 · Viewed 10k times · Source

I am using the basic upload code from the w3schools website but I would like to add the ability to resize the image on upload to 200px wide. Is this something that can be simply added to this code or do I need a different approach to achieve this?

Here's the code:

    <?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Big Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "<img src='upload/" . $_FILES["file"]["name"] . "' /><br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Answer

David Fells picture David Fells · May 5, 2011

You need to check which image library you have available first, using phpinfo() - you likely have GD and/or ImageMagick. There are tons of tutorials on how to write the resizing code out there - here's one: http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html