---
description: PHP provides a convenient way of working with files via its rich collection of built in functions. Most commonly used PHP file functions are File_exists, Fopen, Fwrite, Fclose, Fgets, Copy, Deleting, File_get_contents
title: PHP File() Handling &#038; Functions
image: https://www.guru99.com/images/php-file-handling-functions.png
---

 

[Skip to content](#main) 

**⚡ 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.

[ Read More ](javascript:void%280%29;) 

![PHP File Processing](https://www.guru99.com/images/php-file-handling-functions.png)

## 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](https://www.guru99.com/unix-linux-tutorial.html) or [Unix](https://www.guru99.com/unix-linux-tutorial.html) 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.

[](https://www.guru99.com/images/2013/04/file%5Fexists.png)

## 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.

### RELATED ARTICLES

* [PHP XML Tutorial: Create, Parse, Read with Example ](https://www.guru99.com/php-and-xml.html "PHP XML Tutorial: Create, Parse, Read with Example")
* [PHP Session & PHP Cookies with Example ](https://www.guru99.com/cookies-and-sessions.html "PHP Session & PHP Cookies with Example")
* [PHP Loop: For, ForEach, While, Do While \[Example\] ](https://www.guru99.com/php-loop.html "PHP Loop: For, ForEach, While, Do While [Example]")
* [Top 91 Laravel Interview Questions and Answers (2026) ](https://www.guru99.com/laravel-interview-questions.html "Top 91 Laravel Interview Questions and Answers (2026)")

## 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](https://www.guru99.com/functions-in-php.html) 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.

[](https://www.guru99.com/images/2013/04/write%5Ffile.png)

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

📖 What is the difference between fgets, fread, and file\_get\_contents?

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.

✍️ What is the difference between fwrite and file\_put\_contents?

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.

🔒 How do I check if a file is writable in PHP?

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.

🤖 Can AI generate PHP code to read and parse a data 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.

🤖 Can AI fix a PHP failed to open stream file error?

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:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/php-file-handling-functions.png","url":"https://www.guru99.com/images/php-file-handling-functions.png","width":"700","height":"250","caption":"PHP File() Handling &amp; Functions","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/php-file-processing.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/php","name":"PHP"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/php-file-processing.html","name":"PHP File() Handling &#038; Functions"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/php-file-processing.html#webpage","url":"https://www.guru99.com/php-file-processing.html","name":"PHP File() Handling &#038; Functions","dateModified":"2026-07-25T11:58:29+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/php-file-handling-functions.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/php-file-processing.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/fiona","name":"Fiona Brown","description":"I'm Fiona brown, a Full Stack Developer with over a decade of experience, sharing practical guides on robust and scalable application development.","url":"https://www.guru99.com/author/fiona","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/fiona-brown-author.png","url":"https://www.guru99.com/images/fiona-brown-author.png","caption":"Fiona Brown","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"PHP","headline":"PHP File() Handling &#038; Functions","description":"PHP provides a convenient way of working with files via its rich collection of built in functions. Most commonly used PHP file functions are File_exists, Fopen, Fwrite, Fclose, Fgets, Copy, Deleting, File_get_contents","keywords":"php","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/fiona","name":"Fiona Brown"},"dateModified":"2026-07-25T11:58:29+05:30","image":{"@id":"https://www.guru99.com/images/php-file-handling-functions.png"},"copyrightYear":"2026","name":"PHP File() Handling &#038; Functions","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between fgets, fread, and file_get_contents?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What is the difference between fwrite and file_put_contents?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How do I check if a file is writable in PHP?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can AI generate PHP code to read and parse a data file?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can AI fix a PHP failed to open stream file error?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}],"@id":"https://www.guru99.com/php-file-processing.html#schema-1150206","isPartOf":{"@id":"https://www.guru99.com/php-file-processing.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/php-file-processing.html#webpage"}}]}
```
