PHP file directory operation function study notes_PHP tutorial

WBOY
Release: 2016-07-13 10:49:28
Original
721 people have browsed it

File operations in PHP are nothing more than file read and write operations, deletion operations, judgment operations, permission operations and some file searches, etc. Let me post the PHP file operation functions I have learned.

File operation function

1. Get the file name: basename();

2. Get the directory where the file is located: dirname();

3. Pathinfo() obtains file information and returns an array, including the path, full name of the file, file name and extension. For example:

The code is as follows Copy code
 代码如下 复制代码

$file = '/com/netingcn/error.log';
print_r(pathinfo($file));
结果为:
Array(
    [dirname] => /com/netingcn
    [basename] => error.log
    [extension] => log
    [filename] => error
)

$file = '/com/netingcn/error.log';

print_r(pathinfo($file));

The result is:

Array(

[dirname] => /com/netingcn

[basename] => error.log

[extension] => log

[filename] => error

)

4. Determine whether the file exists: is_file();
 代码如下 复制代码

$handler = fopen($file, 'w'); // w 会冲掉以前的内容、a 是追加
fwrite($handler, 'content');
fclose($handler);              //记得关闭打开的文件句柄9、文件读取操作有很多,

5. Determine whether the directory exists: is_dir();

6. Determine whether the file or directory exists: file_exists();
 代码如下 复制代码

$handler = fopen($file, 'r');

while(!feof($handler)) {
    $datas[] = fgets($handler);  //读取一行内容
}

while(!feof($handler)) {
    $datas[] = fgetss($handler); //读取一行内容并过来html标记
}

while(!feof($handler)) {
    $datas[] = fgetcsv($handler); //读取一行内容并解析csv字段
}

$content = fread($handler, $strLength); //读取指定长读的字符

fclose($handler);

7. Read all the contents of the file: file() or file_get_contents(), where file() returns an array with one row of elements, and file_get_contents() returns the entire contents of the file as a String; 8. Write the file fwrite, such as:

The code is as follows Copy code

$handler = fopen($file, 'w'); // w will flush out the previous content, and a will append
fwrite($handler, 'content');

fclose($handler); //Remember to close the open file handle 9. There are many file reading operations,

 代码如下 复制代码
$file = "phpddt.txt";
$fp = fopen($file,"r");
if ($fp){
while(!feof($fp)){
//第二个参数为读取的长度
$data = fread($fp, 1000);
}
fclose($fp);
}
echo $data;
?>
Here are a few briefly introduced:
The code is as follows Copy code
$handler = fopen($file, 'r'); while(!feof($handler)) { $datas[] = fgets($handler); //Read a line of content } while(!feof($handler)) { $datas[] = fgetss($handler); //Read a line of content and add the html tag } while(!feof($handler)) { $datas[] = fgetcsv($handler); //Read a line of content and parse the csv field } $content = fread($handler, $strLength); //Read the characters of the specified long read fclose($handler);
php read file operation function 1. Use fread() to obtain Please see the php code below:
The code is as follows Copy code
$file = "phpddt.txt";<🎜> $fp = fopen($file,"r");<🎜> if ($fp){<🎜> while(!feof($fp)){<🎜> //The second parameter is the read length<🎜> $data = fread($fp, 1000);<🎜> }<🎜> fclose($fp);<🎜> }<🎜> echo $data;<🎜> ?>

Run result:
PHP Diandiantong (www.bKjia.c0m), focuses on PHP development and provides professional PHP tutorials!
2.fseek (resource handle, int offset [, int whence]), offset the pointer to offset offset.
(The content of php.txt is [Welcome to www.bKjia.c0m])
After running the following php code:

The code is as follows Copy code
 代码如下 复制代码


$file = "php.txt";
$fp = fopen($file,"r");
//将文件指针跳转到第8个字节之后
fseek($fp,8);
//读取数据
$data = fgets($fp,4096);
echo $data;
?>

$file = "php.txt";
$fp = fopen($file,"r");
//Jump the file pointer to after the 8th byte
fseek($fp,8);
//Read data
$data = fgets($fp,4096);
echo $data;
?>

 代码如下 复制代码


$file = "phpddt.txt";
$fp = fopen($file,"r");
//将文件指针跳转到第8个字节之后
fseek($fp,8);
//获取指针位置的偏移量
echo ftell($fp);
?>

The result is:

to www.bKjia.c0m
The description of whence parameter is as follows:
SEEK_SET - Set position equal to offset bytes.
SEEK_CUR - Sets the position to the current position plus offset.
SEEK_END - Set the position to the end of the file plus offset. (assignment)
If whence is not specified, the default is SEEK_SET.
3. The ftell() function is used to obtain the offset of the pointer position
The php demo code is as follows:

The code is as follows Copy code


$file = "phpddt.txt";
$fp = fopen($file,"r");

//Jump the file pointer to after the 8th byte
代码如下 复制代码


$file_arr = parse_ini_file("phpddt.ini",true);
print_r($file_arr);
?>

fseek($fp,8);

//Get the offset of the pointer position
echo ftell($fp);
?>


Running result:
8
4. The rewind() function moves the file pointer to the specified location

5. The parse_ini_file() function parses the .ini file and easily parses multi-dimensional arrays. Take a look at the php tutorial below to find out!

First save the phpddt.ini file. The content of the file is as follows:
[web1]
url= "www.bKjia.c0m"
name = php diandiantong
[web2]

url= "www.baidu.com"

name = Baidu search

Write the following php code:

The code is as follows Copy code

$file_arr = parse_ini_file("phpddt.ini",true);

print_r($file_arr);

?>

 代码如下 复制代码

$base_dir = "filelist/";
$fso = opendir($base_dir);
echo $base_dir."


"   ;
while($flist=readdir($fso)){
echo $flist."
" ;
}
closedir($fso)
?>

The running results are as follows: Array ( [web1] => Array (                                                                                           [url] => www.bKjia.c0m                   [name] => ) [web2] => Array (                                                                                     [url] => www.baidu.com                                                                                                                           [name] => ) ) Directory operations The first introduction is a function that reads from a directory, opendir(), readdir(), closedir(). When used, the file handle is opened first, and then iteratively listed:
The code is as follows Copy code
$base_dir = "filelist/";<🎜> $fso = opendir($base_dir);<🎜> echo $base_dir."
" ; while($flist=readdir($fso)){ echo $flist."
" ; } 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 free space.

Create command:

The code is as follows Copy code
 代码如下 复制代码

mkdir($path,0777)

mkdir($path,0777)

, 0777 is the permission code, which can be set by the umask() function under non-window conditions.

rmdir($path)

The file with the path in $path will be deleted.

dir -- directory class is also an important class for operating file directories. It has three methods, read, rewind, and close. This is a pseudo-object-oriented class. It first uses open file handles, and then uses pointers. Read., see the php manual here:
 代码如下 复制代码

$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "n";
echo "Path: " . $d->path . "n";
while (false !== ($entry = $d->read())) {
    echo $entry."n";
}
$d->close();
?>

The code is as follows Copy code

$d = dir("/etc/php5");

echo "Handle: " . $d->handle . "n";
echo "Path: " . $d->path . "n";
while (false !== ($entry = $d->read())) {
echo $entry."n";
}
$d->close();
?>

Output:

Handle: Resource id #2

Path: /etc/php5

.
..

apache

cgi

cli

File attributes are also very important. File attributes include creation time, last modification time, owner, file group, type, size, etc.
 代码如下 复制代码

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

Let’s focus on file operations.

 代码如下 复制代码

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

3. File Operation ● 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.:
The code is as follows Copy code
$file = 'dirlist.php';<🎜> if (is_readable($file) == false) {<🎜>             die('The file does not exist or cannot be read');<🎜> } else {<🎜>              echo 'exist';<🎜> }<🎜> ?>
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. When a file exists, you can use
The code is as follows Copy code
$file = "filelist.php";<🎜> if (file_exists($file) == false) {<🎜>             die('File does not exist');<🎜> }<🎜> $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 a pointer to read the entire file:

$fso = fopen($cacheFile, 'r');
            $data = fread($fso, filesize($cacheFile));
             fclose($fso);

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:

The code is as follows Copy code
 代码如下 复制代码

$file = 'dirlist.php';
if (is_writable($file) == false) {
die("我是鸡毛,我不能");
}
?>

$file = 'dirlist.php';
代码如下 复制代码

$file = 'dirlist.php';
if (is_writable($file) == false) {
die('我是鸡毛,我不能');
}
$data = '我是可鄙,我想要';
file_put_contents ($file, $data);
?>

if (is_writable($file) == false) {

            die("I am a chicken feather, I can't");

}

?>

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

The code is as follows Copy code

$file = 'dirlist.php';

if (is_writable($file) == false) {

            die('I am a chicken feather, I can't');
代码如下 复制代码

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;
}

}

$data = 'I am despicable, I want';

file_put_contents ($file, $data);

?>

 代码如下 复制代码

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

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). It cannot be used in lower versions of PHP. 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:
The code is as follows Copy code
function cache_page($pageurl,$pagedata){ if(!$fso=fopen($pageurl,'w')){ $this->warns('Unable to open cache file.');//trigger_error Return false; } if(!flock($fso,LOCK_EX)){//LOCK_NB, exclusive lock $this->warns('Unable to lock cache file.');//trigger_error Return false; } if(!fwrite($fso,$pagedata)){//Write byte stream, serialize to write other formats $this->warns('Unable to write to cache file.');//trigger_error Return false; } flock($fso,LOCK_UN);//Release lock fclose($fso); return true; }
● Copy and delete files Deleting files in PHP is very easy. Use the unlink function to simply operate:
The code is as follows Copy code
$file = 'dirlist.php';<🎜> $result = @unlink ($file);<🎜> if ($result == false) {<🎜> echo 'The mosquitoes were driven away';<🎜> } else {<🎜>              echo 'Can't get rid';<🎜> }<🎜> ?>

That’s it.

Copying files is also easy:

The code is as follows
 代码如下 复制代码

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

Copy code

$file = 'yang.txt';

$newfile = 'ji.txt'; # The parent folder of this file must be writable
if (file_exists($file) == false) {

die ('The demo is not online and cannot be copied');
代码如下 复制代码

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

}

$result = copy($file, $newfile);

if ($result == false) {

echo 'Copy memory ok';

}

?>

 代码如下 复制代码

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

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

● Get file attributes

 代码如下 复制代码

// 输出类似:somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Let me talk about a few common functions:

Get the latest modification time:

The code is as follows
 代码如下 复制代码

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

Copy code
$file = 'test.txt';

echo date('r', filemtime($file));

?> The returned timestamp is the unix timestamp, which is commonly used in caching technology. Related are also the time fileatime() and filectime() are used to obtain the last time accessed $owner = posix_getpwuid(fileowner($file)); (non-window system), ileperms() obtains file permissions,
The code is as follows Copy code
$file = 'dirlist.php';<🎜> $perms = substr(sprintf('%o', fileperms($file)), -4);<🎜> echo $perms;<🎜> ?> filesize() returns the file size in bytes:
The code is as follows Copy code
<🎜>// Output is similar: 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:
The code is as follows Copy code
$file = 'dirlist.php';<🎜> $perms = stat($file);<🎜> var_dump($perms);<🎜> ?> http://www.bkjia.com/PHPjc/632695.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632695.htmlTechArticleFile operations in php are nothing more than file read and write operations, deletion operations, judgment operations, permission operations and some files Search and so on, let me introduce the php file operation functions I learned...
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