PHP file system functions can be used to interact with files and directories. File operations include open, write, read, get size, delete and rename. Directory operations include creating, deleting, listing, checking, and changing the current working directory. A practical example shows how to use these functions to upload files to the server.
How to use PHP’s file system functions
PHP provides a rich set of file system functions that allow you to work with files and Directory to interact with. This tutorial guides you through using these functions to complete common file system operations.
File operation
The following are some commonly used file operation functions:
fopen()
: Open a document. fwrite()
and fread()
: Write and read content to the file respectively. fclose()
: Close a file. filesize()
: Get the number of bytes of the file. unlink()
: Delete the file. rename()
: Rename the file. Example: Write file
<?php $file = 'my_file.txt'; $data = "Hello, world!"; $handle = fopen($file, 'w'); fwrite($handle, $data); fclose($handle); echo "文件已写入"; ?>
Directory operation
The following are commonly used directory operation functions:
mkdir()
: Create a directory. rmdir()
: Delete empty directories. scandir()
: Returns the list of files and directories in the directory. is_dir()
: Check whether it is a directory. chdir()
: Change the current working directory. Example: Create a directory
<?php $directory = 'new_directory'; mkdir($directory); echo "目录已创建"; ?>
Practical case
Upload files to the server
The following is sample code on how to use file system functions to upload files to the server:
<?php if ($_FILES['my_file']['error'] === 0) { $target_dir = 'uploads/'; $target_file = $target_dir . basename($_FILES['my_file']['name']); // 检查文件是否已存在 if (file_exists($target_file)) { echo "文件已存在"; } else { // 移动上传的文件到目标目录 if (move_uploaded_file($_FILES['my_file']['tmp_name'], $target_file)) { echo "文件上传成功"; } else { echo "文件上传失败"; } } } ?>
The above is the detailed content of How to use PHP's file system functions?. For more information, please follow other related articles on the PHP Chinese website!