PHP Exercises: Get the size of a file
39. Get File Size
Write a PHP program to get the size of a file.
Sample Solution:
PHP Code:
<?php
// Open a file "/home/students/ppp.txt" for writing, or display an error message if unable to open
$myfile = fopen("/home/students/ppp.txt", "w") or die("Unable to open file!");
// Text to be written to the file
$txt = "PHP Exercises\n";
// Write the first line to the file
fwrite($myfile, $txt);
// Additional text to be written to the file
$txt = "from\n";
// Write the second line to the file
fwrite($myfile, $txt);
// More text to be written to the file
$txt = "w3resource\n";
// Write the third line to the file
fwrite($myfile, $txt);
// Close the file after writing
fclose($myfile);
// Display the size of the created file "/home/students/ppp.txt"
echo "Size of the file: " . filesize("/home/students/ppp.txt") . "\n";
?>
Explanation:
- Open the File:
- fopen("/home/students/ppp.txt", "w") opens the file ppp.txt in write mode.
- If the file cannot be opened, die("Unable to open file!") displays an error message.
- Write Text to the File:
- fwrite($myfile, $txt) writes text to the file.
- Three different strings ("PHP Exercises\n", "from\n", and "w3resource\n") are written to the file in separate fwrite calls.
- Close the File:
- fclose($myfile) closes the file after writing.
- Display File Size:
- filesize("/home/students/ppp.txt") gets the size of the file.
- The size is printed with "Size of the file: ".
Output:
Size of the file: 30
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to obtain a file’s size in bytes and convert it to kilobytes with two-decimal precision.
- Write a PHP script to iterate through a directory, determining and comparing the size of each file.
- Write a PHP script to extract the size of a remote file without downloading its full content.
- Write a PHP script to check if a file exceeds a specified size threshold and log a warning if it does.
Go to:
PREV : Email Validation.
NEXT : Calculate Modulus Without %.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.