---
title: "Read and Write file in PHP"  
description: "From PHP you are able to open up a file on your server and write to it. If the file does not exist then we can create it, however if the file already"  
author: "Anonymous User"  
published: 2011-11-30  
updated: 2014-09-18  
canonical: https://www.mindstick.com/blog/269/read-and-write-file-in-php  
category: "php"  
tags: ["php"]  
reading_time: 1 minute  

---

# Read and Write file in PHP

##### Write to File from PHP:

From PHP you are able to open up a [file on your](https://answers.mindstick.com/qa/93841/what-is-the-best-possible-way-to-attach-link-a-bootstrap-file-on-your-project-describe-it-with-a-reason) [server](https://www.mindstick.com/articles/43769/what-is-serverless-architecture-is-it-worth-switching-over) and write to it. If the file does not exist then we can create it, however if the file [already exists](https://www.mindstick.com/forum/34205/emailid-already-exists) then you [must](https://www.mindstick.com/articles/12978/top-reasons-why-every-magento-ecommerce-store-must-opt-for-mobile-app) open in append mode so it will be writable. When [writing](https://www.mindstick.com/articles/12997/5-essential-tips-on-resume-writing-for-business-analysts) to a file, the first thing you need to do is to open up the file. We do that with this code:

```
 <?php                  // Store file name                     $fileName = "YourFile.php";                    // Open the file                    $handle = fopen($fileName, 'w');                    // Write the file                     fwrite($handle, "Your String Value");
                    // After successfuly wrting close the file                    fclose($handle);            ?>
```

##### Read a File from PHP:

[Reading](https://www.mindstick.com/articles/126273/books-commonly-found-on-college-reading-lists) a file is even easier. You could go through the fopen() [method](https://www.mindstick.com/forum/166/webservice-method) but I'm going to show you an easier way:

```
<?php                // Store file name                     $fileName = "YourFile.php";                // Read the file content                    $fileText = file_get_contents($fileName);                       ?>
```

Note: If you opened the file using fopen() method then you have to [close](https://yourviews.mindstick.com/story/1687/rubbing-hands-close-up-benefits) it using fclose().

---

Original Source: https://www.mindstick.com/blog/269/read-and-write-file-in-php

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
