search
HomeBackend DevelopmentPHP TutorialPHP directory and file processing methods

  1. if(mkdir("./path",0700)) //Create path directory in the current directory
  2. echo "Created successfully";
  3. ?>
Copy code

2. Get and change the current directory The current working directory can be obtained using the getcwd() function, which has no parameters. Returns the current working directory on success, FALSE on failure

3. Open and close directory handles opendir($dir) closed($dir_handle)

4. Read directory contents 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 ]]) Note: $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 succeeds, it returns an array containing all directory and file names under the specified path, if it fails, it returns 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 illustrate 'r' Open the file in read-only mode and read from the beginning of the file 'r+' Open the file in read-write mode and start reading and writing from the beginning of the file. 'w' Open the file in 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 '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 be written from the end of the file. 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 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 for reading and 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 '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), The value of the optional parameter $use_include_path can be set 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 via HTTP). It is a resource variable. It 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 the FTP address is opened, What is recorded may be the passive/active mode of FTP

2.Close the file bool fclose(resource $handle)

4.Writing files The file needs to be opened before writing. If it does not exist, create it first. Generally, it is created using the fopen() function. ●fwrite(). After the file is opened, write content to the file int fwrite(resource $handle , string $string [, int $length ]) Description: The parameter $handle is the file handle to be written. $string is the string data to be written to the file, $length is an optional parameter. If $length is specified, writing will stop after writing the first $length bytes of data in $string. ●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 ]]) Note: $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. After the writing is successful, the function returns the number of bytes written, 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 ]]]) Description: 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 a comma. The optional $enclosure parameter sets the field wrapper (only one character allowed), the default is double quotes

5 File reading

1. Read any length The fread() function can be used to read the contents of a file. The syntax format is as follows: string fread(int $handle, int $length) Description: The parameter $handle is the open file pointer. $length specifies the maximum number of bytes to read, and the maximum value of $length is 8192. If the end-of-file flag (EOF) is encountered before reading $length bytes, the read characters are returned and the reading operation stops. If the read is successful, the read string is returned, if an error occurs, FALSE is returned. 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 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: The function of this 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 on failure. The parameter $filename is the file name to be read. The meanings of the parameters $use_inclue_path and $context are the same as those introduced before. ●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 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 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 ]]) Description: $filename is the file name to be read. The optional parameter $offset can specify the offset from the beginning of the file. 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 ]) Description: $handle is the file handle that has been opened. The optional parameter $length specifies the maximum number of bytes returned, taking into account line terminators. A string of up to length-1 bytes can be returned. If $length is not specified, the default is 1024 bytes ●The fgetss() function is basically the same as fgets(), except that 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. If it encounters EOF, it returns FALSE

5. Read files 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 format 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 other places. Use PHP's move_uploaded_file() to move it to another location The syntax format of the move_uploaded_file() function is as follows: bool move_uploaded_file(string $filename, string $destination) Note: You need to check whether the file was uploaded via HTTP POST before moving it. This can be used to ensure that malicious users cannot trick scripts into accessing files that are otherwise inaccessible. At this time, 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 by the HTML form to the html directory

  1. if(isset($_POST['up ']))
  2. {
  3. if($_FILES['myFile']['type']=="image/gif") //Determine whether the file format is GIF
  4. {
  5. if($_FILES['myFile'][ 'error']>0) //Determine whether there is an error in uploading
  6. echo "Error:".$_FILES['myFile']['error']; //Output error message
  7. else
  8. {
  9. $tmp_filename=$_FILES[ 'myFile']['tmp_name']; //Temporary file name
  10. $filename=$_FILES['myFile']['name']; //Uploaded file name
  11. $dir="html/";
  12. if( is_uploaded_file($tmp_filename)) //Determine whether to upload via HTTP POST
  13. {
  14. if(move_uploaded_file($tmp_filename,$dir.$filename)) //Upload and move the file
  15. {
  16. echo "File uploaded successfully!";
  17. / /Output file size
  18. echo "The file size is:". ($_FILES['myFile']['size']/1024)."kb";
  19. }
  20. else
  21. echo "File upload failed!";
  22. }
  23. }
  24. }
  25. else
  26. {
  27. echo "The file format is not a GIF image!";
  28. }
  29. }
  30. ?>
Copy code

2.File download The function of the 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 the first.php page in the working directory ●Specify web page content. For example, for the same XML format file, 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 file size The filesize() function is used to calculate the size of a file in bytes The filesize() function combined with the fread() function can read the entire file at once

2. Determine whether 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), if the directory 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 ] ) Note: The rename() function is mainly used to rename a file. $oldname is the old name of the file, and $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. Also belongs to the 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

  1. $votefile="EX4_6_vote.txt"; //Text file used for counting $votefile
  2. if(!file_exists($votefile)) //Determine whether the file exists
  3. {
  4. $handle=fopen($votefile,"w+"); //Create the file if it does not exist
  5. fwrite($handle,"0|0|0"); //Initialize the file content
  6. fclose($handle );
  7. }
  8. if(isset($_POST['sub']))
  9. {
  10. if(isset($_POST['vote'])) // Determine whether the user voted
  11. {
  12. $vote=$_POST[' vote']; //Receive the vote value
  13. $handle=fopen($votefile,"r+");
  14. $votestr=fread($handle,filesize($votefile)); //Read the file content to the string $votestr
  15. fclose($handle);
  16. $votearray=explode("|", $votestr); //Split $votestr according to "|"
  17. echo "

    Voting completed!

    ";
  18. if($vote=='PHP')
  19. $votearray[0]++; //If PHP is selected, the first value of the array will be increased by 1
  20. echo "The current number of votes for PHP is: ".$votearray[0]."
    ";
  21. if($vote=='ASP')
  22. $votearray[1]++; //If ASP is selected, add 1 to the second value of the array
  23. echo "The current number of votes for ASP is: ".$votearray[1]."
    if($vote=='JSP')
  24. $votearray[2]++; //If JSP is selected, the third value of the array will be increased by 1
  25. echo "The current number of votes for JSP is: ".$votearray[2]."
    ";
  26. //Calculate the total number of votes
  27. $sum=$votearray[0]+$votearray[1]+$votearray [2];
  28. echo "The total number of votes is:".$sum."
    ";
  29. $votestr2=implode("|",$votearray ); //Concatenate the new array after voting into a string using "|" $votestr2
  30. $handle=fopen($votefile,"w+");
  31. fwrite($handle,$votestr2); //Concatenate the new string Write to file $votefile
  32. fclose($handle);
  33. }
  34. else
  35. {
  36. echo "<script>alert('No voting option selected!')</script>";
  37. }
  38. }
  39. ?> Copy code
  40. The most popular web development language currently:
  41. < ;input type="radio" name="vote" value="PHP">PHP
    ASP
    JSP td>


Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function