Practical analysis of php development (5): file and directory operations

1. Return all files in a directory (excluding subdirectories)

function getfiles($dir)
{
    
    
    if ($dir != '' && substr($dir, strlen($dir) - 1) != '') {
    
    
        $dir .= '/';
    }
    $row = array();
    if (is_dir($dir)) {
    
    
        if ($di = opendir($dir)) {
    
    
            while (($file = readdir($di)) !== false) {
    
    
                if (is_file($dir . $file) && $file != '.' && $file != '..') {
    
    
                    $row[] = $file;
                }
            }
            closedir($di);
        }
    }
    return $row;
}

2. Return all directories under a directory

//返回某目录下的所有目录
function get_dir($dir)
{
    
    
    if ($dir != '' && substr($dir, strlen($dir) - 1) != '') {
    
    
        $dir .= '/';
    }
    $row = array();
    if (is_dir($dir)) {
    
    
        if ($di = opendir($dir)) {
    
    
            while (($file = readdir($di)) !== false) {
    
    
                if (is_dir($dir . $file) && $file != '.' && $file != '..') {
    
    
                    $row[] = $file;
                }
            }
            closedir($di);
        }
    }
    return $row;
}

3. Delete file -unlink

1. Basic usage

In PHP, unlinkfunctions are used to delete files. Its usage is as follows:

bool unlink ( string $filename [, resource $context ] )

Parameter Description:

  • $filename: The path and filename of the file to delete.
  • $context(optional): This is a context resource (for example, an open file handle) that can be passed to the unlink function.

return value:

  • Returns if the file was successfully deleted true.
  • Returned if an error occurred, such as the file does not exist or insufficient permissions to delete the file false.

Example usage:

$file = 'path/to/file.txt';
if (unlink($file)) {
    
    
    echo '文件删除成功';
} else {
    
    
    echo '文件删除失败';
}

It should be noted that unlinkthe function can only be used to delete files, not folders. If you need to delete a folder, you can use rmdira function (for deleting empty folders) or recursively delete all files and subfolders in the folder.

2. Actual use

function del_file($file)
{
    
    
    $delete = @unlink($file);
    clearstatcache();
    if (@file_exists($file)) {
    
    
        $filesys = str_replace("/", "\\", $file);
        $delete = @system("del $filesys");
        clearstatcache();
        if (@file_exists($file)) {
    
    
            $delete = @chmod($file, 0777);
            $delete = @unlink($file);
            $delete = @system("del $filesys");
        }
    }
    clearstatcache();
    if (@file_exists($file)) {
    
    
        return false;
    } else {
    
    
        return true;
    }
}

3. Usage of clearstatcache

In PHP, clearstatcachethe function is used to clear the file state cache. This function can clear the cache used by stat, file_exists, is_readable, is_writableand other file-related functions on files or directories.

Here is clearstatcachethe usage of the function:

void clearstatcache( bool $clear_realpath_cache = false, string $filename = "" )

Parameter Description:

  • $clear_realpath_cache(Optional): If set to true, the realpath cache will be cleared at the same time, that is, realpaththe path resolution results cached by the function will be cleared. The default value is false.
  • $filename(Optional): The filename to clear the associated cache. If a filename is specified, only the cache associated with that file is cleared. The default is an empty string, which means to clear all caches.

Example usage:

$file = 'path/to/file.txt';
// 执行一些与文件状态相关的操作
echo file_exists($file); // 输出 1

// 清除缓存
clearstatcache();

// 重新执行文件不存在检查
echo file_exists($file); // 输出 0

When you are performing multiple operations on the file state and need to ensure that you get the latest file state, you can call clearstatcachethe function to clear the cache. For example, when you modify the attributes of a file or delete a file, calling this function can ensure that the next operation can obtain the latest file status information.

4.system(“del $filesys”)

In PHP, systemfunctions are used to execute system commands. When you invoke system("del $filesys"), it will do something similar to running the command on the command line del $filesys. This command is used to delete the specified file in Windows operating system.

Here is systemthe usage of the function:

string system( string $command [, int &$return_var ] )

Parameter Description:

  • $command: The system command to be executed.
  • $return_var(Optional): A variable to store the command's return value. If this parameter is provided, after the command is executed, the variable will be set as the return value of the command.

return value:

  • Return the command's output, if any, as a string.

Example usage:

$filesys = 'path/to/file.txt';
$command = "del $filesys";

$output = system($command, $return_var);
if ($return_var === 0) {
    
    
    echo '文件删除成功';
} else {
    
    
    echo '文件删除失败';
}

It should be noted that systemthe commands executed by the function may be restricted by the system security settings, so be careful when using this function. Make sure that $filesysthe value of the parameter is the file path you expect to delete, and do necessary security verification and filtering to prevent potential security issues. Also, systemthe function executes commands directly on the terminal, so make sure you only call trusted commands and avoid using values ​​entered dynamically by the user to prevent command injection attacks.

5. Recursively delete all files in a directory

function del_dir($directory)
{
    
    
    if (is_dir($directory)) {
    
    
        //递归删除某个目录下的全部文件
        if ($dh = @opendir($directory)) {
    
    
            while ($filename = readdir($dh)) {
    
    
                if ($filename != "." && $filename != "..") {
    
    
                    //是文件则删除文件
                    if (is_file($directory . "/" . $filename)) {
    
    
                        unlink($directory . "/" . $filename);
                    } else {
    
    
                        //非空目录则递归删除子文件夹或文件
                        del_dir($directory . "/" . $filename);
                        rmdir($directory . "/" . $filename);
                    }
                }
            }
            @closedir($dh);
            //rmdir($directory);
        }
    } else {
    
    
        //直接删除指定某个文件
        if (file_exists($directory)) {
    
    
            unlink($directory);
        }
    }
}

Fourth, create a directory -mkdir

1. Basic usage

When using functions in PHP mkdirto create folders in Windows and Linux systems, the main difference is the path separator and permission settings.

  1. Path separator:

    • On Windows systems, the path separator is a backslash (\). For example, mkdir('C:\my_folder').
    • On Linux systems, the path separator is a forward slash (/). For example, mkdir('/home/my_folder').
  2. Permission settings:

    • In the Windows system, mkdirthe function will automatically inherit the permission settings of the parent directory, and give the current user full control permission in the created folder.
    • In the Linux system, mkdirthe default permission of the folder created by the function is 755 (rwxr-xr-x), which means that the owner has read, write and execute permissions on the folder, while the group and other users only have read and execute permissions. This permission setting can be modified as required.

When using mkdirfunctions to create folders, it is recommended to do so in a portable way, using forward slashes as path separators, and manually setting appropriate permissions if required. For example:

// 在Windows中创建文件夹
mkdir('C:/my_folder');

// 在Linux中创建文件夹,并设置权限为777
mkdir('/home/my_folder');
chmod('/home/my_folder', 0777);

Please note that for some special cases, such as creating multi-level nested folders, you may need to add additional logic in the code to ensure that the parent directory exists.

2. Package use

//创建目录
function mdir($directoryName)
{
    
    
    $directoryName = str_replace("\\", "/", $directoryName);
    $dirNames = explode('/', $directoryName);
    $total = count($dirNames);
    $temp = '';
    for ($i = 0; $i < $total; $i++) {
    
    
        $temp .= $dirNames[$i] . '/';
        if (!is_dir($temp)) {
    
    
            $oldmask = umask(0);
            if (!mkdir($temp, 0777)) exit("can't md dir $temp");
            umask($oldmask);
        }
    }
    return true;
}

5. Write to the file

1. Basic usage

In PHP, fopenfunctions are used to open a file or URL and return a file handle so you can read, write, or otherwise operate on it.

Here is fopenthe usage of the function:

resource fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] )

Parameter Description:

  • $filename: The path and file name of the file to open.
  • $mode: The mode to open the file. Commonly used patterns are:
    • r: Read-only mode, read from the beginning of the file.
    • w: write-only mode, truncates the file to zero length, and creates the file if it does not exist.
    • a: Append mode, write to the end of the file, if the file does not exist, create it.
    • x: Exclusive creation mode, if the file already exists, it will fail to open.
    • Wait, there are other modes to choose from, please refer to the official PHP documentation for more information.
  • $use_include_path(Optional): If set to true, the paths specified in include_path will be searched when opening the file. The default value is false.
  • $context(Optional): A context resource that can be passed to fopenthe function for specific file operation settings.

return value:

  • If the file is opened successfully, a resource handle (resource) representing the open file is returned, which can be used for subsequent operations on the file.
  • Returned if there was an error, such as the file does not exist or insufficient permissions to open the file false.

Example usage:

$file = 'path/to/file.txt';
$handle = fopen($file, 'r');
if ($handle) {
    
    
    // 读取文件内容
    $content = fread($handle, filesize($file));
    echo $content;
    
    // 关闭文件
    fclose($handle);
} else {
    
    
    echo '文件打开失败';
}

After opening the file, you can use other functions such as fread, fwrite, fgets, fputcsvetc. to read and write the file. fcloseRemember to use the function to close the file handle to release resources when you are done with the file operation .

2. Actual use

function write_file($filename, $contents)
{
    
    
    if ($fp = fopen($filename, "w")) {
    
    
        //fwrite($fp,stripslashes($contents));
        $contents = trim($contents) == '' ? ' ' : $contents;
        fwrite($fp, $contents);
        fclose($fp);
        return true;
    } else {
    
    
        return false;
    }
}

@ Leak sometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/131703740