File in PHP

Used before category names. Blog PHP

Managing files and how to upload them is one of the most important parts of any website. On most websites, you need to work with files to work with the website. This article will teach you how to manage and work with file in PHP.

PHP includes functions for creating, editing, and deleting files that we will use to manage files.

Note: Be careful when working with files because another file may be edited or deleted by mistake.

Reading file in PHP

Reading the file with the readfile() function

The readfile() function reads the desired file and places it in the output buffer.

Next to your php file, create a file named “myfile.txt” and save the following text in it.

Ferrari: Is from Italy
Benz: Is from Germany
Toyota: Is from Japan

Then open your php file and use the following command to read and display the content of the file.

echo readfile("myfile.txt");
---------------------
Ferrari: Is from Italy Benz: Is from Germany Toyota: Is from Japan68

The last number in the text indicates the number of characters reads.

The readfile() function is only good for when you want to open a file and read its contents. There are other and better ways to read the file, which we will discuss further.

Reading a file with the fopen() function in PHP

The fopen() function is used like the readfile() function to read the file, but it has more options.

$myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
if ($myfile) {
    echo fread($myfile, filesize("myfile.txt"));
    fclose($myfile);
}

The first parameter of the fopen() function contains the name of the file to be opened and the second parameter specifies the mode in which the file should be opened. If the function cannot open the file, it displays a message to the user.

The fread() function reads the contents of the opened file. The first parameter of this function is the name of the file we want to read and the second parameter is the number of bytes to be read. In this example, the entire file is read to the end.

The fclose() function is also used to close the opened file. In this example, the function closes only the open file, but if you want to close all the open files, you can use the fclose() function without the file variable.

fclose();

Now let’s talk about file opening modes.

  • r: Opens the file for reading only (read-only). The file pointer starts at the beginning of the file.
  • w: Opens the file for writing only. If the file already exists, it deletes the contents of the file or creates a new file if the file does not exist. The file pointer starts at the beginning of the file.
  • a: Opens the file for writing only. If the file already exists, the data in the file will be preserved and if the file does not exist, it will create a new file. The file pointer starts from the end of the file.
  • x: Creates a new write-only file. If the file already exists, it returns false with an error.
  • r+: Opens the file for reading and writing. The file pointer starts at the beginning of the file.
  • w+: Opens the file for reading and writing. If the file already exists, it deletes the contents of the file or creates a new file if the file does not exist. The file pointer starts at the beginning of the file.
  • a+: Opens the file for reading and writing. If the file already exists, the data in the file will be preserved and if the file does not exist, it will create a new file. The file pointer starts from the end of the file.
  • x+: Opens the file for reading and writing. If the file already exists, it returns false with an error.

Read a line from the file

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

$myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
if ($myfile) {
    echo fgets($myfile);
    fclose($myfile);
}
---------------------
Ferrari: Is from Italy

After calling the function, the file pointer moves to the next line. So if we call the function again, it will return the second line.

Check the end of the file

The feof() function checks whether the “end of file” (EOF) has been reached. This function is suitable for reading files in repeating loops because the loop repeats until the end of the file are reached.

$myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
if ($myfile) {
    while (!feof($myfile)) {
        echo fgets($myfile) . "<br>";
    }
    fclose($myfile);
}
-------------------
Ferrari: Is from Italy
Benz: Is from Germany
Toyota: Is from Japan

Reading the file character by character

fgetc() function is used to read a character from a file.

$myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
if ($myfile) {
    while (!feof($myfile)) {
        echo fgetc($myfile);
    }
    fclose($myfile);
}
------------------
Ferrari: Is from Italy Benz: Is from Germany Toyota: Is from Japan

Reading the file with the file() function

This function reads all the content of the file and puts it in the variable.

$myfile = file("myfile.txt") or die("Unable to open file!");

foreach ($myfile as $line_num => $line) {
    echo "Line #{$line_num} : " . htmlspecialchars($line) . "<br />\n";
}
----------------------
Line #0 : Ferrari: Is from Italy
Line #1 : Benz: Is from Germany
Line #2 : Toyota: Is from Japan 

We can also add more features to the function using flags. For example, not reading the empty lines of the file.

$myfile = file("myfile.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  • FILE_USE INCLUDE_PATH: Searches for the file in include_path.
  • FILE_IGNORE_NEW_LINES: Removes the newline at the end of each array item.
  • FILE_SKIP_EMPTY_LINES: Skips empty lines.

Reading the file with the file_get_contents() function

This function reads all the contents of the file into a string variable.

$myfile = file_get_contents("myfile.txt") or die("Unable to open file!");

if($myfile){
    echo $myfile;
}

With this function, you can also read the HTML content of a website page.

$myfile = file_get_contents("https://honarsystems.ir/") or die("Unable to open file!");

if($myfile){
    echo $myfile;
}

Write file in PHP

As you saw in the file opening modes section, there were modes for writing files. Now we will use them to create or write files. For this, as in the previous examples, we must first open the file with the fopen() function.

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

$myfile = fopen("myfile.txt", "w") or die("Unable to open file!");
$txt = "BMW: Is from Germany\n";
fwrite($myfile, $txt);
$txt = "Toyota: Is from Japan\n";
fwrite($myfile, $txt);
fclose($myfile);

The first parameter of the fwrite() function contains the name of the file we want to write to, and the second parameter is the string we want to write inside the file. To write each line in the file, we must call the fwrite() function.

If you open the file, you will see the following two lines.

BMW: Is from Germany
Toyota: Is from Japan

Because we used “w” all the contents of the file were deleted and replaced with new data.

Append content to the file

Now, if we want to add new content to the continuation of the previous content and the previous content is not deleted, we use the following method.

The following content already exists in the file.

Ferrari: Is from Italy
Benz: Is from Germany
Toyota: Is from Japan

And we run the following code.

$myfile = fopen("myfile.txt", "a") or die("Unable to open file!");
$txt = "BMW: Is from Germany\n";
fwrite($myfile, $txt);
fclose($myfile);

If you open the file, you will see that the new content is appended to the previous content.

Ferrari: Is from Italy
Benz: Is from Germany
Toyota: Is from Japan
BMW: Is from Germany

The only difference between this method and the previous method is in the fopen() function and the second parameter, which was “w” in the first one and “a” in this one.

Delete file in PHP

Unlink() function is used to delete a file in PHP.

unlink("myfile.txt");

File upload in PHP

In PHP you can easily upload a file to the server. But remember to observe the security measures because uploading the file can easily threaten the security of the server.

Anyway, to start, you need to make sure whether it is possible to upload the file to the server or not. For this, you need to open the “php.ini” file and change the file_uploads option to On.

file_uploads = On 

The information in the php.ini page has many variables, among which upload_tmp_dir specifies the temporary folder used to upload the file, and the maximum size of files that can be uploaded is also defined in upload_max_filesize.

After this, we first enter the code folder and create the index.html file. Then we open the file and put the following codes in it.

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>

</body>
</html>

Points to keep in mind:

  • Be sure to post the method part. (method=”post”)
  • The enctype=”multipart/form-data” option must be present to specify which content type to use when submitting the form.

The above code will send the uploaded file to the “upload.php” file. Now it’s time to code the upload file.

Create a folder named uploads next to the upload.php file. This is the folder where the files will be uploaded.

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
    } else {
        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
        } else {
            // Allow certain file formats
            if (
                $imageFileType != "jpg" 
                && $imageFileType != "png" 
                && $imageFileType != "jpeg"
                && $imageFileType != "gif"
                && $imageFileType != "pdf"
            ) {
                echo "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.";
            }
            else{
                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                    echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
                } else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }
        }
    }
}

The first three lines extract the name, upload path, and file type.

In this example, we check whether the upload was done through the form or not. We check if a file with this name already exists. Then we check the file size, which should be less than 500KB. We check the type of the uploaded file, which must be one of the types of files defined in the code.

The files uploaded on the server are first uploaded into the “tmp” folder on the server. Using the move_uploaded_file() function, we transfer it from the “tmp” folder to the desired folder.

If any of the above items are not correct when uploading the file, the corresponding error will be displayed to the user.

In the example above, global variables are used as follows:

  • $_FILES['file']['tmp_name']: The name of the uploaded file in the temporary directory on the web server.
  • $_FILES['file']['name']: The actual name of the uploaded file.
  • $_FILES['file']['size']: The size of the uploaded file in bytes.
  • $_FILES['file']['type']: MIME type of the uploaded file.
  • $_FILES['file']['error']: Error code associated with uploading this file.

Upload multiple files

To upload multiple files at the same time in PHP, we need to make a slight change to the previous example.

Open the index.html file and change the form section as follows.

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload[]" id="fileToUpload" multiple="multiple">
    <input type="submit" value="Upload File" name="submit">
</form>

In the “input” element, we add [] to the end of the name in the name section. We also add multiple attributes so that the user can select multiple files (multiple=”multiple”).

Now open the upload.php file, delete the previous codes, and put the following code in it.

$files = array_filter($_FILES['fileToUpload']['name']);

$total_count = count($_FILES['fileToUpload']['name']);

$target_dir = "uploads/";

// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
    for ($counter = 0; $counter < $total_count; $counter++) {
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$counter]);
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));


        // Check if file already exists
        if (file_exists($target_file)) {
            echo "Sorry, file already exists.";
        } else {
            // Check file size
            if ($_FILES["fileToUpload"]["size"][$counter] > 500000) {
                echo "Sorry, your file is too large.";
            } else {
                // Allow certain file formats
                if (
                    $imageFileType != "jpg"
                    && $imageFileType != "png"
                    && $imageFileType != "jpeg"
                    && $imageFileType != "gif"
                    && $imageFileType != "pdf"
                ) {
                    echo "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.";
                } else {
                    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$counter], $target_file)) {
                        echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"][$counter])) . " has been uploaded.";
                    } else {
                        echo "Sorry, there was an error uploading your file.";
                    }
                }
            }
        }
    }
}

Most of the parts are the same as in the previous example, with the difference that in the first line, using the array_filter() function, we delete the files whose names are empty. Then we put the process of uploading the file inside the “for” loop so that this process is repeated for the number of files.

is_readable() function

It is used to check the file whether it can be read or not.

echo is_readable("myfile.txt");

If readable, it returns 1. Sometimes the file does not exist and sometimes the file exists but the server does not allow you to read the file. This function checks whether the file can be read or not.

Tags: