Home > Backend Development > PHP Tutorial > How to use PHP's file system functions?

How to use PHP's file system functions?

WBOY
Release: 2024-04-20 18:33:01
Original
928 people have browsed it

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.

如何使用 PHP 的文件系统函数?

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 "文件已写入";
?>
Copy after login

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 "目录已创建";
?>
Copy after login

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 "文件上传失败";
    }
  }
}
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template