How PHP creates and modifies file content

Source: Internet
Author: User
Tags flock fread learn php rewind
This article mainly share with you how PHP creates and modifies the contents of the file, hoping to help everyone.


File_put_contents Writing Files

Let's start by learning the first way to write a file:

int file_put_contents (string $ file path, string $ write data])

Function: Writes a string to the specified file (it empties the original content) and creates the file if the file does not exist. The length of the bytes written is returned

<?php   $data = "Learn php in Topic.alibabacloud.com, sister tickets no longer words!" ";   $numbytes = file_put_contents (' binggege.txt ', $data); If the file does not exist to create the file and write the content if   ($numbytes) {       echo ' write succeeds, we read the results to try: ';       echo file_get_contents (' binggege.txt ');   } else{       Echo ' write failed or no permission, pay attention to check ';   }? >

Fwrite with fopen for write operations

int fwrite (resource $ file resource variable, string $ write [, int length])
<?php   $filename = ' test.txt ';   $fp = fopen ($filename, "w");  W is a write mode, and the file does not exist to create a file write.   $len = fwrite ($fp, ' I am a wolf from the north, but frozen in the south as a dog ');   Fclose ($FP);   Print $len. ' Byte is written to \ n ';? >

Summary: 1. Whether or not new will open the file to re-write 2. The original file content will be overwritten 3. File does not exist will be created

Let's compare the following patterns:

Mode Description
R Read-only cannot use fwrite write
r+ Can operate read and write
W can only write function
w+ You can read and write

The difference between a mode and W mode

This is also the code below, we changed to a mode.

<?php   $filename = ' test.txt ';   $fp = fopen ($filename, "a");   $len = fwrite ($fp, ' University is confused, topic.alibabacloud.com learn PHP to give you hope ');   echo  $len. ' Byte is written to \ n ';? >

Open the page to execute this code, you will find: every refresh, the file will be more than one paragraph : The university is confused, topic.alibabacloud.com learn PHP to give you hope.

Summarize:

Mode Summary
X Each write kills the contents of the original file, and the file does not exist to be created
A Each write appends content to the end of the file

The difference between x mode and W mode

Let's experiment with this code again and change to x mode:

<?php   $filename = ' test.txt ';   $fp = fopen ($filename, "X");   $len = fwrite ($fp, ' University is confused, topic.alibabacloud.com learn PHP to give you hope ');   echo  $len. ' Byte is written to \ n ';? >

We will find:

1. There will be an error when the file is present 2. If you change the $filename to another file name, you can. However, again the time to refresh the error 3.x+ is enhanced x mode. can also be used when reading.

PHP Create temporary files

Let's take a look at this function:

Resource Tmpfile ()

Function: Creates a temporary file that returns the resource type. Closing the file is deleted.

PHP move, copy, and delete files

Renaming files

BOOL Rename ($ old name, $ new name);

This function returns a bool value and changes the old name to a new one.

<?php//old filename $filename = ' test.txt ';//new file name $filename2 = ' ReName.txt. '; /Modified name rename ($filename, $filename 2);? >

Copying files

Copying a file is equivalent to cloning a technology and cloning a new thing into something. Two of them look exactly alike.

BOOL Copy (source file, destination file)

Function: Copies the source file of the specified path to the location of the destination file.

<?php    //old file name    $filename = ' copy.txt ';        New file name    $filename 2 = ' copy2.txt ';        Modify the name.    copy ($filename, $filename 2);? >

Note: 1 • The copied file name cannot be copied with the same name as the source file; 2. Copy the file name if it already exists, copy the contents of the source files to replace the contents of the copied files.

deleting files

Deleting a file deletes a file of the specified path, but the deletion is deleted directly. Using a Windows PC, you can't see this file in the Recycle Bin.

You'll only find out that this file is gone.

BOOL Unlink (file with path specified)
<?php   $filename = ' test.txt ';   if (unlink ($filename)) {       echo  "deleted the file successfully $filename!\n";   } else {       echo "delete $filename failed!\n";   }? >

PHP Detection File Property function

BOOL File_exists ($ Specify File name or file path) function: whether the file exists. BOOL Is_readable ($ Specify File name or file path) function: Whether the file is readable bool is_writeable ($ Specify File name or file path) function: Whether the file is writable bool Is_executable ($ Specifies the file name or path) Function: Whether the file can execute bool Is_file ($ specified file name or file path) function: is the file bool Is_dir ($ specified file name or file path) feature: is the directory void Clearstatcache (void) Function: Clear state cache of files

Let's talk about the first example, file lock. If it is already installed, the installation lock will prompt for installation, or it will continue to install.

We assume that the installation interface URL is: install.php, the installation of the lock file is Install.lock. We can detect if the Install.lock file exists.

<?phpif (file_exists (' Install.lock ')) {   echo ' is installed, please do not install again ';   Exit;}? >

Common functions and constants for PHP files

| platform | separator |--|--| | Windows |
| Unix-like |/

We will use a constant:

Directory_separator//On behalf of back slash

Because file is a predefined constant for PHP, there is no way to change it if you need to make file adaptive to the operating system. So, do not use file, you can use the custom constants, and the file processing, as follows:

<?php//Gets the file path strength, and then uses Directory_separator to replace the '/', ' \ \ ' In the path, $_current_file = Str_replace (Array ('/', ' \ \ '), Directory_ SEPARATOR, __file__);//re-define constants, output formatted file path strength define (' __cur_file__ ', $_current_file); Echo __cur_file__;      D:\myphp\test\inidex.php?>

File pointer manipulation function

Rewind (Resource handle) function: pointer back to the beginning fseek (resource handle, int offset [, int from_where]) function: The file pointer moves backward the specified character
<?php> demo2.txt    >     aaaaa    >     bbbbb    >     11111    >     22222$fp = fopen (' Demo2.txt ', ' r+ ');//read 10 characters,//read the first 10 bytes (space is one, newline counts two bytes) echo fread ($FP, 10);//pointer set back to the beginning    rewind ($fp);    AAAAA bbb//Read 10 more times to see what the output is echo ' <br> '; Echo fread ($fp, ten);     AAAAA Bbbecho ' <br> ';//The file pointer moves backwards by 10 characters (the current pointer is at the beginning of the position) of Echo fseek ($FP, ten);     The return value of fseek is 0echo ' <br> ';//And look at what is output in the file echo fread ($FP, ten);     BB 11111 echo ' <br> '; fclose ($fp);? >

FileSize the size of the detected file

<?php$filename = ' demo.txt '; Echo $filename. ' File size is: '. FileSize ($filename). ' bytes ';? >

Other functions for manipulating files

Actually there are some other functions that manipulate the file, read the file

Name of function function
File To read an entire file into an array
Fgets Reads a row from the file pointer and returns false at the end of the read
Fgetc Reads a character from the file pointer and returns false at the end of the read
Ftruncate Truncates a file to a given length

Fgetc

Open $fp = fopen (' demo2.txt ', ' r+ ') with an increased r mode;//You will find that each time you read only one character echo  fgetc ($fp). ' <br/> '; Read only one character//I want to read all can, read the result assignment once to $stringwhile ($string = fgetc ($fp)) {    echo $string;    Read not to return false}

Fgets

Open $fp = fopen (' demo.txt ', ' r+ ') with increased r mode;//You will find an open line of Echo fgets ($FP) every time you read it; Echo fgets  ($FP); Echo  fgets ($FP); Echo  fgets ($fp);   Cannot read return false

ftruncate return value of 1 int

Ftruncate ($file, Len); the length of the intercept is greater than the length of the file content and is filled with empty characters
Open the Demo.txt file above us $file = fopen ("Demo.txt", "A +");//You can count the number of 20 words how long to see if it achieves the effect of Echo ftruncate ($file,); Fclose ($file) ;

The time function of the file

function function Description
Filectime File creation time
Filemtime File modification Time
Fileatime File last access time
<?php$filename = ' demo.txt ';    The last access time for the IF (file_exists ($filename)) {       echo ' $filename file is: '  . Date ("Y-m-d h:i:s", Fileatime ($filename));       The echo ' $filename file was created at: '. Date ("Y-m-d h:i:s", Filectime ($filename));          The modified time for Echo ' $filename file is: '. Date ("Y-m-d h:i:s", Filemtime ($filename));}        ? >

PHP file lock mechanism

Use of File Locks:

If a person is writing a file, the other person also writes a file to write the file. In this case, if you encounter a certain probability of collision, do not know who is the operation of the subject. So, this time we introduce the lock mechanism. If user A writes or reads this file, the file is added to the share. I can read it, and others can read it. But if I had this with the time. I use an exclusive lock. This file belongs to me, you don't move unless I release the file lock.

Note: After the file lock is added, be aware of the release.

PHP file lock mechanism file lock mechanism generally in a single open file when the effect is not seen at all. This piece of learning has a little abstraction.

Let's not think about how it's going to come true.

Why can't you see the effect? Answer: Because the computer operation is too fast, basically is the millisecond level. So this experiment is actually not to see the effect.

This chapter understands the basic concepts of file locks and is familiar with file lock functions and lock mechanisms.

Use of File Locks:

If a person is writing a file, the other person also writes a file to write the file. In this case, if you encounter a certain probability of collision, do not know who is the operation of the subject. So, this time we introduce the lock mechanism. If user A writes or reads this file, the file is added to the share. I can read it, and others can read it. But if I had this with the time. I use an exclusive lock. This file belongs to me, you don't move unless I release the file lock.

Note: Regardless of the file lock, pay attention to release.

Let's take a look at this function:

BOOL Flock (resource $handleFile, int $operation)

Let's take a look at the lock type:

Lock Type Description
Lock_sh Get a shared lock (read program)
Lock_ex Acquire an exclusive lock (program written)
Lock_un Release lock (whether shared or exclusive)

We then add an exclusive lock to the demo2.txt to write the operation.

    $fp = fopen ("Demo2.txt", "r+");        Perform an exclusive lock    if (Flock ($FP, lock_ex)) {            echo ' 1 ';            Fwrite ($FP, "The file is my exclusive at this time of yo \ n");            Release lock        Flock ($fp, lock_un);    } else {        echo "lock failed, may be in action, this time cannot lock the file";    }        Fclose ($FP);

Description

1. In the previous example, I added an exclusive lock to the file in order to write the file.

2. If my operation is complete, after the write is completed, the exclusive lock is removed.

3. If you are reading a file, you can add a shared lock according to the same processing idea.

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.