PHP directory and file processing-Zheng Achi (cont.) _php Tutorial

Source: Internet
Author: User
Tags fread rewind
1. File directory operation
The topmost stop is the disk root directory, with '/' or '//'
Current directory./
.. /indicates that the Apache directory is the Htdocs directory
1. Creating and Deleting Directories mkdir
Copy CodeThe code is as follows:
if (mkdir ("./path", 0700))//Create the path directory in the current directory
echo "created successfully";
?>

2. Get and change the current directory
The current working directory can be obtained using the GETCWD () function, which has no parameters. Success returns the current working directory, and failure returns false
3. Open and close the directory handle
Opendir ($dir)
Closed ($dir _handle)
4. Reading directory Contents
Readdir (), which is an already open directory handle, and a while loop can implement a 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 for the specified path. The parameter $sorting_order is sorted alphabetically by default, and if set to 1, it is arranged in descending alphabetical order.
The $context is an optional parameter and is a resource variable that can be generated with the stream_context_create () function, which holds some data about the specific object being manipulated.
If the function succeeds, it returns an array containing all directories and filenames under the specified path, and the failure returns false
2. General methods for manipulating files
3. Opening and closing of files
1. Open 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 open the file, starting with the file header
' R+ '
Read/write mode open file, read and write from 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 if the file does not exist, try to create it
' w+ '
Read-write to open the file and point the file pointer to the file header. If the file already exists, delete the existing content, and if the file does not exist, try to create it
A
Write to open the file, point the file pointer to the end of the file, and if the file already has content, start writing from the end of the file. If the file does not exist, try to create it
' A + '
Read-write to open the file and point the file pointer to the end of the file. If the file already has content, it starts reading and writing from the end of the file. If the file does not exist, try to create it
' X '
Creates and writes the file, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns false, and generates an E_warning level error message. If the file does not exist, try to create it. This option is supported by ph and later versions and can only be used on 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 generates an E_warning level error message. If the file does not exist, try to create it. This option is supported by ph and later versions and can only be used on local files
' B '
Binary mode, which is used to connect behind other modes. If the file system is able to differentiate between binary and text files (Windows differentiated, and UNIX is not differentiated), then this option is required, and it is recommended to use this option all the time for maximum portability

$use the _include_path parameter. If you need to search for files in the include_path (PHP include path, in the PHP configuration file settings),
You can set the value of the optional parameter $use _include_path to 1 or true, which defaults to false.
$context parameters. The optional $context parameter is used only when the file is opened remotely (for example, via HTTP), which is a resource variable.
It holds some data about the specific operand of the fopen () function. If fopen () opens an HTTP address,
Then this variable records the request type, HTTP version and other header information of the HTTP request, and if the FTP address is open,
may be logged in the passive/active mode of FTP
2. Close the file
BOOL Fclose (Resource $handle)
4. Writing the file
The file needs to be opened before it is written, it does not exist, it is generally created with the fopen () function.
Fwrite (). Writing content to a file when the file is opened
int fwrite (Resource $handle, string $string [, int $length])
Description: Parameter $handle is a file handle written to,
$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 bytes of data in $string are written.
The File_put_contents () function. PHP 5 also introduces the File_put_contents () function. This function is functionally the same as calling fopen (), fwrite (), and fclose () functions 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.
Optional parameters $flags and $context can be used when writing data to remote files using FTP or HTTP, not specifically described here.
After the write succeeds, the function returns the number of bytes written, otherwise it returns false.
The Fputcsv () function. CSV is a more commonly used file format, typically with. csv as the extension. The CSV format considers a row of a file to be a record, with fields in the record separated by commas.
Using the Fputcsv () function in PHP, you can format the specified array as content that conforms to the CSV file format and write to the current line that the file pointer points to. The syntax format is as follows:
int Fputcsv (Resource $handle [, Array $fields [, String $delimiter [, String $enclosure]])
Description: The parameter $handle is the file handle to be written.
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.
The optional $enclosure parameter sets the field wrapping character (only one character is allowed), and the default is double quotation marks
5 reading of the file
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 pointer to a file that has been opened.
$length is the maximum number of bytes to read, and the maximum value for the $length is 8192.
If the end of File flag (EOF) is encountered before the $length bytes are read, the read character is returned and the read operation is stopped.
Returns the Read string if the read succeeds, or False if an error occurs.
Note: When displaying file contents after reading a file, the text may contain characters that cannot be displayed directly, such as HTML tags.
You need to use the Htmlspecialchars () function to convert HTML tags to 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 with the following syntax:
Array file (string $filename [, int $use _include_path [, Resource $context]])
Description: The function is to return the file as an array, each cell in the array is the corresponding line in the file, including the newline character,
Returns False if it fails. Parameter $filename is the name of the read file, and the meaning of parameters $use_inclue_path and $context is the same as described earlier
The ReadFile () function. The ReadFile () function is used to output the contents of a file to the browser, in the following syntax format:
int ReadFile (string $filename [, bool $use _include_path [, Resource $context]])
The 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 with the fopen () function, and then pass the file pointer as a parameter to the Fpassthru () function.
The Fpassthru () function sends the file contents pointed to by the file pointer to the standard output. Returns False if the operation successfully returns the number of bytes read.
The file_get_contents () function. The file_get_contents () function can read the entire or partial file contents into a string,
function is the same as calling 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 be read, optional parameter $offset can specify the offset from the beginning of the file header,
The $offset function can return content that starts at the length of $maxlen from the location specified by the. If it fails, the function returns false

3. Read a row of data
The Fgets () function. The fgets () function can read a line of text from a file in the following syntax format:
String fgets (int $handle [, int $length])
Description: $handle is a file handle that has been opened, the 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 basically the same as fgets (), but the FGETSS () function attempts to remove any HTML and PHP tags from the text being read.
The Fgetcsv () function. The Fgetcsv () function reads the current line of the specified file, resolves the field using the CSV format, and returns an array containing the fields.
The syntax format is as follows:
Array fgetcsv (int $handle [, int $length [, String $delimiter [, String $enclosure]])
4. Read a character
The fgetc () function. The fgetc () function can read a character from the file pointer, in the syntax format:
String fgetc (Resource $handle)
The function returns a character in the file pointed to by the $handle pointer, and returns FALSE if EOF is encountered
5. Reading a file using the specified format
The fscanf () function. The fscanf () function can read the data in the 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 will also match a space character in the input stream.
6. Uploading and downloading of files
1. File Upload
File uploads can be done by submitting an HTML form. After the file upload is finished, it is stored in the TEMP directory by default and must be removed from the temp directory or moved to another location.
Use PHP's Move_uploaded_file () to move it to a different location
The syntax format for the Move_uploaded_file () function is as follows:
BOOL Move_uploaded_file (String $filename, String $destination)
Note: Before moving a file, you need to check to see if the file was uploaded via HTTP post, which can be used to ensure that a malicious user cannot spoof a script to access a file that it cannot access.
You need to use the Is_uploaded_file () function. The function's parameters are temporary file names, and if the file is uploaded via HTTP POST, the function returns True.
Example 4.5 Moving a GIF picture file uploaded by an HTML form to an HTML directory
Copy CodeThe code is as follows:


if (Isset ($_post[' up '))
{
if ($_files[' myFile ' [' Type ']== "image/gif")//determine if the file format is GIF
{
if ($_files[' myFile ' [' Error ']>0)//Determine if 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 of the upload
$dir = "html/";
if (Is_uploaded_file ($tmp _filename))//decide whether to upload via HTTP Post
{
if (Move_uploaded_file ($tmp _filename, $dir. $filename))//upload and move files
{
echo "File Upload successful! ";
Output File Size
echo "File size is:". ($_files[' myFile ' [' Size ']/1024). " KB ";
}
Else
echo "Failed to upload the file! ";
}
}
}
Else
{
echo "file format non-GIF pictures! ";
}
}
?>

2. File download
The header () function is to send the correct HTTP header to the browser, which specifies information such as the type of the page content, the properties of the page, and so on.
The header () function has a lot of functions, and here are just a few things:
Page jumps. If the argument of the header () function is "location:xxx", the page will automatically jump to the URL address that "xxx" points to. For example:
Header ("location:http://www.baidu.com"); Skip to Baidu Page
Header ("Location:first.php"); Jump to the first.php page of the working directory
Specifies the Web page content. For example, the same XML-formatted file, if the header () function parameter is specified as "Content-type:application/xml",
The browser will parse it according to the XML file format. But if it is "Content-type:text/xml", the browser will consider it as text parsing.
The header () function, in conjunction with the ReadFile () function, allows you to download the files that will be browsed
7. Other common file functions
1. Calculate File Size
The FileSize () function is used to calculate the size of a file, in bytes
The FileSize () function combined with the fread () function allows the entire file to be read at once
2. Determine if the 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. deleting files
Unlink ()
4. Copying files
BOOL Copy (string $source, String $dest) that will be overwritten if the document already exists
5. Move and rename files
In addition to the Move_uploaded_file () function, there is also a rename () function to move the file.
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 the new file name.
Of course, if the path of $oldname and $newname is not the same, the function of moving the file is realized.
6. File pointer operation
There are many functions in PHP that manipulate file pointers, such as Rewind (), Ftell (), fseek () functions, and so on. The previously used feof () function is used to test if the file pointer is at the end of the file.
Also belongs to the file pointer manipulation function.
The rewind () function. The pointer position used to reset the file so that the pointer is returned to the file header. It has only one parameter, which is the file handle of the specified file that has been opened.
The Ftell () function. The position of the pointer in the file, which is the offset in the file stream, can be reported in bytes. Its arguments are also file handles that have been opened.
The Fseek () function. Can be used to move the file pointer, the syntax format is as follows:
int fseek (resource $handle, int $offset [, int $whence])
Example 4.8 Poll statistics
Copy CodeThe code is as follows:

$votefile = "Ex4_6_vote.txt"; Text file for Count $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 '))//Determine if the user is voting
{
$vote =$_post[' vote ']; Receive voting values
$handle =fopen ($votefile, "r+");
$votestr =fread ($handle, FileSize ($votefile)); Read file contents to string $votestr
Fclose ($handle);
$votearray =explode ("|", $VOTESTR); $votestr according to the "|" Segmentation
echo "

The polls are over!

";
if ($vote = = ' PHP ')
$votearray [0]++; If PHP is selected, the 1th value of the array is added 1
echo "The current number of votes in PHP is:". $votearray [0]. "
";
if ($vote = = ' ASP ')
$votearray [1]++; If you select ASP, the 2nd value of the array is added 1
echo "The current number of ASP votes is:". $votearray [1]. "
";
if ($vote = = ' JSP ')
$votearray [2]++; If you select JSP, the 3rd value of the array is added 1
echo "The current number of tickets for JSP is:". $votearray [2]. "
";
Calculate the total number of votes
$sum = $votearray [0]+ $votearray [1]+ $votearray [2];
echo "Total votes:". $sum. "
";
$votestr 2=implode ("|", $votearray); Use "|" for the new array after the poll Concatenate into a string $votestr2
$handle =fopen ($votefile, "w+");
Fwrite ($handle, $votestr 2); Writes a new string to the file $votefile
Fclose ($handle);
}
Else
{
echo "";
}
}
?>

http://www.bkjia.com/PHPjc/323885.html www.bkjia.com true http://www.bkjia.com/PHPjc/323885.html techarticle 1. The top level of file directory operation is the disk root directory, with '/' or '//' current directory. /indicates that the Apache directory is htdocs directory 1. Create and delete directories mkdir copy code code as follows ...

  • Related Article

    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.