PHP File() Handling & Functions

โšก Smart Summary

File Processing in PHP uses a rich set of built-in functions to create, read, write, copy, and delete files on the server. This walkthrough covers file_exists, fopen and its modes, fwrite, fclose, fgets, copy, unlink, and file_get_contents with practical examples.

  • ๐Ÿ“„ What Files Store: Files hold configuration settings, logs, and simple data, giving a cheap permanent storage option compared with a database.
  • ๐Ÿ” Checking Files: file_exists() confirms whether a file is present before you read from or create it, avoiding errors.
  • ๐Ÿ“‚ Opening Files: fopen() opens a file in a mode such as r, w, or a, which controls reading, writing, and appending.
  • โœ๏ธ Writing and Closing: fwrite() sends data to the file handle, and fclose() releases the handle when the work is done.
  • ๐Ÿ“– Reading Files: fgets() reads one line at a time, while file_get_contents() returns the whole file as a single string.
  • ๐Ÿ—‚๏ธ Copy and Delete: copy() duplicates a file to a new path, and unlink() permanently deletes a file from the server.
  • ๐Ÿค– AI Assist: AI tools can generate file parsing code and resolve permission or failed to open stream errors quickly.

PHP File Processing

What is a File?

A file is simply a resource for storing information on a computer.

Files are usually used to store information such as:

  • Configuration settings of a program
  • Simple data such as contact names against phone numbers.
  • Images, pictures, photos, and similar media.

PHP File Formats Support

PHP file functions support a wide range of file formats that include:

  • File.txt
  • File.log
  • File.custom_extension, i.e. file.xyz
  • File.csv
  • File.gif, file.jpg, and similar image formats

Files are useful in several situations:

  • They provide a permanent, cost-effective data storage solution for simple data, compared to databases that require other software and skills to manage DBMS systems.
  • You want to store simple data such as server logs for later retrieval and analysis.
  • You want to store program settings, i.e. program.ini

PHP File Functions

PHP provides a convenient way of working with files via its rich collection of built-in functions.

Operating systems such as Windows and macOS are not case sensitive, while Linux or Unix operating systems are case sensitive.

Adopting a naming convention such as lower case letters only for file naming is a good practice that ensures maximum cross platform compatibility.

Let us now look at some of the most commonly used PHP file functions.

PHP file_exists() Function

This function is used to determine whether a file exists or not.

  • It comes in handy when we want to know if a file exists before processing it.
  • You can also use this function when creating a new file and you want to ensure that the file does not already exist on the server.

The file_exists function has the following syntax.

<?php
file_exists($filename);
?>

HERE,

  • “file_exists()” is the PHP function that returns true if the file exists and false if it does not exist.
  • “$filename” is the path and name of the file to be checked

The code below uses the file_exists function to determine if the file my_settings.txt exists.

<?php
if (file_exists('my_settings.txt'))
{
echo 'file found!';
}
else
{
echo 'my_settings.txt does not exist';
}
?>

Save the above code in a file named file_function.php. Assuming you saved the file in the phptuts folder in htdocs, open the URL http://localhost/phptuts/file_function.php in your browser. You will get the following results.

PHP file_exists() Function

PHP fopen() Function

The fopen function is used to open files. It has the following syntax.

<?php
fopen($file_name,$mode,$use_include_path,$context);
?>

HERE,

  • “fopen” is the PHP open file function
  • “$file_name” is the name of the file to be opened
  • “$mode” is the mode in which the file should be opened. The table below shows the modes.
Mode Description
r • Read file from beginning.
• Returns false if the file does not exist.
• Read only
r+ • Read file from beginning
• Returns false if the file does not exist.
• Read and write
w • Write to file at beginning
• Truncate file to zero length
• If the file does not exist, attempt to create it.
• Write only
w+ • Write to file at beginning, truncate file to zero length
• If the file does not exist, attempt to create it.
• Read and write
a • Append to file at end
• If the file does not exist, attempt to create it.
• Write only
a+ • Append to file at end
• If the file does not exist, attempt to create it
• Read and write
  • “$use_include_path” is optional, default is false. If set to true, the function searches in the include path too.
  • “$context” is optional and can be used to specify the context support.

PHP fwrite() Function

The fwrite function is used to write to files.

It has the following syntax.

<?php
fwrite($handle, $string, $length);
?>

HERE,

  • “fwrite” is the PHP function for writing to files
  • “$handle” is the file pointer resource
  • “$string” is the data to be written to the file.
  • “$length” is optional and can be used to specify the maximum file length.

PHP fclose() Function

The fclose() function is used to close a file in PHP that is already open.

It has the following syntax.

<?php
fclose($handle);
?>

HERE,

  • “fclose” is the PHP function for closing an open file
  • “$handle” is the file pointer resource.

Let us now look at an example that creates my_settings.txt. We will use the fopen, fwrite, and fclose functions.

The code below “create_my_settings_file.php” implements the above example.

Open a file
<?php

$fh = fopen("my_settings.txt", 'w')

or

die("Failed to create file"); ?>
Closing a file
<?php

fclose($fh);

?>
Create File
<?php

$fh = fopen("my_settings.txt", 'w') or die("Failed to create file");

$text = <<<_END

localhost;root;pwd1234;my_database

_END;

fwrite($fh, $text) or die("Could not write to file");

fclose($fh);

echo "File 1 written successfully"; ?>

Testing the code

Open the URL http://localhost/phptuts/create_my_settings.php in your browser.

You will get the following page.

PHP fclose Function

Note: if your disk is full or you do not have permission to write files, you will get an error message.

Switch back to the URL http://localhost/phptuts/file_function.php. What results do you get?

PHP fgets() Function

The fgets function is used to read PHP files line by line. It has the following basic syntax.

<?php
fgets($handle);
?>

HERE,

  • “fgets” is the PHP function for reading file lines
  • “$handle” is the file pointer resource.

Let us now look at an example that reads the my_settings.txt file using the fopen and fgets functions.

The code below read_my_settings.php implements the above example.

<?php
$fh = fopen("my_settings.txt", 'r') or die("File does not exist or you lack permission to open it");
$line = fgets($fh);
echo $line; fclose($fh);
?>

HERE,

  • “fopen” function returns the pointer to the file specified in the file path
  • “die()” function is called if an error occurs. It displays a message and exits execution of the script

PHP copy() Function

The PHP copy function is used to copy files. It has the following basic syntax.

<?php
copy($file,$copied_file);
?>

HERE,

  • “$file” specifies the file path and name of the file to be copied.
  • “$copied_file” specifies the path and name of the copied file

The code below illustrates the implementation.

<?php
copy('my_settings.txt', 'my_settings_backup.txt') or die("Could not copy file");
echo "File successfully copied to 2";
?>

Deleting a file

The unlink function is used to delete a file. The code below illustrates the implementation.

<?php
if (!unlink('my_settings_backup.txt'))
{
echo "Could not delete file";
}
else
{
echo "File 1 successfully deleted";
}
?>

PHP file_get_contents() Function

The file_get_contents function is used to read the entire file contents.

The difference between file_get_contents and fgets is that file_get_contents returns the file data as a string, while fgets reads the file line by line.

The code below illustrates the implementation.

<?php
echo "<pre>"; // Enables display of line feeds
echo file_get_contents("my_settings.txt");
echo "</pre>"; // Terminates pre tag
?>

PHP File Functions Quick Reference

The table below summarizes the file functions covered in this tutorial.

Function Description
file_exists Used to determine if a file exists or not
fopen Used to open a file. Returns a pointer to the opened file
fwrite Used to write to files
fclose Used to close an open file
fgets Used to read a file line by line
copy Used to copy an existing file
unlink Used to delete an existing file
file_get_contents Used to return the contents of a file as a string

FAQs

fgets reads one line per call, fread reads a set number of bytes from an open handle, and file_get_contents reads the entire file into a string in one call without needing fopen or fclose.

fwrite writes to an open file handle and needs fopen and fclose around it. file_put_contents opens, writes, and closes the file in a single call, making it the shorter choice for simple writes.

Use is_writable(‘file.txt’) to test write permission before writing, and file_exists() to confirm the file is present. On Unix systems, chmod() can adjust permissions if the web server owns the file.

Yes. Describe the format, such as CSV, JSON, or a log layout, and AI can produce code using fgetcsv, json_decode, or a custom loop, plus error handling for missing or malformed files. Test with real data.

Yes. Share the path and error, and AI can identify a wrong relative path, a missing file, or a permissions problem, then suggest using an absolute path, creating the file, or adjusting permissions.

Summarize this post with: