Home > Backend Development > PHP Tutorial > PHP directory and file processing-Zheng Aqi (continued)_PHP tutorial

PHP directory and file processing-Zheng Aqi (continued)_PHP tutorial

WBOY
Release: 2016-07-21 15:26:40
Original
823 people have browsed it

1. File directory operation
The top-level directory is the disk root directory, use '/' or '//'
Current directory./
../ to indicate the apache directory, which is the htdocs directory
1 .Create and delete directories mkdir

Copy code The 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
Use the getcwd() function to get the current working directory. This function has no parameters. If successful, return the current working directory, if failed, return FALSE
3. Open and close the directory handle
opendir($dir)
closed($dir_handle)
4. Read the directory content
readdir(), this parameter is an already opened directory handle, which can be used with the while loop to traverse the directory
5. Get the directories and files in the specified path.
array scandir(string $directory [, int $sorting_order [, resource $context ]])
Explanation: $directory is the specified path. The parameter $sorting_order defaults to sorting in ascending alphabetical order. If set to 1, it means sorting in descending alphabetical order.
$context is an optional parameter and is a resource variable that can be generated using the stream_context_create() function. This variable stores some data related to the specific operation object.
If the function is successful, it will return an array containing all directories and file names under the specified path. If it fails, it will return FALSE
2. General methods of operating files
3. Opening and closing files
1 .Open the file
resource fopen(string $filename , string $mode [, bool $use_include_path [, resource $context ]])
●$filename parameter. The fopen() function binds the name resource specified by the $filename parameter to a stream
●$mode parameter. The $mode parameter specifies the mode in which the fopen() function accesses files. The values ​​are shown in Table 4.5.
$mode
Description
'r'
Open the file in read-only mode, start reading from the file header
'r+'
Open the file in read-write mode, start reading and writing from the file header
'w'
Open the file in writing mode and point the file pointer to the file header. If the file already exists, delete the existing content. If the file does not exist, try to create it.
'w+'
Open the file in read-write mode and point the file pointer to the file header. If the file already exists, delete the existing content. If the file does not exist, try to create it.
'a'
Open the file in writing mode and point the file pointer to the end of the file. If the file already has content, it will start from the end of the file. Write. If the file does not exist, try to create it
'a+'
Open the file in read-write mode and point the file pointer to the end of the file. If the file already contains content, reading and writing will start from the end of the file. If the file does not exist then try to create it
'x'
Create and open the file for writing, 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 then attempts to create it. This option is supported by PH and later versions, and can only be used for local files
'x+'
Create and open the file in read-write mode, 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 then attempts to create it. This option is supported by PH and later versions, and can only be used for local files
'b'
Binary mode, used to connect behind other modes. If the file system can distinguish between binary files and text files (Windows does, but UNIX does not), you need to use this option. It is recommended to always use this option for maximum portability

●$use_include_path parameter . If you need to search for files in include_path (PHP's include path, set in PHP's configuration file),
you can set the value of the optional parameter $use_include_path to 1 or TRUE, and the default is FALSE.
●$context parameter. The optional $context parameter is only used when the file is opened remotely (such as opening through HTTP). It is a resource variable,
which stores some data related to the specific operation object 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; if it opens an FTP address,
may record the FTP passive/ Active mode
2. Close the file
bool fclose(resource $handle)
4. File writing
The file needs to be opened before writing. If it does not exist, create it first. Generally, use fopen() Function creation
●fwrite(). After the file is opened, write content to the file
int fwrite(resource $handle, string $string [, int $length])
Explanation: The parameter $handle is written The file handle of Stop writing after section of data.
●file_put_contents() function. PHP 5 also introduced the file_put_contents() function. The function of this function is the same as calling the fopen(), fwrite(), and fclose() functions in sequence. The syntax format is as follows:
int file_put_contents(string $filename, string $data [, int $flags [, resource $context ]])
Explanation: $filename is the name of the file to which data is to be written.
$data is the string to be written. $data can also be an array, but it cannot be a multi-dimensional array.
When using FTP or HTTP to write data to a remote file, you can use the optional parameters $flags and $context, which are not introduced in detail here.
The function returns the number of bytes written after successful writing, otherwise it returns FALSE.
●fputcsv() function. CSV is a commonly used file format, generally with .csv as the extension.The CSV format treats one line of the file as a record, and the fields in the record are separated by commas.
Use the fputcsv() function in PHP to format the specified array into content that conforms to the CSV file format, and write the current line pointed to by the file pointer. The syntax format is as follows:
int fputcsv(resource $handle [, array $fields [, string $delimiter [, string $enclosure ]]])
Explanation: The parameter $handle is the file handle to be written.
The parameter $fields is the array to be formatted.
The optional $delimiter parameter is used to set the field delimiter (only one character is allowed), which defaults to comma.
The optional $enclosure parameter sets the field wrapper (only one character is allowed), the default is double quotes
5 Reading of files
1. Read any length
The fread() function can Used to read the contents of the file, the syntax format is as follows:
string fread(int $handle, int $length)
Explanation: The parameter $handle is the open file pointer,
$length is the specified read The maximum number of bytes, the maximum value of $length is 8192.
If the end-of-file flag (EOF) is encountered before reading $length bytes, the read characters will be returned and the reading operation will stop.
If the read is successful, return the read string, if an error occurs, return FALSE.
Note: When displaying the file content after reading the file, the text may contain characters that cannot be displayed directly, such as HTML tags.
At this time, you need to use the htmlspecialchars() function to convert the HTML tags into entities to display the characters in the file.
2. Read the entire file
●file() function. The file() function is used to read the entire file into an array. The syntax format is as follows:
array file(string $filename [, int $use_include_path [, resource $context ]])
Description: This function The function is to return the file as an array. Each unit in the array is a corresponding line in the file, including newlines.
Returns FALSE if it fails. The parameter $filename is the file name to be read. The meanings of the parameters $use_inclue_path and $context are the same as the previously introduced
●readfile() function. The readfile() function is used to output the contents of a file to the browser. The syntax format is as follows:
int readfile(string $filename [, bool $use_include_path [, resource $context ]])
●fpassthru() function . The fpassthru() function reads the given file pointer from the current position to EOF and writes the result to the output buffer.
To use this function, you must first use the fopen() function to open the file, and then pass the file pointer as a parameter to the fpassthru() function.
The fpassthru() function sends the content of the file pointed to by the file pointer to the standard output. . Returns the number of bytes read if the operation is successful, otherwise returns FALSE.
●file_get_contents() function. The file_get_contents() function can read the entire or part of the file content into a string. The
function is the same as calling the fopen(), fread() and fclose() functions in sequence. The syntax format is as follows:
string file_get_contents(string $filename [, int $offset [, int $maxlen ]])
Explanation: $filename is the file name to be read, and the optional parameter $offset can specify the file from The offset from the beginning of the head. The
function can return content with a length of $maxlen starting from the position specified by $offset. If it fails, the function will return FALSE

3. Read a row of data
●fgets() function. The fgets() function can read a line of text from a file. The syntax format is as follows:
string fgets(int $handle [, int $length])
Explanation: $handle is the opened file handle, optional parameters $length specifies the maximum number of bytes to return. Taking into account line terminators,
can return a string of up to length-1 bytes. If $length is not specified, it defaults to 1024 bytes
●The fgetss() function is basically the same as fgets(), but the fgetss() function will try to remove any html and php tags from the read text.
●fgetcsv() function. The fgetcsv() function can read the current line of the specified file, parse out the fields using CSV format, and return an array containing these fields.
The syntax format is as follows:
array fgetcsv(int $handle [, int $length [, string $delimiter [, string $enclosure ]]])
4. Read a character
fgetc() function. The fgetc() function can read a character from the file pointer. The syntax format is:
string fgetc(resource $handle)
This function returns a character in the file pointed to by the $handle pointer, and returns when EOF is encountered. FALSE
5. Read the file using the specified format
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 is as follows:
mixed fscanf(resource $handle , string $format [, mixed &$... ])
Any whitespace in the format string will match any whitespace in the input stream.
This means that even the tab character "t" in the format string will match a space character in the input stream.
6. File upload and download
1. File upload
File upload can be achieved by submitting an html form.After the file is uploaded, it is stored in the temporary directory by default. At this time, it must be deleted from the temporary directory or moved to another place
Use PHP's move_uploaded_file() to move it to another location
move_uploaded_file() function syntax format As follows:
bool move_uploaded_file(string $filename, string $destination)
Note: Before moving the file, you need to check whether the file was uploaded via HTTP POST. This can be used to ensure that malicious users cannot trick scripts into accessing For files that cannot be accessed,
you need to use the is_uploaded_file() function. The parameter of this function is the temporary file name of the file. If the file is uploaded through HTTP POST, the function returns TRUE.
Example 4.5 Move the GIF image file uploaded from the HTML form to the html directory
Copy the code The code is as follows:






if(isset ($_POST['up']))
{
if($_FILES['myFile']['type']=="image/gif") //Determine whether the file format is GIF
{
if($_FILES['myFile']['error']>0) //Determine whether there is an error in uploading
echo "Error:".$_FILES['myFile']['error']; //Output error message
else
{
$tmp_filename=$_FILES['myFile']['tmp_name']; //Temporary file name
$filename=$_FILES['myFile'] ['name']; //Uploaded file name
$dir="html/";
if(is_uploaded_file($tmp_filename)) //Determine whether to upload via HTTP POST
{
if (move_uploaded_file($tmp_filename,$dir.$filename)) //Upload and move files
{
echo "File uploaded successfully!";
//Output file size
echo "The file size is : ". ($_FILES['myFile']['size']/1024)."kb";
}
else
echo "Failed to upload file! ";
}
}
}
else
{
echo "The file format is not a GIF image!";
}
}
?>

2 The function of the file download
header() function is to send the correct HTTP header to the browser. The header specifies the type of web page content, page attributes and other information.
The header() function has many functions, only the following are listed here:
●Page jump. If the parameter of the header() function is "Location: xxx", the page will automatically jump to the URL pointed to by "xxx". For example:
header("Location: http://www.baidu.com"); //Jump to Baidu page
header("Location: first.php"); //Jump to working directory The first.php page
● specifies the web content. For example, for the same file in XML format, if the parameter of the header() function 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 treat it as text parsing.
The header() function combined with the readfile() function can download the file to be browsed
7. Other commonly used file functions
1. Calculate the file size
The filesize() function is used to calculate the size of the file. The unit is bytes
The filesize() function combined with the fread() function can read the entire file at one time
2. Determine whether the file exists
file_exits()
is_dir() function is used to judge the given Whether the file name is a directory
The is_file() function is used to determine whether the 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 the file
unlink()
4. Copy the file
bool copy(string $source, string $dest) , if the directory file already exists, it will be overwritten
5. Move and rename the file
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 ] )
Explanation: The rename() function is mainly used to rename a file, $oldname is the file The old name, $newname is the new file name.
Of course, if the paths of $oldname and $newname are different, the function of moving the file is realized
6. File pointer operation
There are many functions in PHP that operate file pointers, such as rewind(), ftell(), fseek() functions, etc. The feof() function used before is used to test whether the file pointer is at the end of the file.
is also a file pointer operation function.
rewind() function. Used to reset the file pointer position so that the pointer returns to the beginning of the file. It has only one parameter, which is the file handle of the specified file that has been opened.
ftell() function. The position of a pointer in the file, that is, the offset in the file stream, can be reported in bytes. Its parameter is also the file handle that has been opened.
fseek() function. It 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 Voting Statistics
Copy the code The code is as follows:



< ;td bgcolor="#CCCCCC">
The most popular web development language currently:


ASP


PHP
JSP


$votefile="EX4_6_vote.txt"; / /Text file used for counting $votefile
if(!file_exists($votefile)) //Determine whether the file exists
{
$handle=fopen($votefile,"w+"); //No If it exists, create the file
fwrite($handle,"0|0|0"); //Initialize the file content
fclose($handle);
}
if(isset($_POST ['sub']))
{
if(isset($_POST['vote'])) // Determine whether the user voted
{
$vote=$_POST['vote'] ; //Receive vote value
$handle=fopen($votefile,"r+");
$votestr=fread($handle,filesize($votefile)); //Read file content to string$ votestr
fclose($handle);
$votearray=explode("|", $votestr); //Split $votestr according to "|"
echo "

Voting completed!

";
if($vote=='PHP')
$votearray[0]++; //If PHP is selected, the first value of the array will be increased by 1
echo " The current number of votes for PHP is:".$votearray[0]."
";
if($vote=='ASP')
$votearray[1]++; //If ASP is selected, the second value of the array will be incremented by 1
echo "The current number of votes for ASP is: ".$votearray[ 1]."
";
if($vote=='JSP')
$votearray[2]++; //If JSP is selected, the 3rd one in the array Add 1 to the value
echo "The current number of JSP votes is: ".$votearray[2]."
";
//Calculation Total votes
$sum=$votearray[0]+$votearray[1]+$votearray[2];
echo "The total number of votes is: ".$sum. "
";
$votestr2=implode("|",$votearray); //Concatenate the new array after voting into a string using "|" $votestr2
$ handle=fopen($votefile,"w+");
fwrite($handle,$votestr2); //Write the new string to the file $votefile
fclose($handle);
}
else
{
echo "<script>alert('No voting option selected!')</script>";
}
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323885.htmlTechArticle1. The top level of file directory operation is the disk root directory, use '/' or '//' currently Directory ./ ../ represents the apache directory, which is the htdocs directory 1. Create and delete the directory mkdir. Copy the code as follows...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template