php directory and file processing continued by jeong aki of

  • 2020-05-09 18:18:41
  • OfStack

1. Operation of file directory
The top stop is the root directory of the disk, using '/' or '//'
Current directory./
. / represents the directory of apache or htdocs
1. Create and delete mkdir
 
<?php 
if(mkdir("./path",0700)) // Create in the current directory path directory  
echo " Creating a successful "; 
?> 

2. Get and change the current directory
You can get the current working directory using the getcwd() function, which takes no arguments. Returns the current working directory on success, and FALSE on failure
3. Open and close directory handles
opendir($dir)
closed($dir_handle)
4. Read the contents of the directory
readdir(), the parameter is an open directory handle, and the while loop enables directory traversal
Gets the directory and files in the specified path.
array scandir(string $directory [, int $sorting_order [, resource $context ]])
Note: $directory is the specified path. The parameter $sorting_order is sorted alphabetically in ascending order by default. If it is set to 1, it is sorted alphabetically in 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 operation object.
The function returns an array of all directories and file names in the specified path on success, and FALSE on failure
2. 1 way to manipulate files
3. File opening and closing
1. Open the file
resource fopen(string $filename , string $mode [, bool $use_include_path [, resource $context ]])
Low $filename parameters. The fopen() function binds the named resource specified by the $filename parameter to a stream
Low $mode parameters. The $mode parameter specifies the mode in which the fopen() function accesses the file, as shown in table 4.5.
$mode
Said Ming
'r'
Open the file in read-only mode and read from the file header
'r+'
Read-write mode opens the file, starting with the file header
'w'
Write mode opens the file and points the file pointer to the file header. Delete the existing file if it already exists, and try to create it if it doesn't
'w+'
Read/write opens the file and points the file pointer to the file header. Delete the existing file if it already exists, and try to create it if it doesn't
'a'
Write mode opens the file, points the file pointer to the end of the file, and writes from the end of the file if the file already contains content. If the file does not exist, try to create it
'a+'
Read/write opens the file and points the file pointer to the end of the file. Reads and writes start at the end of the file if the file already contains content. If the file does not exist, try to create it
'x'
Create and open the file as a write, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE, generating an E_WARNING level error message. If the file does not exist, try to create it. This option is supported by PH and later, and can only be used for local files
'x+'
Create and open the file as a read/write, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE with an E_WARNING level error message. If the file does not exist, try to create it. This option is supported by PH and later, and can only be used for local files
'b'
Base 2 mode, used to connect to other modes. This option is required if the file system is able to distinguish between base 2 files and text files (Windows does, UNIX does not), and it is recommended that you use this option for maximum portability

Low $use_include_path parameters. If you need to search for files in include_path (include path of PHP, PHP profile Settings),
You can set the value of the optional parameter $use_include_path to either 1 or TRUE, with the default of FALSE.
Low $context parameters. The optional $context parameter is used only when the file is opened remotely (such as through HTTP). It is a resource variable,
It holds some data related to the specific operation object of the fopen() function. If fopen() opens an HTTP address,
This variable records the request type of the HTTP request, the HTTP version, and other header information. If you open the FTP address,
The record may be in the passive/active mode of FTP
Close the file
bool fclose(resource $handle)
4. Write files
You need to open the file before writing it, create it first if it does not exist, and use fopen() function to create it
●fwrite(). When the file is opened, write to the file
int fwrite(resource $handle , string $string [, int $length ])
Note: parameter $handle is written to the file handle,
$string is the string data to be written to the file,
$length is optional. If $length is specified, the first $length bytes of data in $string are written.
Low file_put_contents () function. PHP 5 also introduces the file_put_contents() function. This function does the same thing as calling fopen(), fwrite(), and fclose() in turn. The syntax is as follows:
int file_put_contents(string $filename , string $data [, int $flags [, resource $context ]])
Note: $filename is the file name to write the data to.
$data is the string to write, and $data can also be an array, but not a multidimensional array.
When writing data to a remote file using FTP or HTTP, you can use the optional parameters $flags and $context, which are not specified here.
The function returns the number of bytes written after a successful write, otherwise returns FALSE.
Low fputcsv () function. CSV is a commonly used file format with an extension of.csv. CSV treats a line of a file as a record, with fields separated by commas.
The fputcsv() function is used in PHP to format the specified array into CSV file format, and to write a pointer to the file pointing to the current path. The syntax is as follows:
int fputcsv(resource $handle [, array $fields [, string $delimiter [, string $enclosure ]]])
Note: the parameter $handle is the file handle to write to.
The parameter $fields is the array to format.
The optional $delimiter parameter is used to set the field delimiter (only 1 character allowed), which defaults to a comma.
Optional $enclosure parameter setting field surround character (only 1 character allowed), default to double quotation marks
5 file reading
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)
Note: parameter $handle is the open file pointer,
$length is the maximum number of bytes specified to be read. The maximum value of $length is 8192.
If the end of the file flag (EOF) is encountered before the $length byte count is read, the character read is returned and the read operation is stopped.
The read string is returned on success, and FALSE is returned on error.
Note: when the contents of a file are displayed after it has been read, the text may contain characters that cannot be displayed directly, such as the HTML token.
You need to use the htmlspecialchars() function to convert the HTML token into an entity to display the characters in the file.
2. Read the entire file
Low file () function. The file() function is used to read the entire file into an array. The syntax is as follows:
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 1 line in the file, including the newline character.
If it fails, FALSE is returned. The parameters $filename is the file name read, and the parameters $use_inclue_path and $context have the same meaning as described earlier
Low readfile () function. The readfile() function is used to output the contents of a file to the browser. The syntax is as follows:
int readfile(string $filename [, bool $use_include_path [, resource $context ]])
Low fpassthru () function. The fpassthru() function reads a given file pointer from its 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 an argument to the fpassthru() function,
The fpassthru() function sends the file contents that the file pointer points to to standard output. If the operation succeeds in returning the number of bytes read, FALSE is returned otherwise.
Low file_get_contents () function. The file_get_contents() function reads the entire or partial contents of a file into a single string,
The function is the same as the function of calling fopen(), fread() and fclose(). The syntax is as follows:
string file_get_contents(string $filename [, int $offset [, int $maxlen ]])
Note: $filename is the file name to read. The optional parameter $offset can specify an offset starting from the file header.
The function returns $maxlen starting at the location specified by $offset. If it fails, the function returns FALSE

3. Read 1 row of data
Low fgets () function. The fgets() function reads 1 line of text from a file in the following syntax format:
string fgets(int $handle [, int $length ])
Note: $handle is an open file handle. The optional parameter $length specifies the maximum number of bytes to return.
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(), although the fgetss() function tries to remove any html and php tags from the text it reads.
Low fgetcsv () function. The fgetcsv() function reads the current state of the specified file, parses out the fields using CSV, and returns an array containing these fields.
The syntax is as follows:
array fgetcsv(int $handle [, int $length [, string $delimiter [, string $enclosure ]]])
4. Read 1 character
fgetc () function. The fgetc() function reads 1 character from the file pointer. The syntax is:
string fgetc(resource $handle)
This function returns 1 character in the file to which the $handle pointer points, and FALSE when EOF is encountered
5. Read the file in the specified format
fscanf () function. The fscanf() function reads the data in a file, formats it in the specified format, and returns an array. The syntax is as follows:
mixed fscanf(resource $handle , string $format [, mixed &$... ])
Any white space in the format string matches any white space in the input stream.
This means that even the TAB character "\t" in the format string matches a single space character in the input stream.
6. Upload and download files
1. File upload
File uploads can be done by submitting the html form. Once the file is uploaded, it is stored by default in a temporary directory, which must be removed or moved elsewhere
Move it to another location using move_uploaded_file() of PHP
The syntax of the move_uploaded_file() function is as follows:
bool move_uploaded_file(string $filename , string $destination)
Note: you need to check if the file was uploaded via HTTP POST before moving the file. This can be used to ensure that malicious users cannot trick scripts into accessing files that are not accessible.
You need to use the is_uploaded_file() function. This function takes the temporary file name of the file and returns TRUE if the file was uploaded via HTTP POST.
Example 4.5 moves the GIF image file uploaded by the HTML form to the html directory
 
<form enctype="multipart/form-data" action="" method="post"> 
<input type="file" name="myFile"> 
<input type="submit" name="up" value=" Upload a file "> 
</form> 
<!-- HTML The form  --> 
<?php 
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 uploaded  
$dir="html/"; 
if(is_uploaded_file($tmp_filename)) // Judge whether or not HTTP POST upload  
{ 
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 " File format not GIF The picture! "; 
} 
} 
?> 

2. File download
The header() function sends the correct HTTP header to the browser, which specifies the type of content on the page, the properties of the page, and so on.
The header() function has many functions, but here are just a few:
● page jump. If the parameter of the header() function is "Location: xxx", the page will automatically go to the URL address pointed to by "xxx". Such as:
header (" Location: http: / / www. baidu. com "); / / jump to baidu page
header (" Location: first. php "); // jump to first.php in the working directory
● specify web content. For example, for the same 1 XML file, if the parameter of the header() function is specified as "Content-type: application/xml",
The browser will parse it in the XML file format. But if it's "Content-type: text/xml," the browser will treat it as text parsing.
The header() function combines with the readfile() function to download the file to be browsed
7. Other common file functions
1. Calculate the file size
The filesize() function is used to calculate the size of a file in bytes
The filesize() function combines with the fread() function to read the entire file 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. Delete files
unlink()
4. Copy files
bool copy(string $source,string $dest) is overwritten if the header file already exists
5. Move and rename files
In addition to the move_uploaded_file() function, there is also an rename() function that can move files.
The syntax is as follows:
bool rename ( string $oldname , string $newname [, resource $context ] )
Note: the rename() function is used to rename a file. $oldname is the old file name and $newname is the new file name.
Of course, if the $oldname and $newname paths are different, you have the ability to move the file
6. File pointer operation
There are many functions in PHP that manipulate file Pointers, such as rewind(), ftell(), fseek(), and so on. The previous 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 is returned to the file header. It takes only one parameter, the file handle of the specified file that has been opened.
ftell () function. You can report, in bytes, the position of the pointer in the file, which is the offset in the file stream. Its parameters are also open file handles.
fseek () function. Can be used to move the file pointer, the syntax is as follows:
int fseek ( resource $handle , int $offset [, int $whence ] )
Example 4.8 voting statistics
 
<form enctype="multipart/form-data" action="" method="post"> 
<table border="0"> 
<tr><td bgcolor="#CCCCCC"> 
<font size=4 color=blue> The most popular at the moment 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"; // A text file for counting $votefile 
if(!file_exists($votefile)) // Determine if the file exists  
{ 
$handle=fopen($votefile,"w+"); // The file is created if it does not exist  
fwrite($handle,"0|0|0"); // Initializes the file contents  
fclose($handle); 
} 
if(isset($_POST['sub'])) 
{ 
if(isset($_POST['vote'])) // Determine if the user voted  
{ 
$vote=$_POST['vote']; // Receive vote value  
$handle=fopen($votefile,"r+"); 
$votestr=fread($handle,filesize($votefile)); // Reads the contents of the file to a string $votestr 
fclose($handle); 
$votearray=explode("|", $votestr); // will $votestr According to the" | "Segmentation  
echo "<h3> The vote is over! </h3>"; 
if($vote=='PHP') 
$votearray[0]++; // If you choose to PHP , then array number 1 A value added 1 
echo " At present PHP The votes are: <font size=5 color=red>".$votearray[0]."</font><br>"; 
if($vote=='ASP') 
$votearray[1]++; // If you choose to ASP , then array number 2 A value added 1 
echo " At present ASP The votes are: <font size=5 color=red>".$votearray[1]."</font><br>"; 
if($vote=='JSP') 
$votearray[2]++; // If you choose to JSP , then array number 3 A value added 1 
echo " At present JSP The votes are: <font size=5 color=red>".$votearray[2]."</font><br>"; 
// Total votes counted  
$sum=$votearray[0]+$votearray[1]+$votearray[2]; 
echo " The total number of votes is: <font size=5 color=red>".$sum."</font><br>"; 
$votestr2=implode("|",$votearray); // Use the" | "Concatenate into a string $votestr2 
$handle=fopen($votefile,"w+"); 
fwrite($handle,$votestr2); // Writes the new string to a file $votefile 
fclose($handle); 
} 
else 
{ 
echo "<script>alert(' No voting option selected! ')</script>"; 
} 
} 
?> 

Related articles: