How to Upload File in PHP

php file upload 1

File upload is the maximum used characteristic within the web application.
PHP presents an easy manner to upload documents or images to the server.
With PHP, you could upload documents or images to the server by writing minimal code.
In this tutorial, we will provide a PHP script to add documents to the directory on the server.
Using our PHP script you may add all types of files including photos to the server in PHP.

Upload Form HTML
At first, HTML form desires to be created that permit user to pick out a file they need to add.
Make sure tag contains the following attributes.

  • method=”post”
  • enctype=”multipart/form-data”

Also, make sure <input> tag contains type=”file” attribute.
Thus, code will look like as per below :

<form action="uploadfile.php" method="post" enctype="multipart/form-data">
    Select File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">

The above upload form will be submitted to the uploadfile.php file for uploading a document or a image to the server.

Now create a file to Upload File in PHP (uploadfile.php)

PHP provides a function called move_uploaded_file() that moves an uploaded file to a given location.
Using move_uploaded_file() function we can upload a file in PHP.
The following code is used to upload a file in PHP. Specify the directory in $target_dir a variable, where the uploaded file will be placed.
Also, in following code we had define the file types that you want to allow for uploading.

$status_msg = '';
$target_dir = "uploads_files/";  // File upload aboutsulte path For Example : C:/xampp/htdocs/php-demos/uploads_files/
$filename = basename($_FILES["file"]["name"]); // get your file base name
$target_file_path = $target_dir . $filename; // set your path with file to upload
$filetype = pathinfo($target_file_path,PATHINFO_EXTENSION); // get your file type 
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])) {
    //allow certain file formats
    $allowed_file_types = array('jpg','png','jpeg','gif','pdf','doc','docx','ppt','pptx'); // Set your allow file types here
    if(in_array($filetype, $allowed_file_types)){
        //upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_path)){
            $status_msg = "The file ".$filename. " has been uploaded successfully.";
            $status_msg = "Sorry, there was an error while uploading your file.";
        $status_msg = 'Sorry, only JPG, JPEG, PNG, GIF, PDF, DOC, DOCX, PPT, PPTX files are allowed to upload.';
    $status_msg = 'Please select a file to upload.';

//display file upload status message
echo $status_msg;

Leave a Reply

Your email address will not be published. Required fields are marked *