PHP / PHP File Handling

Reading and Writing Files in PHP

This tutorial will guide you through the process of reading and writing files in PHP. We will cover different ways to read from and write to files, and show you how to handle comm…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers reading, writing, and manipulating files using PHP.

Introduction

In this tutorial, we will learn how to read from and write to files using PHP, which is a critical part of almost any web-based application. By the end of this tutorial, you will be able to manipulate file data in your PHP applications.

Prerequisites:
- Basic knowledge of PHP syntax
- Familiarity with running PHP in a local development environment

Step-by-Step Guide

There are several ways to handle files in PHP. The most common methods are fopen(), fwrite(), and fclose().

  • fopen() function is used to open a file
  • fwrite() is used to write data to a file
  • fclose() is used to close an open file

Best practices and tips:
Always remember to close any files that you have opened. Leaving files open could lead to memory leaks or other problems.

Code Examples

Example 1: Writing to a File

<?php
$file = fopen("testfile.txt", "w");  // Open a file for writing

if( $file == false ) {
   echo ( "Error in opening new file" );
   exit();
}

fwrite( $file, "This is  a simple test\n" );  // Write data to the file
fclose( $file );  // Close the file
?>

In this example, we open a file named "testfile.txt" for writing. If the file cannot be opened, an error message is displayed and the script exits. We then write some data to the file and finally, close the file.

Example 2: Reading from a File

<?php
$file = fopen("testfile.txt", 'r'); // Open the file for reading

if( $file == false ) {
   echo ( "Error in opening file" );
   exit();
}

$filesize = filesize( "testfile.txt" );
$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

In this example, we open the "testfile.txt" file for reading. If the file cannot be opened, an error message is displayed and the script exits. We then read the entire file into a string using fread(). Finally, we close the file and print out the contents.

Summary

In this tutorial, we've learned how to read from and write to files in PHP. We've covered the basic functions used in file handling and shown you how to handle common errors.

Practice Exercises

  1. Exercise: Write a PHP script that opens a file, writes your name in it, then closes it.
  2. Exercise: Write a PHP script that opens the file from exercise 1 and reads the content.

Solutions:

  1. Writing to a file:
<?php
$file = fopen("myfile.txt", "w");

if( $file == false ) {
   echo ( "Error in opening new file" );
   exit();
}

fwrite( $file, "Your Name" ); 
fclose( $file );
?>
  1. Reading from a file:
<?php
$file = fopen("myfile.txt", 'r');

if( $file == false ) {
   echo ( "Error in opening file" );
   exit();
}

$filesize = filesize( "myfile.txt" );
$filetext = fread( $file, $filesize );
fclose( $file );

echo ( "<pre>$filetext</pre>" );
?>

For further practice, try writing and reading different kinds of data, like CSV or JSON data. See if you can parse this data into a useful format.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help