PHP file read, write, delete operation (file and directory operations in PHP) _php instance

Source: Internet
Author: User
Tags echo date filegroup flock fread mkdir rewind file permissions
One: Catalog operations
The first is a function read from the directory, Opendir (), Readdir (), Closedir (), which is used to open the file handle first and then iterate over the following list:
Copy Code code as follows:

<?php
$base _dir = "filelist/";
$fso = Opendir ($base _dir);
echo $base _dir. " while ($flist =readdir ($FSO)) {
echo $flist. " <br/> ";
}
Closedir ($FSO)
?>

This is a program that returns the files in the directory below the file directory (0 files will return false).
Sometimes you need to know the directory information, you can use the DirName ($path) and basename ($path), respectively, to return the directory section of the path and file name part, available disk_free_space ($path) back to see space space.
   To Create a command:
mkdir ($path, 0777)
, 0777 is the permission code, and the Umask () function can be set under non window.
RmDir ($path)
The path will be deleted in the $path file.
DIR-The Directory class is also an important class for manipulating file directories, with 3 methods, Read,rewind,close, which is an object-oriented class that first uses open file handles and then reads with pointers. Here's a look at the PHP manual:
Copy Code code as follows:

<?php
$d = Dir ("/etc/php5");
echo "Handle:". $d->handle. "\ n";
echo "Path:". $d->path. "\ n";
while (false!== ($entry = $d->read ())) {
echo $entry. " \ n ";
}
$d->close ();
?>
[Code]
Output:
Handle:resource ID #2
Path:/ETC/PHP5
.
..
Apache
Cgi
Cli
The properties of the file are also important, including the creation time, last modified time, owner, filegroup, type, size, etc.
Here we focus on file operation.
   Two: File operation
Read files
First is a file to see whether can read (permission problem), or exist no, we can use the Is_readable function to get information.:
[Code]
<?php
$file = ' dirlist.php ';
if (is_readable ($file) = = False) {
Die (' File not present or unreadable ');
} else {
echo ' existence ';
}
?>

The function to determine the existence of a file is also file_exists (shown below), but this is clearly not is_readable comprehensive. When a file exists, you can use
Copy Code code as follows:

<?php
$file = "filelist.php";
if (file_exists ($file) = = False) {
Die (' File not present ');
}
$data = file_get_contents ($file);
echo htmlentities ($data);
?>

However, the file_get_contents function is not supported on a lower version, you can first create a handle to the file and then read it all with the pointer:
Copy Code code as follows:

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

There is also a way to read binary files:
$data = Implode ("", File ($file));
Learn more about how to work with files and directories in PHP
One: Introduction
In any computer device, files are all necessary objects, and in Web programming, the operation of files has always been a headache for web programmers, and the operation of files in the CMS system this is necessary, very useful, we often encounter the production file directory, file (folder) editing and other operations, Now I'm going to make a detailed summary of these functions in PHP and illustrate how to use them. For a detailed description of the corresponding function, please refer to the PHP manual. Here is a summary of the key points. and the places to be noted. (This is not in the PHP manual.)
Two: catalog operation
The first is a function read from the directory, Opendir (), Readdir (), Closedir (), which is used to open the file handle first and then iterate over the following list:
Copy Code code as follows:

<?php
$base _dir = "filelist/";
$fso = Opendir ($base _dir);
echo $base _dir. " while ($flist =readdir ($FSO)) {
echo $flist. " <br/> ";
}
Closedir ($FSO)
?>

This is a program that returns the files in the directory below the file directory (0 files will return false).
Sometimes you need to know the directory information, you can use the DirName ($path) and basename ($path), respectively, to return the directory section of the path and file name part, available disk_free_space ($path) back to see space space.
To Create a command:
mkdir ($path, 0777), 0777 is the permission code, the Umask () function can be set under non window.
RmDir ($path) will delete the path in the $path file.
DIR-The Directory class is also an important class for manipulating file directories, with 3 methods, Read,rewind,close, which is an object-oriented class that first uses open file handles and then reads with pointers. Here's a look at the PHP manual:
Copy Code code as follows:

<?php
$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 important, including the creation time, last modified time, owner, filegroup, type, size, etc.
Here we focus on file operation.
Three: File Operation
Read files
First is a file to see whether can read (permission problem), or exist no, we can use the Is_readable function to get information.:
Copy Code code as follows:

<?php
$file = ' dirlist.php ';
if (is_readable ($file) = = False) {
Die (' File not present or unreadable ');
} else {
echo ' existence ';
}
?>

The function to determine the existence of a file is also file_exists (shown below), but this is clearly not is_readable comprehensive. When a file exists, you can use
Copy Code code as follows:

<?php
$file = "filelist.php";
if (file_exists ($file) = = False) {
Die (' File not present ');
}
$data = file_get_contents ($file);
echo htmlentities ($data);
?>

However, the file_get_contents function is not supported on a lower version, you can first create a handle to the file and then read it all with the pointer:
$fso = fopen ($cacheFile, ' R ');
$data = Fread ($fso, FileSize ($cacheFile));
Fclose ($FSO);
There is also a way to read binary files:
$data = Implode ("", File ($file));
Write a file
and read the file in the same way, first see if you can write:
Copy Code code as follows:

<?php
$file = ' dirlist.php ';
if (is_writable ($file) = = False) {
Die ("I am chicken feathers, I cannot");
}
?>

If you can write it, you can use the File_put_contents function to write:
Copy Code code as follows:

<?php
$file = ' dirlist.php ';
if (is_writable ($file) = = False) {
Die (' I'm chicken feathers, I can't ');
}
$data = ' I am contemptible, I want ';
File_put_contents ($file, $data);
?>

The newly introduced function of the file_put_contents function in PHP5 (if you don't know it, use the Function_exists function to determine first) the lower version of PHP is not available, and you can use the following methods:
$f = fopen ($file, ' w ');
Fwrite ($f, $data);
Fclose ($f);
Replaced.
When writing a file, you sometimes need to lock and then write:
Copy Code code as follows:

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 write to other format
$this->warns (' Unable to write cache file. '); /trigger_error
return false;
}
Flock ($fso, Lock_un);/release lock
Fclose ($FSO);
return true;
}

copying, deleting files
PHP Delete file is very easy to use the unlink function simple operation:
Copy Code code as follows:

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

Can.
Copying files is also easy:
Copy Code code as follows:

<?php
$file = ' yang.txt ';
$newfile = ' ji.txt '; # This file parent folder must be able to write
if (file_exists ($file) = = False) {
Die (' sample not on-line, cannot copy ');
}
$result = Copy ($file, $newfile);
if ($result = = False) {
echo ' Copy memory OK ';
}
?>

You can use the rename () function to rename a folder. Other operations are a combination of these functions can be achieved.
Get file properties
I say a few common functions:
Get the last modified time:
Copy Code code as follows:

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

Returns the Unix-time timestamp, which is commonly used in caching techniques.
Also relevant is the time to obtain the last accessed Fileatime (), Filectime () when the file permissions, owner, all groups or other inode metadata is updated, Fileowner () function returns the file owner $owner = posix_ Getpwuid (Fileowner ($file));(Non-Window System), Ileperms () to obtain permissions for the file,
Copy Code code as follows:

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

FileSize () returns the number of bytes in the file size:
Copy Code code as follows:

<?php
Output similar to: somefile.txt:1024 bytes
$filename = ' somefile.txt ';
Echo $filename. ': ' . FileSize ($filename). ' bytes ';
?>

Get all the information for a file there is a function stat () function that returns an array:
Copy Code code as follows:

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

The key corresponds to what can be consulted for details, no longer expanded here.
Four: Concluding remarks
Above I briefly summed up a few file operations, if you are proficient in the above listed functions, already in the operation of the time is not a big problem, PHP file operation function Changes faster, now is very strong, the file this part is also learning PHP very important part, I hope not to ignore.

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.