Learn more about how to work with files and directories in PHP

Source: Internet
Author: User
Tags manual echo date file size flock php file php and file permissions

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, file operations in the CMS system this is necessary, very useful, we often encounter the production file directory, file (folder) editing and other operations, Now I do a detailed summary of these functions in PHP and examples of how to use, for the corresponding functions in detail, please consult the PHP manual, here only to summarize the focus and need to pay attention to the place.

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:

The following are the referenced contents:
<?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-Directory class is also an important class for manipulating file directories, there are 3 methods, Read,rewind,close, this is an object-oriented class, it first uses open file handle, and then read by pointer, here look at the PHP manual:

The following are the referenced contents:

<?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:

The following are the referenced contents:
<?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 obviously not is_readable comprehensive, when a file exists, you can use

The following are the referenced contents:

<?php
$file = "filelist.php";
if (file_exists ($file) = = False) {
Die (' File not present ');
}
$data = file_get_contents ($file);
echo htmlentities ($data);
?> but the file_get_contents function is not supported on a later version, you can 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:

The following are the referenced contents:

<?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:

The following are the referenced contents:

<?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:

The

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:

The following are the referenced contents:
<?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:

The following are the referenced contents:
<?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. The other operations are the combination of these functions can be achieved.

Get file properties

I say a few common functions:

Get the last modified time:

The following are the referenced contents:
<?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,

The following are the referenced contents:

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

FileSize () returns the number of bytes in the file size:
<?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:

The following are the referenced contents:
<?php
$file = ' dirlist.php ';
$perms = stat ($file);
Var_dump ($perms);
?>

The key corresponds to what can be consulted for details, no longer expanded here.

IV: 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.