Home Backend Development PHP Tutorial PHP5 Tutorial File Operation_PHP Tutorial

PHP5 Tutorial File Operation_PHP Tutorial

Jul 21, 2016 pm 02:53 PM
php5 web one exist object operate Tutorial document yes computer equipment

1. Introduction

In any computer device, files are necessary objects, and in web programming, the operation of files has always been a headache for web programmers, and , file operations are necessary and very useful in the CMS system. We often encounter operations such as generating file directories, editing files (folders), etc. Now I will give a detailed summary of these functions in PHP and demonstrate how to use them with examples. ., for a detailed introduction to the corresponding functions, please refer to the PHP manual. Here we only summarize the key points and points that need attention. (This is not available in the PHP manual.) (www.bkjia.com)

II , Directory operation

The first thing introduced is a function that reads from the directory, opendir(), readdir(), closedir(). When used, the file handle is opened first, and then iteratively listed:

$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 and directories under the file directory (0 files will return false).

Sometimes you need to know the directory information, you can use dirname($path) and basename($ path), respectively returns the directory part and file name part of the path. You can use disk_free_space($path) to return the free space.

Creation command:

mkdir($path,0777)


, 0777 is the permission code, which can be set by the umask() function under non-window conditions.

rmdir($path)


will delete the path in $ The file of path.

dir -- directory class is also an important class for operating file directories. It has three methods, read, rewind, and close. This is a pseudo-object-oriented class. It first uses open files. The handle is then read using a pointer. See the PHP manual here:

$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, etc.

Let’s focus on file operations below.

3. File operations

A. Reading files

First, check whether a file can be read (permission issue), or whether it exists. We can use the is_readable function to obtain the information.

$file = 'dirlist.php';
if (is_readable($file) == false) {
    die('The file does not exist or cannot be read ');
} else {
echo 'exists';
}
?>


The function to determine the existence of a file also includes file_exists (demoed below ), but this is obviously not as comprehensive as is_readable. When a file exists, you can use

$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 lower versions. You can first create a handle to the file, and then use a pointer to read all of it:

$fso = fopen($cacheFile, 'r');
$data = fread($fso, filesize($cacheFile));
fclose($fso);


There is another way to read binary File:

$data = implode('', file($file));


B. Writing files

is the same as reading files , first see if you can write:

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


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

$file = 'dirlist.php';
if (is_writable($file) == false) {
die('I am a chicken, I can't');
}
$data = 'I am despicable, I want';
file_put_contents ($file, $data);
?>


The file_put_contents function is newly introduced in php5 function (if you don’t know it exists, use the function_exists function to determine it first). Lower versions of PHP cannot be used. You can use the following method:

$f = fopen($file, 'w');
fwrite( $f, $data);
fclose($f);

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 Lock the cache file.');//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize writes other formats
$this->warns('Unable to write to cache file.');//trigger_error
return false;
}
flock($fso,LOCK_UN);//Release lock
fclose($fso);
return true;
}


C. Copy and delete files

It is very easy to delete files in php, use the unlink function: 🎜>

$file = 'dirlist.php';
$result = @unlink ($file);
if ($result == false) {
echo 'Mosquitoes are driven away';
} else {
echo 'Cannot be driven away';
}
?>

That's it.

Copying files is also easy:

$file = 'yang.txt';
$newfile = 'ji.txt'; # The parent folder of this file must be writable
if (file_exists($file) == false) {
die ('The sample is 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 file Clip. Other operations can be achieved by combining these functions.

D. Get file attributes

I will talk about a few common functions:

Get the latest Modification time:

$file = 'test.txt';
echo date('r', filemtime($file));
?>

The returned timestamp is the Unix timestamp, which is commonly used in caching technology.

Relevantly, fileatime() and filectime() are used to obtain the last accessed time and file permissions. The time when the owner, metadata in all groups or other inodes is updated, the fileowner() function returns the file owner

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


(non-window system), ileperms() obtains file permissions,

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

filesize() returns the file size in bytes Number:

// Output is similar: somefile.txt: 1024 bytes

$filename = 'somefile.txt';

echo $filename . ': ' . filesize($filename) . ' bytes';

?>

To get all the information of the file, there is a function stat() function that returns an array:

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

You can check the detailed information about what the key corresponds to, which will not be expanded here.

4. Conclusion

I briefly summarized several file operations above. You are proficient in the functions listed above, and there are no major problems when operating them. The functions of PHP file operations change quickly and are now very powerful. The file part is also a very important part of learning PHP. I hope you will not ignore it

http://www.bkjia.com/PHPjc/371497.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371497.htmlTechArticle1. Introduction In any computer device, files are necessary objects, and in web programming, File operations have always been a headache for web programmers, and file operations in the cms system...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

2024 CSRankings National Computer Science Rankings Released! CMU dominates the list, MIT falls out of the top 5 2024 CSRankings National Computer Science Rankings Released! CMU dominates the list, MIT falls out of the top 5 Mar 25, 2024 pm 06:01 PM

The 2024CSRankings National Computer Science Major Rankings have just been released! This year, in the ranking of the best CS universities in the United States, Carnegie Mellon University (CMU) ranks among the best in the country and in the field of CS, while the University of Illinois at Urbana-Champaign (UIUC) has been ranked second for six consecutive years. Georgia Tech ranked third. Then, Stanford University, University of California at San Diego, University of Michigan, and University of Washington tied for fourth place in the world. It is worth noting that MIT's ranking fell and fell out of the top five. CSRankings is a global university ranking project in the field of computer science initiated by Professor Emery Berger of the School of Computer and Information Sciences at the University of Massachusetts Amherst. The ranking is based on objective

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

What should I do if there is no sound in the system after win11 update? How to solve the problem of no sound in win11 device What should I do if there is no sound in the system after win11 update? How to solve the problem of no sound in win11 device Jun 25, 2024 pm 05:19 PM

After some users have updated and upgraded the win11 system, the computer has no sound. The problem of loving you is usually caused by no device, missing sound card driver, or unknown error. So how should we solve these problems? , this issue of win11 tutorial is here to answer everyone’s questions. Next, let’s take a look at the detailed steps. Solution to no sound after win11 upgrade: 1. No device 1. If we are using a desktop computer, it is probably because there is no device. 2. Because ordinary desktop computers do not come with built-in speakers, we need to plug in speakers or headphones to have sound. 2. The sound card driver is missing 1. After we update the Win11 system, the original sound card or audio device driver may not be available.

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

PHP Tutorial: How to convert int type to string PHP Tutorial: How to convert int type to string Mar 27, 2024 pm 06:03 PM

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

Apple Vision Pro receives major update, visionOS 1.3 RC version released Apple Vision Pro receives major update, visionOS 1.3 RC version released Jul 25, 2024 pm 04:25 PM

According to news on July 24, Apple recently pushed the highly anticipated visionOS1.3RC version update to VisionPro headset users. This update marks Apple’s continued innovation and progress in the field of virtual reality. Although the official did not clearly disclose the specific content of this update, users generally expect it to include performance optimization, functional improvements, and bug fixes. The internal version number of this update is 21O771, 141 days have passed since the last update. However, due to caching issues with node server configurations in Apple's various regions, some users may experience delays in upgrades and updates. Apple recommends users to back up their data before installing updates to ensure information security. 1.VisionPro users can use the "

How to stop your iPad from ringing when your iPhone rings How to stop your iPad from ringing when your iPhone rings Apr 17, 2024 pm 01:50 PM

Does your iPad ring every time someone calls you on your iPhone? In almost all cases, the benefits of continuity features in the Apple ecosystem usually help. However, if your iPad starts ringing, it can be distracting even if you don't want to. However, there is a way to fix this problem and set your iPad (or any other nearby device) to ring automatically. How to make your iPad not ring when your iPhone rings You need to adjust the phone settings in the iPhone Settings tab. Change the "Call on other devices" setting there to prevent the iPad ringtone from being used during incoming calls on your iPhone. Step 1 – Look for the ⚙️ logo on your phone’s App Library

See all articles