Tutorial: Image upload using forms
When I started out in PHP this was really difficult to get working. I hope this tutorial will speed thing up for you in your quest for the perfect webpage.
This Tutorial will upload an gif image to your server, I restricted It to gif just so you can see how it works, I know this code will not work for all of you because of restrictions from your host. I will make a Tutorial later on in how to go around the restrictions and upload an image even though your host says no.
Lets start of with the HTML code
<form name="form1" method="post" action="" enctype="multipart/form-data">
<input type="file" name="imagefile">
<input type="submit" name="Submit" value="Submit">
Here we just did a form, a filebutton and a submit button.
Now for the fun part:
<?
if(isset( $Submit ))
{
//If the Submitbutton was pressed do:
if ($_FILES['imagefile']['type'] == "image/gif"){
Check if the image type from the selected file is gif. If the type is gif then we want to copy it like this:
copy ($_FILES['imagefile']['tmp_name'], "files/".$_FILES['imagefile']['name'])
or die ("Could not copy");
Copy the temporary file with 'tmp_file' to the our desired location. A temp file usually look like "C:\PHP\uploadtemp\php42F.tmp" and we both know that that's not the file we selected, copy it in using only 'name' to get it right. Thats it really, your file is uploaded but lets write some info about the file we just uploaded to the browser.
echo "";
echo "Name: ".$_FILES['imagefile']['name']."";
echo "Size: ".$_FILES['imagefile']['size']."";
echo "Type: ".$_FILES['imagefile']['type']."";
echo "Copy Done....";
}
The browser should now display the name, size and type of file uploaded, type should be image/gif because thats the
only type we are allowing to be uploaded
else
{
echo "";
echo "Could Not Copy, Wrong Filetype (".$_FILES['imagefile']['name'].")";
}
}
Else, The file is not an gif, write out an errormessage and display the name of the file the user tried to upload. Close the form and you are all done.
?> </form>
|