Php read file from html input file

In today’s world, files are exchanged daily, especially over the internet. Websites use these files for various purposes such as user profile pictures & exchange of information among users. These range from images, videos to lớn pdf documents.

Bạn đang xem: Php read file from html input file

Introduction

In this tutorial, we will look at how lớn use HTML forms và PHP to upload files lớn a website.

Prerequisites

Before starting this tutorial, make sure you have prior knowledge on how khổng lồ create HTML forms & databases in MySQL. You can kiểm tra out a simple guide on how to lớn create forms in HTML here.

Since we will be using PHP, make sure you have installed Xampp khổng lồ help in running the PHP code. You can download it here.

NOTE: In this tutorial, we will be using Windows.

Once the installation is complete, start the Xampp control panel & activate Apache by clicking the start button as highlighted below.

*

After a few seconds, the Apache header should change to a green background to indicate the apache server is running. Kiểm tra the image below for reference.

*

Step 1 — Creating the PHP files

Navigate to C:xampphtdocs (the driver location will depend on where you installed your Xampp app) & create a new folder test.

We shall move lớn create a new tệp tin (index.php) under the test folder, this is where we will be writing all the code for this tutorial.

In the index.php file insert the following code:


To view the output of this code, head khổng lồ your browser at http://localhost/test. Here we append our folder name thử nghiệm to the base URL of our Apache server http://localhost/

From the browser, you should have something lượt thích this.

*

Step 1 — Creating the PHP logic to handle the tệp tin uploads

In the form we created above, once we click the submit button an kích hoạt seems to lớn be taking place. Although the file we choose to lớn upload seems lớn have been uploaded, we cannot locate them.

To make this form save the uploaded file on our preferred location, we will be creating a PHP script lớn handle the submission process.

There are usually two common ways of handling the above situation.

Saving a file on a table record - In this way, we save the files in a thư mục and then save the reference on the database.Saving the tệp tin directly on the database - In this way, we save the files as binary files (BLOB). However, this way is not efficient especially in situations where large files are to be uploaded. This is because it will slow the database access as records increase.Saving the tệp tin on a table record

When saving files on a table record, we follow these steps.

Create a database -> Head lớn the xampp control panel and start MySQL. Click the admin button to lớn access the phpMyAdmin dashboard; this is where we will create our database.

*
.

The admin button on the MySQL row should take you to lớn your browser & display this.

Xem thêm: Facebook Live Chat For Php, How To Add Facebook Live Chat To Your Website

Phpmyadmin dashboard

Connecting khổng lồ a database -> For this tutorial we will be using mysqli. In our index.php file , under the closing html tag lets add the following php script.

$server = 'localhost';$user = "root";$password = "";$dbname = "tutorial";$conn = mysqli_connect($server, $user, $password, $dbname) or die("could not connect to the database");?>
The code above allows us to lớn connect lớn our database. The $server variable stores the name of the vps where our database is located.

The $user và $password variables store data about the user. $password is empty in our case because in our Apache hệ thống we have not mix any. $dbname stores our database name.

We will use the $conn variable to lớn connect lớn the database. Khổng lồ ensure the connection is working we use the die function to end the connection & give us feedback in case the connection fails.

Getting the file from the form -> when a user uploads a file in our form, we need to get the file và store it in our preferred location. To lớn perform this, add a new folder inside the test thư mục and name it uploads.

This code will get the file from the forms. Insert it in our PHP script just below $conn.


if(isset($_POST<'submit'>)) $name = $_FILES<'file'><'name'>; //the directory lớn upload lớn $targetDir = "uploads/"; //the tệp tin being upload $targetFile = $targetDir.basename($\_FILES<'file'><'name'>); //select the tệp tin type - file extension $fileType = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));
We use an if statement to check whether the user has clicked the submit button. If true the file name will be stored in $name.Since we created our preferred storage location, we use $targetDir to lớn indicate where will store our file.

In some cases, we might want lớn restrict the type of files uploaded. Different files have different extensions which enable us to filter the files.

Insert the following code below $fileType.


//valid file extensions we will allow$extensions_arr= array("jpg","jpeg","png");//checking the extension of our uploaded fileif(in_array($fileType,$extensions_arr)) // Insert record $query = " INSERT into `files` (`filename`) values('$name')"; mysqli_query($conn,$query); // Upload tệp tin move_uploaded_file($_FILES<'file'><'tmp_name'>,$targetDir.$name); else echo " wrong tệp tin type ";
In this tutorial we will limit the type lớn only photos. $extensions_arr stores the tệp tin types we will allow.

Let’s check whether our file has any of the above extensions. The in_array function checks if a value exists in an array.

If it exists, we shall create a query khổng lồ insert the file’s name into our database. This acts as a reference to lớn our tệp tin which will be stored in the uploads folder.

In case the tệp tin type does not match the extensions in our array, we will return an error message using the echo function.

Retrieving the file

To retrieve the file we stored in our database, we need lớn query the database for the file’s name .

Since we only stored the tệp tin name and not the tệp tin name itself, the result from the query is matched to lớn the files in our uploads folder.


php $sql = "SELECT `filename` FROM `files` WHERE `filename`= '$name'"; $result = mysqli_query($conn,$sql); $row = mysqli_fetch_array($result); $image = $row<'filename'>; $image_src = "uploads/".$image
Since our files are images, we will địa chỉ an image tag after the closing tag of our PHP script. This code will display the image we have uploaded in our database.


php
Our final code will be as shown below.


Conclusion

That is how we handle file uploads in HTML forms with PHP. It is an easy và efficient way of handling multipart form submissions.