Skip to main content

PHP File Handling

By SamK
0
0 recommends
Topic(s)

In this tutorial, you'll learn how to handle files in PHP.

PHP provides multiple functions for reading, creating, uploading, and modifying files.

readfile() Function

The readfile() function reads a file and outputs its contents to the buffer.

Suppose we have a file named file.txt" stored on the server, having contents "This is a text file". 

The PHP code to read that file will be:

<?php
readfile("file.txt");
?>

/*
Output:
This is a text file
*/

fopen() Function

Another way to open files is by using the fopen() function, which offers more options compared to the readfile() function.

The first parameter of the fopen() function specifies the name of the file to be opened, while the second parameter determines the mode in which the file should be opened. 

Example:

<?php
$testfile = fopen("file.txt", "r"); // r: read mode
?>

The file can be opened in one of the following modes.

r - Reading only. Reads from the beginning.
w - Writing only. Existing contents are erased or a new file is created if it doesn’t exist.
a - Writing only. Existing data is preserved or a new file is created if it doesn’t exist. The file pointer starts at the end of the file.
x - Create a new file for writing only if it doesn't exists.
r+ - Reading and writing. The file pointer starts at the beginning of the file.
w+ - Reading and writing. Existing contents are erased or a new file is created if it doesn’t exist.
a+ - Reading and writing. Existing data is preserved or a new file is created if it doesn’t exist. The file pointer starts at the end of the file.
x+ - Reading and writing, only if the file doesn't exist.

The fopen() function in PHP can be used not only to open files but also to create them. If you attempt to open a file that doesn’t exist and specify a mode that allows writing or appending, such as "w" (write) or "a" (append), PHP will create the file automatically.

In the following example, a new file called "examplefile.txt" is created in the same directory as the PHP script.

<?php
$testfile = fopen("examplefile.txt", "w")
?>

PHP File Permissions

If you encounter errors while trying to run this code, ensure that your PHP script has the necessary permissions to write to the hard drive. Without proper write access, the file creation process will fail.

Read File - fread()

The fread() function reads data from an open file.

The first parameter of fread() is the file handle, while the second parameter specifies the maximum number of bytes to read.

The following PHP code reads the contents of the "file.txt" file until the end, because the filesize() function specifies the total number of bytes in a file.

<?php
fread($testfile,filesize("file.txt"));
?>

Close File - fclose()

The fclose() function is utilized to terminate access to a file that has been previously opened.

It's a good practice in programming to close files once you're done with them, because leaving a file open can unnecessarily consume resources on your server!

<?php
$testfile = fopen("file.txt", "r");
// some code....
fclose($testfile);
?>

Read Single Line - fgets()

The fgets() function is used to read one line from a file.

In the example below, it displays the first line from the "file.txt" file.

<?php
$testfile = fopen("file.txt", "r");
echo fgets($testfile);
fclose($testfile);
?>

Note: After a call to the fgets() function, the file pointer moves to the next line.

Check End-Of-File - feof()

The feof() function checks whether the "end-of-file" (EOF) has been reached.

It is particularly useful when looping through data of an unknown length.

In the example below, the "file.txt" file is read line by line until the end of the file is reached.

<?php
$testfile = fopen("file.txt", "r");
// Output one line until end-of-file
while(!feof($testfile)) {
  echo fgets($testfile) . "<br>";
}
fclose($testfile);
?>

Read Single Character - fgetc()

The fgetc() function is used to read one character at a time from a file.

In the example below, it reads the "file.txt" file character by character until the end of the file is reached.

<?php
$testfile = fopen("file.txt", "r");
// Output one character until end-of-file
while(!feof($testfile)) {
  echo fgetc($testfile);
}
fclose($testfile);
?>

Note: Each time the fgetc() function is called, the file pointer advances to the next character.

Write to File - fwrite()

The fwrite() function is used to write data to a file.

It takes two parameters: the first is the file pointer (the file to write to), and the second is the string to be written.

In the following example, multiple lines are written to a new file called "file.txt":

<?php
// Open the file in write mode. If it doesn't exist, it will be created.
$testfile = fopen("file.txt", "w");

// Write multiple lines to the file
$lines = ["This is line 1.", "This is line 2."];
foreach ($lines as $line) {
    fwrite($testfile, $line . "\n");
}

// Close the file after writing
fclose($testfile);

// Reopen the file in read mode to check/print its contents
$testfile = fopen("file.txt", "r");
echo fread($testfile, filesize("file.txt"));

// Close the file after reading
fclose($testfile);

/*
Output:
This is line 1.
This is line 2.
*/
?>

Notice that we wrote to the file "file.txt" twice. The first time, we wrote the string "This is line one.," and the second time, we wrote "This is line two."

File Overwriting

When we open an already existing file for writing, the existing content will be completely erased, and the file will be cleared, leaving it empty and ready for new data.

Example:

<?php
// Open the file in write mode. If it doesn't exist, it will be created.
$testfile = fopen("file.txt", "w");

// Write multiple lines to the file
$lines = ["This is line 3.", "This is line 4."];
foreach ($lines as $line) {
    fwrite($testfile, $line . "\n");
}

// Close the file after writing
fclose($testfile);

// Reopen the file in read mode to check/print its contents
$testfile = fopen("file.txt", "r");
echo fread($testfile, filesize("file.txt"));

// Close the file after reading
fclose($testfile);

/*
Output:
This is line 3.
This is line 4.
*/
?>

PHP Append Text

To add data to an existing file without erasing the current content, you can use the "a" mode. This mode appends new text to the end of the file instead of overwriting.

Example:

<?php
// Open the file in write mode. If it doesn't exist, it will be created.
$testfile = fopen("file.txt", "a");

// Write multiple lines to the file
$lines = ["This is line 3.", "This is line 4."];
foreach ($lines as $line) {
    fwrite($testfile, $line . "\n");
}

// Close the file after writing
fclose($testfile);

// Reopen the file in read mode to check/print its contents
$testfile = fopen("file.txt", "r");
echo fread($testfile, filesize("file.txt"));

// Close the file after reading
fclose($testfile);

/*
Output:
This is line 1.
This is line 2.
This is line 3.
This is line 4.
*/
?>

Uploading Files in PHP

Uploading files to the server using PHP is straightforward, but it comes with risks. It's important to exercise caution whenever file uploads are permitted.

Here is how you can setup a basic script to uploads files on a server.

Configure The "php.ini" File

First, make sure PHP is set up to allow file uploads. In your "php.ini" file, locate the file_uploads directive and set it to On.

file_uploads = On

Create The HTML Form

Next, build an HTML form that allows files selection and uploading.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>

<form action="file_upload.php" method="post" enctype="multipart/form-data">
    <label for="fileUpload">Select File:</label>
    <input type="file" name="fileUpload" id="fileUpload" required>
    <button type="submit" name="submit">Upload</button>
</form>

</body>
</html>

Form requirements:

  • Ensure the form uses method="post" for proper data submission.
  • The form must also include the enctype="multipart/form-data" attribute. This specifies the content type to be used when submitting the form.
  • The input tag should have the type="file" attribute.

The above form will send the uploaded file data to a script named "file_upload.php", which we will create next.

Create a PHP Script

The "file_upload.php" file for handling file uploads, with improvements for security, structure, and readability:

<?php
// Define the target directory for uploads
$targetDir = "uploads/";
// Set the full target file path
$targetFile = $targetDir . basename($_FILES["fileUpload"]["name"]);
// Variable to track if the upload is allowed
$allow_upload = 1;
// Get the file extension in lowercase
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if the form was submitted
if (isset($_POST["submit"])) {
    // Check if the file was uploaded without errors
    if (is_uploaded_file($_FILES["fileUpload"]["tmp_name"])) {
        echo "File is valid and uploaded.<br>";
        $allow_upload = 1;
    } else {
        echo "No file was uploaded or an error occurred.<br>";
        $allow_upload = 0;
    }

    // Optionally, check for allowed file extensions
    $allowedTypes = ['pdf', 'doc', 'docx', 'txt']; // Add allowed extensions here
    if (!in_array($fileType, $allowedTypes)) {
        echo "File type is not allowed.<br>";
        $allow_upload = 0;
    }

    // Optionally, check for file size limit (e.g., 5MB limit)
    $maxFileSize = 5 * 1024 * 1024; // 5 MB in bytes
    if ($_FILES["fileUpload"]["size"] > $maxFileSize) {
        echo "File is too large. Maximum allowed size is 5MB.<br>";
        $allow_upload = 0;
    }

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, the file already exists.<br>";
        $allow_upload = 0;
    }

    // Attempt to save the file if all checks passed
    if ($allow_upload == 1) {
        if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $targetFile)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileUpload"]["name"])) . " has been uploaded successfully.<br>";
        } else {
            echo "Sorry, there was an error uploading your file.<br>";
        }
    }
}
?>

Questions & Answers