How to Open, Read, Write and Delete a file in PHP

Here I’ll show you the basic file handling techniques in PHP, if you didn’t know, it’s possible to access and modify files from your PHP script and it’s easy too.

Open a File

$some_file = 'the_file.txt'; if ( false == fopen($some_file, 'w') ) die('Unable to open ' . $some_file);

The preceding example will create the file if it does not exist.

Read a File

$some_file = 'the_file.txt'; $handle = fopen($some_file, 'r'); $read_file = fread($handle, filesize($some_file));

Write to a File

$some_file = 'the_file.txt'; $handle = fopen($some_file, 'w') or die('Unable to open ' . $some_file); $data = 'Write this text to file'; fwrite($handle, $data);

Delete a File

$some_file = 'the_file.txt'; unlink($some_file);

If you’re wondering what the ‘r’ and ‘w’ parameters in the fopen() function does, they are the mode that specify the type of access you require.

r = Open for reading only.

w = Open for writing only.

There are other modes that you can use, read about them on the PHP manual.

And my job here is done.

Originally published at on January 29, 2016.

Show your support

Clapping shows how much you appreciated Deon Dazy’s story.