How to add simple image upload to a form?

ninja208 picture ninja208 · Dec 12, 2010 · Viewed 37.1k times · Source

I have a html form. I want to add a simple image upload feature to it and it will be send the image to a php page called "next.php". Any suggestions on how to do it?

Answer

user513873 picture user513873 · Dec 12, 2010

Create an HTML form like the following:

<html>
<body>
<form action="next.php" method="post" enctype="multipart/form-data">
<label for="image">Image:</label>
<input type="image" name="image" id="image" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Your "next.php" file could handle the image similar to this:

<?php

if ($_FILES["file"]["error"] > 0)
    echo "Error: " . $_FILES["image"]["error"] . "<br />";
else
{
    echo "Upload: " . $_FILES["image"]["name"] . "<br />";
    echo "Type: " . $_FILES["image"]["type"] . "<br />";
    echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["image"]["tmp_name"];
}

At this point, you can make it more secure by checking the type and ensuring it's only jpg, gif, png, or of the sort. I would recommend copying the image into 2 or 3 sizes (thumb, medium, original), and deleting it from the temporary directory. You could use ImageMagick to resize the images and then use the filesystem functions to move around and delete temporary uploads.