PHP file directory operation function Learning Note _php Tutorial

Source: Internet
Author: User
Tags echo date flock fread php read file rewind
In PHP file operation is nothing more than a file read and write operations, delete operations, judgment operations, permissions operations and some file search, and so on, I will learn the PHP file operation function for everyone to post it.

File manipulation functions

1, get the file name: basename ();

2. Get the directory where the files are located: DirName ();

3. PathInfo () Gets the file information and returns the result as an array, including the path, full file name, filename, and extension. For example:

The code is as follows Copy Code

$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 ();

5, determine whether the directory exists: Is_dir ();

6, determine whether the file or directory exists: File_exists ();

7. Read all Files: file () or file_get_contents (), where file () returns a row for the element's array,file_get_contents () to return the entire contents of the file as a string;

8, write file fwrite, such as:

The code is as follows Copy Code

$handler = fopen ($file, ' w '); W will flush out the previous content, A is append
Fwrite ($handler, ' content ');
Fclose ($handler); Remember to close the open file handle 9, there are many file read operations,


Here are a few simple examples:

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 come over the HTML tag
}

while (!feof ($handler)) {
$datas [] = Fgetcsv ($handler); Read a line of content and parse the CSV field
}

$content = Fread ($handler, $strLength); Reads a specified long-read character

Fclose ($handler);

PHP Read File operation function

1. Use Fread () to obtain
Take a look at the following PHP code:

The code is as follows Copy Code
$file = "Phpddt.txt";
$fp = fopen ($file, "R");
if ($fp) {
while (!feof ($fp)) {
The second parameter is the length of the read
$data = Fread ($fp, 1000);
}
Fclose ($FP);
}
Echo $data;
?>

Operation Result:
PHP Point-to-point (www.bKjia.c0m), Focus on PHP development, provide professional PHP tutorial!
2.fseek (resource handle, int offset [, int whence]), offsets the pointer to offset offsets.
(Php.txt content 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");
Jumps a file pointer to the 8th byte
Fseek ($FP, 8);
Reading data
$data = Fgets ($fp, 4096);
Echo $data;
?>

The result is:
To www.bKjia.c0m
The whence parameters are described as follows:
Seek_set-the set position equals the offset byte.
Seek_cur-Sets the position to the current position plus offset.
Seek_end-Set the position to the end of the file plus offset. (Assigned value)
If whence is not specified, the default is Seek_set.
The 3.ftell () function is used to get the offset of the position of the pointer
The PHP demo code is as follows:

The code is as follows Copy Code


$file = "Phpddt.txt";
$fp = fopen ($file, "R");
Jumps a file pointer to the 8th byte
Fseek ($FP, 8);
Gets the offset of the pointer position
Echo Ftell ($FP);
?>


Operation Result:
8
4.rewind () function moves the file pointer to the specified position
The 5.parse_ini_file () function parses an. ini file for easy resolution of multidimensional arrays. Look at the following PHP tutorial to understand!
First save the Phpddt.ini file, the contents of the file are as follows:
[Web1]
Url= "www.bKjia.c0m"
name = php dot-Pass
[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);
?>

The results of the operation are as follows:
Array
(
[Web1] = = Array
(
[url] = www.bKjia.c0m
[name] + PHP dot-pass
)

[WEB2] = = Array
(
[url] = www.baidu.com
[Name] + Baidu Search
)

)


Directory Operations

The first introduction is a function read from the directory, Opendir (), Readdir (), Closedir (), using the file handle is opened first, and then the iteration is 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 the return file directory under which the file is already in the directory program (0 file will return false).

Sometimes you need to know the directory information, you can use DirName ($path) and basename ($path), respectively, return the directory portion of the path and the file name part, the Disk_free_space ($path) to return to see space free space.

To create a command:

The code is as follows Copy Code

mkdir ($path, 0777)

, 0777 is the permission code, and the Umask () function can be set under non-window.

RmDir ($path)

The path to the $path file will be deleted.

DIR--The Directory class is also an important class to manipulate the file directory, there are 3 methods, Read,rewind,close, this is a copy object-oriented class, it first uses the open file handle, and then read by the way of the pointer. Here's a look at the PHP manual:

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

The properties of the file are also very important, including the creation time, the last modified time, the owner, the file group, the type, the size, and so on.

Here we focus on file operations.


Third, file operation

Read the file

The first is a file to see if it can read (permission problems), or there is no, we can use the Is_readable function to obtain information.:

The code is as follows Copy Code

$file = ' dirlist.php ';
if (is_readable ($file) = = False) {
Die (' file does not exist or cannot be read ');
} else {
echo ' presence ';
}
?>

The function of judging the existence of a file is also file_exists (shown below), but this is obviously not is_readable comprehensive. When a file exists, it can be used

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 earlier versions, you can create a handle to the file first, and then read all with the pointer:

$fso = fopen ($cacheFile, ' R ');
$data = Fread ($fso, FileSize ($cacheFile));
Fclose ($FSO);

There is also a way to read a binary file:

$data = Implode (', File ($file));

Write a file

and read the file the same way, first see if it can write:

The code is as follows Copy Code

$file = ' dirlist.php ';
if (is_writable ($file) = = False) {
Die ("I'm chicken feathers, I can't");
}
?>

If you can write it, 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'm chicken feathers, I can't ');
}
$data = ' I am contemptible, I want to ';
File_put_contents ($file, $data);
?>

file_put_contents function in the php5 of the newly introduced function (do not know the existence of the function_exists function first to judge) the lower version of PHP is not available, you can use the following way:

$f = fopen ($file, ' w ');
Fwrite ($f, $data);
Fclose ($f);

Replace it.

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

The code is as follows Copy Code

function Cache_page ($pageurl, $pagedata) {
if (! $fso =fopen ($pageurl, ' W ')) {
$this->warns (' cannot open cache file. '); /trigger_error
return false;
}
if (!flock ($fso, lock_ex)) {//LOCK_NB, exclusive type lock
$this->warns (' cannot lock cache file. '); /trigger_error
return false;
}
if (!fwrite ($fso, $pagedata)) {//write byte stream, serialize write to other format
$this->warns (' cannot write to cache file. '); /trigger_error
return false;
}
Flock ($fso, lock_un);//Release lock
Fclose ($FSO);
return true;
}

Copy, delete files

PHP Delete Files is very easy, with the unlink function simple operation:

The code is as follows Copy Code

$file = ' dirlist.php ';
$result = @unlink ($file);
if ($result = = False) {
Echo ' Mosquitoes have driven away ';
} else {
Echo ' cannot be driven away ';
}
?>

Can.

Copying files is also easy:

The code is as follows Copy Code

$file = ' yang.txt ';
$newfile = ' ji.txt '; # The parent folder of this file must be able to write
if (file_exists ($file) = = False) {
Die (' sample not online, cannot copy ');
}
$result = Copy ($file, $newfile);
if ($result = = False) {
echo ' Copy memory OK ';
}
?>

You can use the rename () function to rename a folder. The other operations are done by combining these functions.

Get file properties

I say a few common functions:
Gets the last modified time:

The code is as follows Copy Code

$file = ' test.txt ';
echo Date (' R ', Filemtime ($file));
?>

Returns a timestamp that says Unix, which is commonly used in caching techniques.

Related to the last time accessed Fileatime (), Filectime () when the permissions of the file, the owner, the metadata in all groups or other inode are updated, the Fileowner () function returns the file owner

$owner = Posix_getpwuid (Fileowner ($file));

(Non-Window System), Ileperms () Gets the file permissions,

The code is as follows Copy Code

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

FileSize () returns the number of bytes in the file size:

The code is as follows Copy Code

Output similar to: somefile.txt:1024 bytes

$filename = ' somefile.txt ';
Echo $filename. ': ' . FileSize ($filename). ' bytes ';

?>

To get all the information for 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.html www.bkjia.com true http://www.bkjia.com/PHPjc/632695.html techarticle in PHP file operation is nothing more than a file read and write operations, delete operations, judgment operations, permissions operations and some file search, and so on, I will learn from the PHP file Operation function ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.