Monday, 7 July 2014

How to upload a file using PHP ?

For uploading a file in PHP + MySQL, we have to use datatype as varchar(250) to store the filename and it's path.

Before uploading any photo or doc we must have to make our form tag as enctype. And inside the phpcode we must have to check weather the file is already exists in that location or not.

For Example. Table of Database is given
tblimagedemo
Data Type            Column Name 
id                           int                             PK  Auto_Increment  
photo                    varchar(250)

On Webpage file upload control is given in below image to choose file with button submit.


For that write HTML code.

<form method="post" name="pform" id="pform" action="" enctype="multipart/form-data">
<table>
<tr>
<td>Image</td>
<td>
<input type="file" value="" name="file" id="file"/>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit" name="btnsubmit"/>
<input type="button" value="reset" name="btnreset"/>
</td>
</tr>
</table>
</form>


Write PHP code in head or body section.
<?php

if(isset($_POST['btnsubmit']))
{
if($_FILES['file']['error']>0)
   {
         echo"Error in uploading";
   }
else
   {
       echo"upload:".$_FILES['file']['name']."<br>";
        $i="image/".$_FILES['file']['name'];

         if(file_exists("image/".$_FILES['file']['name']))
          {
                       echo $_FILES['file']['name']."File is already  Exists";
          }
          else
          {
                   move_uploaded_file($_FILES['file']['tmp_name'],"image/".$_FILES['file']['name']);
                  echo "File is uploaded successfully";
          }
    }
if(empty($i))
{
echo "Upload your image";
}
else
{
$sql = "INSERT INTO `superstore`.`tblimagedemo` (`id`, `photo`) VALUES (NULL, '$i')";

                 if(mysqli_query($con,$sql))
                {
                      echo"Record inserted";
                 }
                else
                {
                        echo"error";
                 }
}
}

Learn PHP Project with MySQL 
visit website : Final Year Project Training in Vadodara for student

3 comments:

  1. The code is perfect to write coding of uploading image with all validations check like image is selected by the file tag or not and this php program code also check weather the image is already exist or not.

    ReplyDelete
  2. If You are interested for learning PHP Project Training Then visit below website: www.vataliyatuitionclasses.com

    ReplyDelete
  3. PHP - World's best Web Development Technology For more information visit http://www.vataliyacomputer.in

    ReplyDelete