How to Open and Read a File in PHP

In order to open and read a file through code in PHP, the first thing you need to do is find a place to upload the file. This is where the user will select the file location, upload and then save it. You can open the file, read it and do whatever you want to do with the provided data in the file.

In order to make a file uploader, put the following code in your HTML form:

After the file is uploaded and form is submitted, you would like to open the file and read the content provided in it.

The above code will open the file in read mode. First of all it checks that file is uploaded. If it is uploaded, then will open it in read mode using $handle = fopen($temp_file,”r”);.

Once the file is opened, you can extract its data the way you want and use it for your purposes. This might include importing some records from a CSV file. In that case, you can read it row by row for each column and populate the tables in your database. Here is an example:

The above code will run on your CSV file reading it row by row and assigning first three columns of each row with a variable. You can then use the code to achieve your target with this provided data in file.

In the end make sure that you close the file using the following code:

User Comments

Leave a Reply

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

Get in Touch