PHP File Handling Interview Questions & Answers
PHP file handling interview questions: check if a file exists, get file size, fopen(), delete a file, unlink() vs unset(), include vs require and secure file upload.
Which is the PHP function to delete a file from server?
Use the unlink() function. It deletes a file from the server and returns true on success. It is better to check first if the file exists.
<?php
$file = "sample-file.txt";
if (file_exists($file) && unlink($file)) {
echo "File deleted";
} else {
echo "File not found or could not be deleted";
}
?>
Output:
File deleted
- The deleted file can not be taken back.
- PHP needs permission to delete the file, otherwise you get a warning.
- Never pass a file name from user input without checking it.
- Do not mix it with
unset(), see unlink() vs unset().
What is fopen function PHP?
fopen() opens a file (or a URL) and returns a file handle, that you use with functions like fgets(), fwrite() and fclose(). If it fails, it returns false and shows a warning.
<?php
$handle = fopen("sample.txt", "r");
if ($handle === false) {
die("Could not open the file.");
}
echo fgets($handle); // read the first line
fclose($handle);
?>
Output:
Line 1
The second parameter is the mode: r read, w write (erases the file), a append, x create a new file. See the full table in PHP File Handling. Always close the file with fclose().
What is the difference between unlink() and unset() in PHP?
unlink() deletes a file from the file system. unset() removes a variable from memory. They do very different jobs.
| unlink() | unset() |
|---|---|
| Deletes a file from the server | Destroys a variable |
| Takes the file name or path | Takes the variable |
| Returns true or false | Returns nothing |
| The file is gone for ever | Only the variable becomes undefined |
<?php
$file = "notes.txt";
file_put_contents($file, "Hello"); // create a file
unlink($file);
echo file_exists($file) ? "File exists<br>" : "File deleted<br>";
$name = "Robin";
unset($name);
var_dump(isset($name));
?>
Output:
File deleted
bool(false)
Be careful with unlink(), a deleted file can not be taken back. Never pass a file name that comes from user input without checking it.
How to check if a file exists in PHP?
Use the file_exists() function. It takes the file name or path and returns true if it exists, otherwise false.
<?php
$file = "data.txt";
if (file_exists($file)) {
echo "File found";
} else {
echo "File not found";
}
?>
Output:
File not found
Note that file_exists() also returns true for folders. Use is_file() to check only files and is_dir() to check only folders.
How to get the size of a file in PHP?
Use the filesize() function. It returns the size of a file in bytes. If the file does not exist, it gives a warning and returns false.
<?php
file_put_contents("sample.txt", "Hello PHP");
echo filesize("sample.txt") . " bytes";
?>
Output:
9 bytes
To show the size in KB, divide it by 1024.
<?php
$kb = filesize("sample.txt") / 1024;
echo round($kb, 2) . " KB";
?>
Output:
0.01 KB
PHP remembers the result of filesize() for the same file. If the file changes during the same script, call clearstatcache() first.
What is the difference between include() and require() in PHP?
Both include and require add the code of another file into your script. The difference is what happens when the file is missing.
| Statement | If the file is missing |
|---|---|
| include | Shows a warning and the script continues |
| include_once | Same as include, but does not add the same file again |
| require | Shows a fatal error and the script stops |
| require_once | Same as require, but does not add the same file again |
<?php
echo "Start<br>";
include "missing.php"; // warning, but the script goes on
echo "After include<br>";
require "missing.php"; // fatal error, the script stops here
echo "After require"; // this line never runs
?>
What you will see: “Start”, then a warning, then “After include”, and then a fatal error. The text “After require” is never shown.
Use require for files that your page can not work without, like database connection or config. Use include for optional parts, like a sidebar. Read more in PHP File Inclusion.
What is the maximum file size we can upload using PHP? How to increase it?
By default PHP allows files up to 2 MB. This limit is set by the upload_max_filesize setting. You can increase it in the php.ini file.
upload_max_filesize = 15M
post_max_size = 20M
memory_limit = 128M
You need to change post_max_size also. It is the limit for the whole form data (the file plus other fields), so it must be bigger than upload_max_filesize. If it is smaller, the upload fails without a clear error and $_FILES stays empty.
You can check the current values with ini_get().
<?php
echo ini_get("upload_max_filesize") . "<br>";
echo ini_get("post_max_size");
?>
Output:
2M
8M
Also read PHP File Upload and the safe upload rules in PHP Security Tips.
How to upload a file securely in PHP?
File upload is risky, because someone can upload a PHP file and run it on your server. Follow these steps to make it safe:
- Check the upload error with
UPLOAD_ERR_OK. - Check the real type of the file, not the name or the type sent by the browser.
- Limit the file size.
- Give the file a new random name, and never use the original name.
- Save the file outside the public folder if you can, or at least block PHP execution in the upload folder.
<?php
if ($_FILES["photo"]["error"] !== UPLOAD_ERR_OK) {
exit("Upload failed.");
}
$allowed = ["image/jpeg" => "jpg", "image/png" => "png"];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES["photo"]["tmp_name"]);
if (!isset($allowed[$mime])) {
exit("Only JPG and PNG files are allowed.");
}
if ($_FILES["photo"]["size"] > 2 * 1024 * 1024) {
exit("File is too big. Maximum 2 MB.");
}
$newName = bin2hex(random_bytes(16)) . "." . $allowed[$mime];
move_uploaded_file($_FILES["photo"]["tmp_name"], "/var/www/uploads/" . $newName);
?>
Learn the basics in PHP File Upload, and how to change the size limit in maximum upload size.