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?
Asked
Active
Viewed 4.7k times
5
-
A Google search for PHP upload file returns about 25 million results, such as: http://www.w3schools.com/PHP/php_file_upload.asp PS: I see you tagged your question `asyncfileupload`: do you want the upload to be asynchronous? – nico Dec 12 '10 at 14:54
2 Answers
3
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.
1
I'm not aware of any means to interact with a file input
on the client-side, so you'll need to verify/validate the uploaded file server-side (within the 'next.php' script), but this should be enough:
<form action="path/to/next.php" method="post" enctype="multipart/form-data">
<fieldset>
<input type="file" name="picture" id="picture" />
</fieldset>
</form>

David Thomas
- 249,100
- 51
- 377
- 410
-
1The enctype attribute has to be set or this won't work. He'll be beating his head against the wall trying to figure out what is going wrong... – Brian H Dec 12 '10 at 15:04
-
@Brian H, oops...thanks, and edited. There's always **something**... =D – David Thomas Dec 12 '10 at 15:11