1. File directory operation
The top stop record is the disk root directory, with '/' or '/'
Current directory./
.. /Represents the Apache directory, the Htdocs directory
1. Create and delete directories mkdir
Copy Code code as follows:
<?php
if (mkdir ("./path", 0700))//Create the path directory in the current directory
echo "Create success";
?>
2. Get and change the current directory
Use the GETCWD () function to get to the current working directory, which has no parameters. Success returns the current working directory and returns false if it fails
3. Open and close the directory handle
Opendir ($dir)
Closed ($dir _handle)
4. Read Directory Contents
Readdir (), which is an open directory handle, and the while loop enables traversal of the directory
5. Gets the directories and files in the specified path.
Array Scandir (string $directory [, int $sorting _order [, Resource $context]])
Description: $directory to the specified path. Parameter $sorting_order is sorted alphabetically by default, if set to 1 for alphabetical descending order.
$context is an optional parameter, a resource variable that can be generated using the Stream_context_create () function, which holds some data related to the specific action object.
Function succeeds returns an array containing all the directories and file names under the specified path, False if failed
2. General methods of manipulating documents
3. Open and close the file
1. Open the file
Resource fopen (String $filename, String $mode [, bool $use _include_path [, Resource $context]])
$filename parameters. The fopen () function binds the name resource specified by the $filename parameter to a stream
$mode parameters. The $mode parameter specifies the mode in which the fopen () function accesses the file, as shown in table 4.5.
$mode
Description
' R '
Read-only to open the file and start reading from the file header
' R+ '
Read and write to open the file, start reading from the file header
' W '
Write to open the file and point the file pointer to the file header. If the file already exists, delete the existing content and try to create it if the file does not exist
' w+ '
Read and write to open the file, pointing the file pointer to the file header. If the file already exists, delete the existing content and try to create it if the file does not exist
A
Write to open the file, point the file pointer to the end of the file, if the file already has content will start at the end of the file. If the file does not exist, try to create it
' A + '
Read and write to open the file, pointing the file pointer at the end of the file. If the file already has content, it will begin reading and writing from the end of the file. If the file does not exist, try to create it
' X '
Create and write to open the file, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE, and a e_warning level error message is generated. If the file does not exist, try to create it. This option is supported by ph and later versions and can only be used for local files
' x+ '
Create and read-write to open the file, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE, and a e_warning level error message is generated. If the file does not exist, try to create it. This option is supported by ph and later versions and can only be used for local files
' B '
Binary mode, which is used to connect behind other modes. If the file system can differentiate between binary and text files (Windows distinguishes, and UNIX does not differentiate), you need to use this option, which is recommended for maximum portability
$use _include_path parameters. If you need to search for files in include_path (PHP include path, in PHP configuration file settings),
You can set the value of an optional parameter $use _include_path to 1 or true, and the default is False.
$context parameters. The optional $context parameter is used only when the file is opened remotely (such as through HTTP), which is a resource variable,
It holds some data about the specific action object of the fopen () function. If fopen () is opening an HTTP address,
This variable records the request type of the HTTP request, the HTTP version, and other header information, and if the FTP address is open,
The passive/Active mode of the FTP may be logged
2. Close the file
BOOL Fclose (Resource $handle)
4. Writing of files
File must be opened before it is written, and it will not exist before it is created, typically with the fopen () function
Fwrite (). write to file after file is opened
int fwrite (Resource $handle, string $string [, int $length])
Description: Parameter $handle is the file handle that is written.
$string is the string data that will be written to the file.
$length is an optional parameter, and if $length is specified, the write is stopped when the first $length byte of data in $string is written.
File_put_contents () function. PHP 5 also introduces the File_put_contents () function. The function of this function is the same as the function of calling fopen (), fwrite (), and the fclose () function in turn. The syntax format is as follows:
int file_put_contents (string $filename, String $data [, int $flags [, Resource $context]])
Description: $filename is the name of the file to write data to.
$data is the string to write, $data can also be an array, but not a multidimensional array.
When you write data to a remote file using FTP or HTTP, you can use optional parameters $flags and $context, which are not specifically described here.
When the write succeeds, the function returns the number of bytes written, otherwise it returns false.
Fputcsv () function. CSV is a more commonly used file format, usually with. csv as the extension. The CSV format regards a row of files as a record, with the fields in the record separated by commas.
Use the Fputcsv () function in PHP to format the specified array into a CSV file format and write the current line to which the file pointer points. The syntax format is as follows:
int Fputcsv (Resource $handle [, Array $fields [, String $delimiter [, String $enclosure]]])
Description: Parameter $handle is the file handle to write.
The parameter $fields is the array to format.
The optional $delimiter parameter is used to set the field delimiter (only one character is allowed) and the default is a comma.
Optional $enclosure parameter set field wrap character (only one character allowed), default to double quotes
5 reading of files
1. Read any length
The Fread () function can be used to read the contents of a file in the following syntax format:
string fread (int $handle, int $length)
Description: Parameter $handle is a file pointer that has been opened.
The $length is the maximum number of bytes read, with a maximum value of 8192 $length.
If the file end sign (EOF) is encountered before the $length byte count is read, the read character is returned and the read operation is stopped.
Returns the read string if the fetch succeeds, or FALSE if the error returns.
Note: When you display the contents of a file after reading it, the text may contain characters that cannot be displayed directly, such as HTML markup.
You need to use the Htmlspecialchars () function to convert HTML tags into entities to display the characters in the file.
2. Read the entire file
The file () function. The file () function is used to read entire files into an array, in the following syntax format:
Array file (string $filename [, int $use _include_path [, Resource $context]])
Note: This function is to return the file as an array, each cell in the array is the corresponding line in the file, including line breaks,
Returns False if it fails. Parameter $filename is the file name that is read, and the $use_inclue_path and $context of the parameters are the same as those described earlier
ReadFile () function. The ReadFile () function is used to output the contents of a file into the browser, with the following syntax:
int ReadFile (string $filename [, bool $use _include_path [, Resource $context]])
Fpassthru () function. The Fpassthru () function reads the given file pointer from the current location to EOF and writes the result to the output buffer.
To use this function, you must first open the file using the fopen () function, and then pass the file pointer as a parameter to the Fpassthru () function.
The Fpassthru () function sends the contents of the file pointed to by the file pointer to the standard output. Returns False if the operation successfully returns the number of bytes read.
File_get_contents () function. The file_get_contents () function reads the entire or partial file contents into a string.
Functionality is the same as the ability to invoke the fopen (), Fread () and fclose () functions in turn. The syntax format is as follows:
String file_get_contents (string $filename [, int $offset [, int $maxlen]])
Description: $filename is the name of the file to read, optional parameter $offset can specify the offset from the header of the file.
The function can return content that is $maxlen at the beginning of the position specified from the $offset. If it fails, the function returns false
3. read one row of data
Fgets () function. The fgets () function reads a line of text from a file, and the syntax is as follows:
String fgets (int $handle [, int $length])
Description: $handle is a file handle that is already open, optional parameter $length specifies the maximum number of bytes returned, taking into account the line terminator,
You can return a string of up to length-1 bytes. If $length is not specified, the default is 1024 bytes
The FGETSS () function is essentially the same as fgets (), but the FGETSS () function attempts to remove any HTML and PHP tags from the read text.
Fgetcsv () function. The Fgetcsv () function can read the current row of the specified file, parse out the fields in CSV format, and return an array containing the fields.
The syntax format is as follows:
Array fgetcsv (int $handle [, int $length [, String $delimiter [, String $enclosure]]]
4. Read one character
Fgetc () function. The fgetc () function can read a character from a file pointer, in the form of:
String fgetc (Resource $handle)
This function returns a character in the file pointed to by the $handle pointer, and returns FALSE if EOF is encountered
5. Reading files using the specified format
FSCANF () function. The fscanf () function can read the data in a file, format it according to the specified format, and return an array. The syntax format is as follows:
Mixed fscanf (Resource $handle, String $format [, Mixed &$ ...])
Any whitespace in the format string matches any whitespace in the input stream.
This means that even the tab "T" in the format string matches a space character in the input stream.
6. File Upload and download
1. File Upload
File uploads can be implemented by submitting HTML forms. After the file is uploaded, the default is stored in the temporary directory, which must be removed from the temporary directory or moved to another location
Use PHP's Move_uploaded_file () to move it to another location
The Move_uploaded_file () function syntax is formatted as follows:
BOOL Move_uploaded_file (String $filename, String $destination)
Note: You need to check to see if the file was uploaded via an HTTP post before moving the file, which can be used to ensure that a malicious user cannot spoof a script to access a file that cannot be accessed.
You need to use the Is_uploaded_file () function. The function's argument is a temporary filename for the file, and the function returns True if the file was uploaded via an HTTP post.
Example 4.5 move a GIF picture file uploaded by an HTML form to an HTML directory
Copy Code code as follows:
<form enctype= "Multipart/form-data" action= "" method= "POST" >
<input type= "File" name= "MyFile" >
<input type= "Submit" name= "Up" value= "Upload file" >
</form>
<!--HTML form-->
<?php
if (Isset ($_post[' up '))
{
if ($_files[' myFile '] [' type ']== ' image/gif ')//determine if the file format is GIF
{
if ($_files[' myFile '] [' ERROR ']>0]//Judge whether the upload is wrong
echo "Error:". $_files[' myFile ' [' Error ']; Output error message
Else
{
$tmp _filename=$_files[' myFile ' [' tmp_name ']; Temporary file name
$filename =$_files[' myFile ' [' name ']; File name for upload
$dir = "html/";
if (Is_uploaded_file ($tmp _filename))//Determine if uploading via HTTP Post
{
if (Move_uploaded_file ($tmp _filename, $dir. $filename))//upload and move files
{
echo "File Upload success!" ";
Output File Size
echo "File size is:". ($_files[' myFile '] [' size ']/1024]. " KB ";
}
Else
echo "Upload file failed!" ";
}
}
}
Else
{
echo "file format non-GIF picture!" ";
}
}
?>
2. File download
The header () function is to send the correct HTTP header to the browser, which specifies the type of content of the Web page, the properties of the page, and so on.
The header () function has many functions, and only the following points are listed here:
Page jump. If the header () function has an argument of "location:xxx", the page automatically jumps to the URL address that "xxx" points to. For example:
Header ("location:http://www.baidu.com"); Jump to Baidu Page
Header ("Location:first.php"); Jump to the first.php page of the working directory
Specifies the content of the Web page. For example, the same XML-formatted file, if the header () function parameter is specified as "Content-type:application/xml",
The browser parses it in an XML file format. But if it is "Content-type:text/xml", the browser will consider it as text parsing.
The header () function combines the ReadFile () function to download the file that will be browsed
7. Other common file functions
1. Calculate File Size
The FileSize () function is used to calculate the size of the file, in bytes
The FileSize () function combines the fread () function to read the entire file at once
2. Determine whether a file exists
File_exits ()
The Is_dir () function is used to determine whether a given file name is a directory
The Is_file () function is used to determine whether a given file name is a file.
The is_readable () function is used to determine whether a given file is readable.
Is_writeable () is used to determine whether a given file is writable
3. Delete Files
Unlink ()
4. Copy files
BOOL Copy (string $source, String $dest), if the target file already exists, it will be overwritten
5. Move and rename files
In addition to the Move_uploaded_file () function, there is also a rename () function that can also move files.
The syntax format is as follows:
BOOL Rename (string $oldname, String $newname [, Resource $context])
Description: The rename () function is primarily used to rename a file, $oldname is the old name of the file, $newname is the new file name.
Of course, if the $oldname is not the same as the $newname path, it implements the ability to move the file.
6. File pointer operation
PHP has a number of functions that manipulate file pointers, such as Rewind (), Ftell (), fseek () functions, and so on. The previously used feof () function is used to test whether the file pointer is at the end of the file.
Also belongs to the file pointer operation function.
Rewind () function. Used to reset the pointer position of the file so that the pointer returns to the file header. It has only one parameter, which is the file handle of the specified file that is already open.
Ftell () function. The position of the pointer in a file, which is the offset in the file stream, can be reported in bytes. Its argument is also a file handle that has been opened.
Fseek () function. Can be used to move a file pointer, the syntax format is as follows:
int fseek (resource $handle, int $offset [, int $whence])
Example 4.8 Voting statistics
Copy Code code as follows:
<form enctype= "Multipart/form-data" action= "" method= "POST" >
<table border= "0" >
<TR><TD bgcolor= "#CCCCCC" >
<font size=4 color=blue> The current most popular web development language:</font>
</td></tr>
<tr><td><input type= "Radio" name= "vote" value= "PHP" >PHP</td></tr>
<tr><td><input type= "Radio" name= "vote" value= "ASP" >ASP</td></tr>
<tr><td><input type= "Radio" name= "vote" value= "JSP" >JSP</td></tr>
<tr><td><input type= "Submit" Name= "sub" value= "please vote" > </td></tr>
</table>
</form>
<?php
$votefile = "Ex4_6_vote.txt"; Text file for counting $votefile
if (!file_exists ($votefile))//Determine if the file exists
{
$handle =fopen ($votefile, "w+"); Does not exist then create the file
Fwrite ($handle, "0|0|0"); Initializes the contents of the file
Fclose ($handle);
}
if (Isset ($_post[' Sub '))
{
if (Isset ($_post[' vote '))//judge whether the user votes
{
$vote =$_post[' vote ']; Receive voting value
$handle =fopen ($votefile, "r+");
$votestr =fread ($handle, FileSize ($votefile)); Read the contents of the file to the string $votestr
Fclose ($handle);
$votearray =explode ("|", $VOTESTR); Will $votestr according to "|" Segmentation
echo if ($vote = = ' PHP ')
$votearray [0]++; If you select PHP, the 1th value of the array plus 1
echo "The current number of PHP votes: <font size=5 color=red>". $votearray [0]. " </font><br> ";
if ($vote = = ' ASP ')
$votearray [1]++; If you select ASP, the 2nd value of the array plus 1
echo "The current number of ASP votes: <font size=5 color=red>". $votearray [1]. " </font><br> ";
if ($vote = = ' JSP ')
$votearray [2]++; If you select a JSP, the 3rd value of the array plus 1
echo "Current JSP ticket number is: <font size=5 color=red>". $votearray [2]. " </font><br> ";
Calculate the total number of votes
$sum = $votearray [0]+ $votearray [1]+ $votearray [2];
echo "The total number of votes: <font size=5 color=red>". $sum. " </font><br> ";
$votestr 2=implode ("|", $votearray); Put the new array after the vote with the "|" Connect to String $VOTESTR2
$handle =fopen ($votefile, "w+");
Fwrite ($handle, $votestr 2); Writes a new string to a file $votefile
Fclose ($handle);
}
Else
{
echo "<script>alert (' no voting option selected! ') </script>;
}
}
?>