PHP file operation instance code _ php Tutorial-PHP Tutorial

Source: Internet
Author: User
Tags flock
Php file operation instance code. The following code copies a simple instance :? Phpif (! Is_dir (txt) to determine whether the txt is a folder directory {mkdir (txt); create a folder directory named txt $ openfopen (first send a simple instance

The code is as follows:


If (! Is_dir ('txt ') // determines whether the txt file is a folder directory.
{
Mkdir ('txt '); // create a directory named txt
$ Open = fopen ('txt/in.txt ', "w +"); // open a file in read/write mode.
If (is_writable ('txt/in.txt ') // if this file is in writable mode
{
If (fwrite ($ open, "Today is a wonderful day and you must be happy! --")> 0) // write content
Fclose ($ open); // close the file
Echo "script" alert ('write succeeded '); script "; // A success prompt is displayed.
}
}
Else
{
If (is_file ('txt/in.txt ') // The Directory contains the in.txt file.
{
If (is_readable ('txt/in.txt ') // checks whether the file is readable.
{
Echo file_get_contents ('txt/in.txt '); // output text information
Unlink ('txt/in.txt '); // delete the file in.txt
Rmdir ('txt '); // delete the Directory
}
}
}
?>


I. INTRODUCTION

In any computer device, files are essential objects. in web programming, file operations have always been a headache for web programmers, file operations are required and useful in the cms system. we often encounter operations such as file directory generation and File (folder) editing, now I will make a detailed summary of these functions in php and demonstrate how to use them in an example ., for more information about the corresponding functions, see The php Manual. here we will only summarize the key points. and precautions. (This is not available in the php manual .)

II. Directory operations

First, we will introduce a function that reads data from a directory, such as opendir (), readdir (), and closedir (). when using this function, we will first open the file handle and then list it through iteration:

The code is as follows:


$ 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 under the file directory that are already in the Directory (0 files will return false ).

If you need to know the directory information, you can use dirname ($ path) and basename ($ path) to return the directory and file name respectively. disk_free_space ($ path) is available) returns the free space of the viewing space.

Create Command:

Mkdir ($ path, 0777)

, 0777 is the permission code, which can be set by the umask () function in a non-window environment.

Rmdir ($ path)

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

The dir -- directory class is also an important class for operating file directories. It has three methods: read, rewind, and close. this is an object-oriented class. it first uses open file handles, and then read it by pointer ., see the php manual here:

The code is as follows:


$ 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, and so on.

Next we will focus on file operations.


III. file operations

● Read files

The first is to check whether a file can be read (Permission problem) or whether the file exists. we can use the is_readable function to obtain information .:

The code is as follows:


$ File = 'dirlist. php ';
If (is_readable ($ file) = false ){
Die ('file does not exist or cannot be read ');
} Else {
Echo 'exist ';
}
?>


The file_exists function is used to determine the existence of the file (as shown below), but this is obviously not comprehensive. it can be used when a file exists.

The code is as follows:


$ 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 in earlier versions. you can create a handle for the file and then read all with pointers:

$ 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 files

The same way as reading files, let's see if it can be written:

The code is as follows:



$ File = 'dirlist. php ';
If (is_writable ($ file) = false ){
Die ("I'm a chicken feather, I can't ");
}
?>


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

The code is as follows:


$ File = 'dirlist. php ';
If (is_writable ($ file) = false ){
Die ('I am a chicken feather, I can't ');
}
$ Data = 'I am cool, I want ';
File_put_contents ($ file, $ data );
?>


File_put_contents functions newly introduced functions in php5 (if you do not know the existence, use the function_exists function to judge first) are unavailable in lower versions of php. you can use the following method:

The code is as follows:


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


Replaced.

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

The code is as follows:


Function cache_page ($ pageurl, $ pagedata ){
If (! $ Fso = fopen ($ pageurl, 'w ')){
$ This-> warns ('cache file cannot be opened. '); // trigger_error
Return false;
}
If (! Flock ($ fso, LOCK_EX) {// LOCK_NB, locking
$ This-> warns ('unable to lock the cache file. '); // trigger_error
Return false;
}
If (! Fwrite ($ fso, $ pagedata) {// write byte stream, serialize writes to other formats
$ This-> warns ('unable to write the cache file. '); // trigger_error
Return false;
}
Flock ($ fso, LOCK_UN); // release lock
Fclose ($ fso );
Return true;
}


● Copy and delete an object

Php is very easy to delete files. it is easy to use the unlink function:

The code is as follows:


$ File = 'dirlist. php ';
$ Result = @ unlink ($ file );
If ($ result = false ){
Echo 'mosquito drive away ';
} Else {
Echo 'cannot get rid of it ';
}
?>


You can.

It is also easy to copy files:

The code is as follows:


$ File = 'ang.txt ';
$ Newfile = 'ji.txt '; # The parent folder of this file must be writable.
If (file_exists ($ file) = false ){
Die ('small samples are not online and cannot be copied ');
}
$ Result = copy ($ file, $ newfile );
If ($ result = false ){
Echo 'copy memory OK ';
}
?>


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

● Get file attributes

I will talk about several common functions:
Obtain the last modification time:

The code is as follows:


$ File = 'test.txt ';
Echo date ('R', filemtime ($ file ));
?>


The unix timestamp is returned, which is commonly used in cache technology.

Related to obtaining the last access time fileatime (), filectime () when the object's permission, owner, metadata in all groups or other inode is updated, fileowner () function return file owner

$ Owner = posix_getpwuid (fileowner ($ file ));

(Non-window system), ileperms () get file permissions,

The code is as follows:


$ File = 'dirlist. php ';
$ Perms = substr (sprintf ('% O', fileperms ($ file),-4 );
Echo $ perms;
?>


Filesize () returns the number of bytes of the file size:

The code is as follows:


// The output is similar to: 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 () that returns an array:

The code is as follows:


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


For details about the corresponding key, we will not expand it here.

IV. Conclusion

I have briefly summarized several file operations above. if you are familiar with the functions listed above, there are no major problems during operations. the Function operations in the PHP file are fast changing, now it is very powerful, and this part of the file is also a very important part of learning php, hope not to ignore.

The pipeline code is as follows :? Php if (! Is_dir ('txt ') // Determine whether the txt is a folder directory {mkdir ('txt'); // create a folder named txt directory $ open = fopen ('...

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.