PHP function introduction—filesize(): Get the size of the file
In PHP development, we often need to get the size of the file, which requires the use of the PHP built-in function filesize(). The filesize() function is used to get the size of a file and returns the size value in bytes.
The basic syntax of the filesize() function is as follows:
filesize(string $filename): int|false
Among them, $filename represents the file name whose size needs to be obtained, which can be the URL of a local file or a remote file. The function returns an integer representing the size of the file. If the function fails to execute, return false.
Let's look at an example. Suppose we have a file test.txt and we want to get its size:
$filename = 'test.txt'; $size = filesize($filename); if ($size !== false) { echo "文件的大小是:" . $size . " 字节"; } else { echo "获取文件大小失败"; }
In the above code, we change test by calling the filesize() function. The size of the .txt file is stored in the variable $size. Then, we check whether the function is executed successfully by judging whether $size is false. If the execution is successful, we use the echo statement to print out the size of the file. If the execution fails, an error message is printed out.
It should be noted that the size returned by the filesize() function is in bytes. If we want to convert it to other units (such as KB or MB), we can do it by dividing by 1024 . For example:
$filename = 'test.txt'; $size = filesize($filename); if ($size !== false) { $size_kb = round($size / 1024, 2); echo "文件的大小是:" . $size_kb . " KB"; } else { echo "获取文件大小失败"; }
In the above code, we divide the size of the file by 1024 and use the round() function to take two decimal places and save the result in the variable $size_kb. We then print out the file size and display it in KB.
Summary:
The filesize() function is a very practical PHP function that can easily obtain the size of the file. By calling this function, we can quickly obtain the file size during project development and perform subsequent processing and judgment. In actual use, we can also convert the unit of file size by dividing by 1024 and other operations to meet different needs.
The above is the detailed content of PHP function introduction—filesize(): Get the size of a file. For more information, please follow other related articles on the PHP Chinese website!