File upload in php

File upload in php

Welcome readers! we are back with another article to discuss file upload in PHP. In our previous article, we created an HTML form and Performed the first CRUD operation. We created a "book" table into our "Library" database and inserted the data retrieved from HTML form into our "book" table. We did not explain file upload because it's a separate topic. In this article, we will mainly discuss file upload. We will add a new column "filename" in "book" table to store the name of the pdf or word file. It's because we will only allow the user to upload pdf and word format files. In order to upload files, we will also modify our HTML form by adding a file upload input field. So let"s start our article to learn file upload in PHP.

Adding "Filename" column to "Book" Table:

  • Open "localhost/phpmyadmin" in your browser.
  • Click on the name of the table under database name. In our case, we want to add a column to "book" table and our database name is "library".
  • Once you clicked the table name, click on the "structure" tab to modify the structure of your table.
File upload in php


  • You can see two input fields; enter the number of columns you want to add and after which column you want to add your new columns. 
  •  We want to add "1" column "filename" after the "date" column. After filling the two fields, click on the "go" button. 
File upload in php


  • Now Write the name, type, length, etc of the new column and then click on the save button.
File upload in php


  • You will see a new column will be added to your table.
File upload in php


Modifying HTML form:

  • Open "addbook.php" file that we created in our previous PHP CRUD article.
  • Add "enctype" attribute to HTML form tag and set it to "multipart/form-data". This is crucial if you want to upload files or images through HTML forms.
  • Add an input field of type file to upload files from your form.
Now see the working code of the modified HTML form.

 <div class="container-fluid ">
    	<div class="row justify-content-center">
    	    <div class="col-6 text-center mb-5 py-5 px-5">
 	    <h1 class="text-center mb-5 text-dark">Add books and Spread Knowledge</h1>
    	    <form method="POST" action="includes/addbook.inc.php" enctype="multipart/form-data">
                <div class="form-group my-3">
                  <input type="text" class="form-control"  placeholder="Enter Title" name="title">
                </div>
                <div class="form-group my-3">
                  <input type="text" class="form-control"  placeholder="Enter Author" name="Author">
                </div>
                <div class="form-group my-3">
                <textarea class="form-control" rows="5" name="desc"
                placeholder="Enter Description" style="resize: none;"></textarea>
                </div>
                <div class="mb-3">
		  <label for="file" class="form-label">Upload pdf or docx format book document</label>
        	  <input class="form-control" type="file" name="file">
		</div>
               <button type="submit" name="submit" class="btn my-3 fs-5 px-4" 
               style="background:#068a9c">Submit</button>
               <a href="#" class="btn btn-danger text-dark my-3 fs-5 px-4">Go Back</a>
           </form>
    	   </div>	
    	</div>
    </div>

Submit HTML form to "addbook.inc.php" file:

  • Once the user clicks the submit button, The form will be submitted to the "addbook.inc.php" file.
  • We have already learned how to retrieve and insert textual data into the database in our previous PHP CRUD post. This article is mainly for file upload in PHP. 
  • As a good practice, always apply a check to verify that the form is submitted properly.
  • Retrieve the data of title, author, and description in PHP Variables from $_POST array.
  • Once the file data is received from the HTML form, We can use $_FILES two-dimensional associative array to access all the necessary information related to the file we want to upload to the server. 
  •  The PHP creates $_FILES['file']['name'], $_FILES['file']['size'],  $_FILES['file']['tmp_name'], $_FILES['file']['type'] and  $_FILES['file']['error'] variables if the input name attribute is set to "file" in HTML Form. These variables are very useful when writing file upload script in php.
  • Retrieve the crucial information from $_FILES associative array into PHP variables. 
  • Create an array $extensions to store extensions of all file formats you want to allow on your website. In our case, we want to allow pdf and Docx file formats. 
  •  Use PHP explode() function to get the extension of the uploading file.
  • Use strtolower() function to convert the extension to lower case.
See the working code and understand the concepts in detail.

<?php 
require "db.inc.php";
session_start();
    if(isset($_POST['submit'])){

	$title = mysqli_real_escape_string($conn, $_POST["title"]);
	$Author = mysqli_real_escape_string($conn, $_POST["Author"]);
	$desc = mysqli_real_escape_string($conn, $_POST["desc"]);
	$date = mysqli_real_escape_string($conn, date("l jS \of F Y h:i:s A"));
	$user_id = $_SESSION["id"];
		//file data
	$file_name = $_FILES['file']['name'];
	$file_size = $_FILES['file']['size'];
        $file_tmp = $_FILES['file']['tmp_name'];
	$file_type = $_FILES['file']['type'];

	    //file upload code starts here 

	$extensions= array("docx","pdf");
	$FileExt = explode('.',$file_name);
        $FileActualExt = strtolower(end( $FileExt));

    }else{
	die("error while submiting the form");
     }

Apply server-side validation:

  • Apply server-side validation on the title, author, and description to check if they are not empty() and properly entered by the user.
  • Apply validations on file also to avoid irrelevant and unwanted file uploads.
  • Apply validation to check if the file format is correct using PHP in_array() function. This function compares the file extension with the allowed file extensions available in $extensions array.
  • Also, apply restrictions on file size and do not allow the upload of files greater than 10MB. 10MB is equal to 10000000bytes. 
Now let's see the working code of all the above-stated validations.

<?php
    //Server side file validation//
    if(empty($file_name)){ header("location: ../addbook.php?error=FileEmpty"); exit();     } if(in_array($FileActualExt,$extensions)=== false){ header("location: ../addbook.php?error=InvalidFileFormat"); exit(); } if($file_size > 10000000) { header("location: ../addbook.php?error=InvalidFileSize"); exit(); }     //Server side validation for title author and description//     if(empty($title) && empty($Author) && empty($desc) ){ header("location: ../addbook.php?error=AllInputsEmpty"); exit();     }     
    if(empty($title)){
	header("location: ../addbook.php?error=EmptyTitle");
	exit();
	}
    if(empty($Author)){
	header("location: ../addbook.php?error=EmptyAuthor");
	exit();
	}
    if(empty($desc)){
	header("location: ../addbook.php?error=EmptyDesc");
	exit();
	}

    if(str_word_count($desc)<20){
	header("location: ../addbook.php?error=InvalidDesc");
	exit();
    }
	

Upload file to the server:

  • First of all, create a unique name for the uploading file. Use PHP rand() function to generate a random number. In our case, the name is composed of user_id, random number, and the file extension. 
  • You can use your own logic to create a new name for the file but the file extension must be included in the new name.
  • Now use PHP move_uploaded_file() function to upload the file to the server. This function moves the file to our specified destination. It ensures that the uploaded file is valid and then moves it to the new location.
  • Now execute the insert query to insert the new name of the file into the database. It will insert the data of the title, author, and description as well.
  • As a good practice, always check if the query is successfully executed. Use die() function in case of failure and in case of success, redirect the user to "addbook.php". 
see the working code example to understand things better.

<?php

//uplaoding file & executing query to insert data
	if(empty($errors)==true) {
           
      	$FileNewName = $user_id.rand(1000, 9999).".".$FileActualExt;
      
        move_uploaded_file($file_tmp,'../uploads/'.$FileNewName);

        $query ="INSERT INTO `book`(`user_id`, `title`, `Author`,`description`,`date`,`filename` ) 
		VALUES ($user_id,'$title','$Author','$desc','$date','$FileNewName')";

	if(mysqli_query($conn, $query)){

	    header("location: ../addbook.php?error=success");
	}else{
			
	    die("error while executing the query". mysqli_error($conn));
			
	}
      
    }

mysqli_close($conn);

?>

Hurrah! Our file upload in PHP is completed now. 

File upload in php


Let's print proper alert messages for all our server-side validations.

Print proper alert messages for users:

  • Now in the final part of the article, print proper alert messages according to the errors received in the $_GET variable.
  • Write the PHP script under the form tag to display errors below the form.
  • Use bootstrap "alert alert-danger" class to create a properly styled red color alert.
  • Use bootstrap "alert alert-success" class to generate a green color success message.
Now see the working code and understand it in detail.

<!--Displaying error messages Using Get variable "error"-->
<?php
    if(isset($_GET["error"])){
		
	if($_GET["error"]=="AllInputsEmpty"){

        	echo "
	    	<p class='alert alert-danger'>
	    	Warning! All input Fields are Empty.
	    	</p>
	    	";
	 }

	if($_GET["error"]=="EmptyTitle"){

		echo "
		<p class='alert alert-danger'>
	 	Warning! Title can not be empty.
	        </p>
	        ";
	 }

	if($_GET["error"]=="EmptyAuthor"){

	        echo "
		<p class='alert alert-danger'>
	        Warning! Author name can not be empty.
	        </p>
	        ";
	 }

	if($_GET["error"]=="EmptyDesc"){

		echo "
		<p class='alert alert-danger'>	
	        Warning! Description can not be empty.
	        </p>
	         ";
	 }

	if($_GET["error"]=="InvalidDesc"){

	        echo "
	        <p class='alert alert-danger'>
	        Warning! Description is too short.Min 20 words required.
	        </p>
	        ";

	 }

	 if($_GET["error"]=="success"){

		echo "
		<p class='alert alert-success'>
	        Book Added successfully.
	        </p>
	        ";
			    	
				  }

          if($_GET["error"]=="InvalidFileFormat"){

	        echo "
	        <p class='alert alert-danger'>
	        Warning! Invalid file format. Upload only pdf or docx file.
	        </p>
	        ";
			    	
	}
	
         if($_GET["error"]=="InvalidFileSize"){

	        echo "
	        <p class='alert alert-success'>
		Warning! File size too big.
	        </p>
	        ";
			    	
	  }

          if($_GET["error"]=="FileEmpty"){

		echo "
		<p class='alert alert-danger'>
	        Warning! File field can not be empty.
	        </p>
		";
			    	
	  }

				  
        }

?>

The article is completed here and we have successfully uploaded the file to the server and store its name in the database. Now lets the complete code at once. It will make it easy to understand the code in sequence. 

Html + PHP code"addbook.php":

<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />

        <title>Add Book</title>
        <style type="text/css">
            .navbar {
                background: -webkit-linear-gradient(to right, #5bc0de, #fff);
                background: linear-gradient(to right, #5bc0de, #fff);
            }
            .col-6 {
                margin-top: 5%;
                background: -webkit-linear-gradient(to right, #5bc0de, #fff);
                background: linear-gradient(to right, #5bc0de, #fff);
            }
        </style>
    </head>
    <body>
        <!--Starts Here NavBar-->
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container-fluid">
                <a class="navbar-brand" href="#"><h3>My Library</h3></a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                    <div class="navbar-nav ms-auto mb-2 mb-lg-0">
                        <a class="nav-link" href="#"><?php echo "Hello! ".$_SESSION['name'] ?></a>
                        <a class="nav-link" href="includes/logout.inc.php">Log out</a>
                    </div>
                </div>
            </div>
        </nav>

        <!--Addbook form container-->
        <div class="container-fluid">
            <div class="row justify-content-center">
                <div class="col-6 text-center mb-5 py-5 px-5">
                    <h1 class="text-center mb-5 text-dark">Add books and Spread Knowledge</h1>
                    <form method="POST" action="includes/addbook.inc.php" enctype="multipart/form-data">
                        <div class="form-group my-3">
                            <input type="text" class="form-control" placeholder="Enter Title" name="title" />
                        </div>
                        <div class="form-group my-3">
                            <input type="text" class="form-control" placeholder="Enter Author" name="Author" />
                        </div>
                        <div class="form-group my-3">
                            <textarea class="form-control" rows="5" name="desc" placeholder="Enter Description" style="resize: none;"></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="file" class="form-label">Upload pdf or docx format book document</label>
                            <input class="form-control" type="file" name="file" />
                        </div>
                        <button type="submit" name="submit" class="btn my-3 fs-5 px-4" style="background: #068a9c;">Submit</button>
                        <a href="#" class="btn btn-danger text-dark my-3 fs-5 px-4">Go Back</a>
                    </form>

    <!--Displaying error messages Using Get variable "error"-->
  <?php
    if(isset($_GET["error"])){
		
	if($_GET["error"]=="AllInputsEmpty"){

        	echo "
	    	<p class='alert alert-danger'>
	    	Warning! All input Fields are Empty.
	    	</p>
	    	";
	 }

	if($_GET["error"]=="EmptyTitle"){

		echo "
		<p class='alert alert-danger'>
	 	Warning! Title can not be empty.
	        </p>
	        ";
	 }

	if($_GET["error"]=="EmptyAuthor"){

	        echo "
		<p class='alert alert-danger'>
	        Warning! Author name can not be empty.
	        </p>
	        ";
	 }

	if($_GET["error"]=="EmptyDesc"){

		echo "
		<p class='alert alert-danger'>	
	        Warning! Description can not be empty.
	        </p>
	         ";
	 }

	if($_GET["error"]=="InvalidDesc"){

	        echo "
	        <p class='alert alert-danger'>
	        Warning! Description is too short.Min 20 words required.
	        </p>
	        ";

	 }

	 if($_GET["error"]=="success"){

		echo "
		<p class='alert alert-success'>
	        Book Added successfully.
	        </p>
	        ";
			    	
				  }

          if($_GET["error"]=="InvalidFileFormat"){

	        echo "
	        <p class='alert alert-danger'>
	        Warning! Invalid file format. Upload only pdf or docx file.
	        </p>
	        ";
			    	
	}
	
         if($_GET["error"]=="InvalidFileSize"){

	        echo "
	        <p class='alert alert-success'>
		Warning! File size too big.
	        </p>
	        ";
			    	
	  }

          if($_GET["error"]=="FileEmpty"){

		echo "
		<p class='alert alert-danger'>
	        Warning! File field can not be empty.
	        </p>
		";
			    	
	  }

				  
        }

?>
</div> </div> </div> <!--Starts Here Footer--> <footer class="text-center text-dark border-top"> <!-- Copyright --> <div class="text-center p-3"> © 2020 Copyright: <a href="www.Programmopedia.com">programmopedia.com</a> </div> <!-- Copyright --> </footer> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>


Pure Php code "addbook.inc.php":


<?php
require "db.inc.php";
session_start();
if (isset($_POST['submit'])) {
    $title = mysqli_real_escape_string($conn, $_POST["title"]);
    $Author = mysqli_real_escape_string($conn, $_POST["Author"]);
    $desc = mysqli_real_escape_string($conn, $_POST["desc"]);
    $date = mysqli_real_escape_string($conn, date("l jS \of F Y h:i:s A"));
    $user_id = $_SESSION["id"];
    //file data
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_type = $_FILES['file']['type'];

    //file upload code starts here

    $extensions = ["docx", "pdf"];
    $FileExt = explode('.', $file_name);
    $FileActualExt = strtolower(end($FileExt));

    if (empty($file_name)) {
        header("location: ../addbook.php?error=FileEmpty");
        exit();
    }

    if (in_array($FileActualExt, $extensions) === false) {
        header("location: ../addbook.php?error=InvalidFileFormat");
        exit();
    }

    if ($file_size > 10000000) {
        header("location: ../addbook.php?error=InvalidFileSize");
        exit();
    }

    //Server side validation//
    if (empty($title) && empty($Author) && empty($desc)) {
        header("location: ../addbook.php?error=AllInputsEmpty");
        exit();
    }
    if (empty($title)) {
        header("location: ../addbook.php?error=EmptyTitle");
        exit();
    }
    if (empty($Author)) {
        header("location: ../addbook.php?error=EmptyAuthor");
        exit();
    }
    if (empty($desc)) {
        header("location: ../addbook.php?error=EmptyDesc");
        exit();
    }

    if (str_word_count($desc) < 20) {
        header("location: ../addbook.php?error=InvalidDesc");
        exit();
    }

    //uplaoding file & executing query to insert data
    if (empty($errors) == true) {
        $FileNewName = $user_id . rand(1000, 9999) . "." . $FileActualExt;

        move_uploaded_file($file_tmp, '../uploads/' . $FileNewName);

        $query = "INSERT INTO `book`(`user_id`, `title`, `Author`,`description`,`date`,`filename` ) 
   	VALUES ($user_id,'$title','$Author','$desc','$date','$FileNewName')";

        if (mysqli_query($conn, $query)) {
            header("location: ../addbook.php?error=success");
        } else {
            die("error while executing the query" . mysqli_error($conn));
        }
    }
} else {
    die("error while submiting the form");
}

mysqli_close($conn);

?>

In this article, we learned about file upload in PHP which is also a part of PHP CRUD. We will meet again in the next article with new useful information. Keep reading and supporting us.


Post a Comment

0 Comments