Home Know Me Snaps Feedback
 
::Online Microsoft Office,Web ,Graphic and many more Tutorials
Simple File Uploading with PHP
In this tutorial I am going to show you how to create a simple upload script which will enable you to upload .gif, .jpg and .png images. This can be enhanced to allow more formats if you wish but I will not cover this in this tutorial.

Creating the form

Add the following code:

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<br/>
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>

This is the html code for the form, it adds a simple file upload field and an upload button. The upload field will have a browse button, the user will click this to locate the file on their computer and then click the Upload button to upload it to the server.

this copy and paste this code below the html code you added earlier:

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
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 "Uploaded";
}
}
}
else
{
echo "Invalid file";
}
?>

If you take a look at the code above you will notice that it defines some actions first of all, so for example it defines your email address as $to and the subject of the email as $subject. Now you will also notice a $_POST["title"]; this collects the data from the previous page in the field stated in the speech marks (in this case title). The name of the $_POST is the name of the form item.

Finally it mails the email to you by calling the $to (your email address), the $subject (title of the email), $messagesent (the message) and $headers which is the recipients name/email.

A few things to do to make it all work properly…

  • You need to make sure that your uploads folder is granted access rights by users of the site, in order to do this ensure that you chmod the folder to 777. There should be an option to change the permissions of a folder on your file manager of the web host area.
  • Sometimes you may get an error saying that there is a problem with the memory handling, this is because you haven’t set an appropriate memory limit. To set it add this code just under the <?php :
    ini_set(”memory_limit”,”12M”);
  PHP Table of Content
  Php sessions System
  Create a PHP contact form
  Comment System with php/mysql
  Admin Login and Delete Comment
  Simple file upload
  File Upload Function
  Connect with mysql database
 
   
 
 
       
   
© 2008, krishnakumar.com.np. All rights reserved
.