File Handling in PHP
File Handling in PHP
Opening a File
The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:
<?php $file=fopen("welcome.txt","r");?>
Closing a File
The fclose() function is used to close an open file:
<?php$file = fopen("test.txt","r"); //some code to be executedfclose($file);?>
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file);?>
Reading a File Character by Character
The fgetc() function is used to read a single character from a file.
The example below reads a file character by character, until the end of file is reached:
<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>
File Manipulation
There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't connect to the database. It'd be impossible to keep this information in the database, since it's not available at exactly the time you'd need to write to it. PHP provides functions for file manipulation that can perform the following:
- Check the existence of a file
- Create a file
- Append to a file
- Rename a file
- Delete a file
file_exists()
To check for the existence of a file, use the function file_exists, which takes the name of the file to check for its parameter. If the file exists, it returns TRUE; otherwise, it returns FALSE.
<?php $file_name=“abc.php"; if(file_exists($file_name)) { echo ("$file_name does exist."); } else { echo ("$file_name does not exist."); } ?>
Permissions
Now that you know a file exists, you may think you're done, but you're not. Just because it's there doesn't mean you can read, write, or execute the file. To check for these attributes, use is_readable to check for read access, is_writable to check for write access, and is_executable to check for the ability to execute the file. Each function takes a filename as its parameter.
<?php $file_name=“abc.php"; if(is_readable($file_name)) { echo ("The file $file_name is readable.<br>"); } else { echo ("The file $file_name is not readable.<br>"); } if(is_writeable($file_name)) { echo ("The file $file_name is writeable.<br>"); } else { echo ("The file $file_name is not writeable.<br>"); } if(is_executable($file_name)) { echo ("The file $file_name is executable.<br>"); } else { echo ("The file $file_name is not executable.<br>"); } ?>
Creating files
Files can be created with the touch command. This command takes a filename as its parameter. If a file doesn't already exist, it's created as an empty zero length file. If the file does exist, only its modification time is updated.
$file_name="test.txt"; touch($file_name);
Deleting files
Files can be deleted with the unlink command. This command takes a filename as its parameter. If a file exists and PHP has adequate permission, it'll delete the file.
unlink(file_name);
Moving files
To move a file, you should use the rename function. It renames files or directories and takes the old name and the new name as its parameters.
$file_name="test.txt"; $new_file_name="production.txt"; $status=rename($file_name,$new_file_name);
if ($status) { echo ("Renamed file."); }
File Upload
With PHP, it is possible to upload files to the server.
We need:
- The Upload-File Form
- The Upload Script
Upload-File Form
<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
File Upload
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
- $_FILES["file"]["name"] - the name of the uploaded file
- $_FILES["file"]["type"] - the type of the uploaded file
- $_FILES["file"]["size"] - the size in bytes of the uploaded file
- $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
- $_FILES["file"]["error"] - the error code resulting from the file upload
- This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.
The Upload Script
if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; }
if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; }
In this way we can store the file in a desired location. This is very basic and traditional way to upload the file. For for understanding it is useful.
Comments (0)
Leave a comment
Related Blogs
Introduction to Kibana
Aug 1, 2020, 6:19:45 PM | Anurag Srivastava
Bucket Aggregation in Elasticsearch
Aug 29, 2018, 7:15:06 PM | Anurag Srivastava
Metrics Aggregations in Elasticsearch
Aug 18, 2018, 6:02:20 PM | Anurag Srivastava
Introduction to Elasticsearch Aggregations
Aug 14, 2018, 4:47:56 PM | Anurag Srivastava
Wildcard and Boolean Search in Elasticsearch
Aug 10, 2018, 7:14:40 PM | Anurag Srivastava
Basics of Data Search in Elasticsearch
Aug 4, 2018, 7:02:21 AM | Anurag Srivastava
Top Blogs
Wildcard and Boolean Search in Elasticsearch
Aug 10, 2018, 7:14:40 PM | Anurag Srivastava
Elasticsearch REST APIs
Jul 31, 2018, 6:16:42 PM | Anurag Srivastava
How to count number of words in a HTML string and find Read time in Python 3
Jun 30, 2018, 12:07:47 PM | jitender yadav
Create a Chess board in PHP
Mar 9, 2020, 8:45:41 AM | Rocky Paul
Bucket Aggregation in Elasticsearch
Aug 29, 2018, 7:15:06 PM | Anurag Srivastava
Metrics Aggregations in Elasticsearch
Aug 18, 2018, 6:02:20 PM | Anurag Srivastava