Directory operations and file operations in PHP

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

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.)

Second, the directory 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:

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

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:

<?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, the last modification time, the owner, the filegroup, the type, the size, and so on.

Here we focus on file operation.

Third, file operation

A, read the document

First is a file to see whether can read (permission problem), or exist no, we can use the Is_readable function to get information.

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

<?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));

B, write the document

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

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

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

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

C, copy, delete files

PHP Delete file is very easy to use the unlink function simple operation:

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

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

D, get file properties

I say a few common functions:

Get the last modified time:

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

Returns the Unix-time timestamp, which is commonly used in caching techniques.

Related also to get last accessed time Fileatime (), Filectime () When file permissions, owner, all groups or other inode metadata is updated, Fileowner () function returns file owner

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

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

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

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

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

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.