Social Icons

Wednesday, June 19, 2013

PHP file upload

In a website, it is a common requirement to upload a file or photo (image). Here, I am providing a solution as how can do it in PHP. It is not advisable to store the file in database directly. Instead, you should store the file in your project folder and in your database, you should store only the path of the file. So, we'll follow the same approach only.

First we design a form containing a file field. HTML code for the form containing a file field is :

<html>
<head>
<title>File Upload Form</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="myfile" id="myfile"/>
<br/>
<input type="submit" name="submit" id="submit" value="Upload File"/>
</form>
</body>
</html>

Above is just the html code for displaying a file field in the web page. Now, on clicking  of submit button, it will redirect you to upload.php as it is defined in form action. So, we'll write the code for upload.php now.

upload.php

<?php

if ( $_FILES['myfile']['error'] > 0)
{
  echo "Error: ".$_FILES['myfile']['error'];
}
else
{
  if (file_exists("upload/" . $_FILES["myfile"]["name"]))          //upload/file is the path where file                                                                                                                 gets stored
  {
      echo $_FILES["myfile"]["name"] . " already exists. ";
  }
  else
  {
      move_uploaded_file($_FILES["myfile"]["tmp_name"],
      "upload/" . $_FILES["myfile"]["name"]);
      echo "File Stored in: " . "upload/" . $_FILES["myfile"]["name"];
   }}
?>


Thats it. Now, your file upload script is ready. In the above code, "upload/" . $_FILES["myfile"]["name"] is the path where file gets uploaded or stored.  Make sure, you have 'upload' directory in your project folder path. Now as your file gets stored, if you want to save its path in database, then you can run a sql query in your upload.php script as its path after uploading the file. In that case, anytime you can echo the file with the help of the path.

No comments:

Post a Comment

Total Pageviews