Home >Backend Development >PHP Tutorial >PHP directory and file operations_PHP tutorial

PHP directory and file operations_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:24921browse

Directory operations

The first is the function to read from the directory, opendir(), readdir(), closedir(). When used, the file handle is opened first, and then iteratively listed:

<?php
$base_dir="filelist/";
$fso=opendir($base_dir);
echo  $base_dir."<hr/>";
while($flist=readdir($fso)){
      echo $flist."<br/>";
}
closedir($fso)
?>

This is a program that returns the files and directories under the file directory (0 files will return false).

Sometimes you need to know directory information. You can use dirname($path) and basename($path) to return the directory part and file name part of the path respectively. You can use disk_free_space($path) to return the remaining space of the view space.

Create command:

  • mkdir($path,0777): 0777 is the permission code, which can be set with the umask() function under non-window conditions.
  • rmdir($path): will delete the file with the path in $path.

New file

First, determine the permissions of the directory where the file you want to create is located. The recommended device is 777. Then, it is recommended to use an absolute path for the name of the new file.

<?php
$filename="test.txt";
$fp=fopen("$filename", "w+"); //打开文件指针,创建文件
if ( !is_writable($filename) ){
      die("文件:" .$filename. "不可写,请检查!");
}
//fwrite($filename, "anything you want to write to $filename.";
fclose($fp);  //关闭指针
?>

Read file

First, check whether a file can be read (permission issue), or whether it exists. We can use the is_readable function to obtain the information:

<?php
$file = 'dirlist.php';
if (is_readable($file) == false) {
        die('文件不存在或者无法读取');
} else {
        echo '存在';
}
?>

The function to determine the existence of a file also includes file_exists (demonstrated below), but this is obviously not as comprehensive as is_readable. It can be used when a file exists:

<?php
$file = "filelist.php";
if (file_exists($file) == false) {
        die('文件不存在');
}
$data = file_get_contents($file);
echo htmlentities($data);
?>

However, the file_get_contents function is not supported on lower versions. You can first create a handle to the file, and then use the pointer to read all:

There is another way to read binary files:

$data = implode('', file($file));

Write file

Same as reading a file, first check if it can be written:

<?php
$file = 'dirlist.php';
if (is_writable($file) == false) {
        die("You have no right to write!");
}
?>

If you can write, you can use the file_put_contents function to write:

<?php
$file = 'dirlist.php';
if (is_writable($file) == false) {
        die('不能写入');
}
$data = '帮客之家';
file_put_contents ($file, $data);
?>

The file_put_contents function is a newly introduced function in php5 (if you don’t know it exists, use the function_exists function to determine it first). Lower versions of php cannot be used. You can use the following method:

$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);

Replace it.

When writing a file, sometimes you need to lock it, and then write:

function cache_page($pageurl,$pagedata){
    if(!$fso=fopen($pageurl,'w')){
        $this->warns('无法打开缓存文件.');//trigger_error
        return false;
    }
    if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型锁定
        $this->warns('无法锁定缓存文件.');//trigger_error
        return false;
    }
    if(!fwrite($fso,$pagedata)){//写入字节流,serialize写入其他格式
        $this->warns('无法写入缓存文件.');//trigger_error
        return false;
    }
    flock($fso,LOCK_UN);//释放锁定
    fclose($fso);
    return true;
}

Copy, delete files

Deleting files in PHP is very simple, just use the unlink function:

<?php
$file = 'dirlist.php';
$result = @unlink ($file);
if ($result == false) {
        echo '蚊子赶走了';
} else {
        echo '无法赶走';
}
?>

Copying files is also easy:

<?php
$file = 'yang.txt';
$newfile = 'ji.txt'; # 这个文件父文件夹必须能写
if (file_exists($file) == false) {
        die ('小样没上线,无法复制');
}
$result = copy($file, $newfile);
if ($result == false) {
        echo '复制记忆ok';
}
?>

You can use the rename() function to rename a folder. Other operations can be achieved by combining these functions.

Get file attributes

Get the last modification time:

<?php
$file = 'test.txt';
echo date('r', filemtime($file));
?>

The returned timestamp is the unix timestamp, which is commonly used in caching technology.

Related are fileatime() and filectime() to get the last time accessed . $owner = posix_getpwuid(fileowner($file)); (non-window system), ileperms() obtains the file permissions.

<?php
$file = 'dirlist.php';
$perms = substr(sprintf('%o', fileperms($file)), -4);
echo $perms;
?>

filesize() returns the file size in bytes:

<?php
// 输出类似:somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>

To get all the information of a file, there is a function stat() function that returns an array:

<?php
$file = 'dirlist.php';
$perms = stat($file);
 var_dump($perms);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752478.htmlTechArticleDirectory operations are first functions to read from the directory, opendir(), readdir(), closedir(), use The file handle is opened first, and then iteratively listed: ?php$base_dir="filelist/";$fso...
Statement:
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