Home Backend Development PHP Tutorial (Advanced) Commonly used file operation functions in PHP

(Advanced) Commonly used file operation functions in PHP

Feb 06, 2017 am 10:08 AM

The following are PHP file operation functions. Of course, this is just part of it, there are many more that I didn’t list.

1. Parse the path:

1 Get the file name:

basename();
Gives a string containing the full path to a file, This function returns the base file name. If the filename ends with suffix, this part will also be removed.
eg:

$path = "/home/httpd/html/index.php";
$file = basename($path,".php"); // $file is set to "index"
Copy after login

2 Get the directory part:
dirname();
Gives a string containing the full path to a file , this function returns the directory name after removing the file name.
eg:

$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
Copy after login

3 Get the path associative array
pathinfo();
Get the three parts of a specified path: directory name, basic Name, extension.
eg:

$pathinfo = pathinfo("www/test/index.html");
var_dump($pathinfo);
// $path['dirname']
$path['basename']
$path['extenssion']
Copy after login


2. File type
1. filetype();
Returns the type of file. Possible values ​​are fifo, char, dir, block, link, file and unknown.
eg:

echo filetype('/etc/passwd'); // file
echo filetype('/etc/');        // dir
Copy after login


3. Get an array of useful information for a given file (very useful)

1. fstat();
Through the opened The file pointer obtains file information
Obtains the statistical information of the file opened by the file pointer handle. This function is similar to the stat() function, except that it operates on an open file pointer instead of a file name.
eg:

// 打开文件
$fp = fopen("/etc/passwd", "r");
// 取得统计信息
$fstat = fstat($fp);
// 关闭文件
fclose($fp);
// 只显示关联数组部分
print_r(array_slice($fstat, 13));
Copy after login

2. stat()
Get the statistical information of the file specified by filename (analogous to fstat())

4. Calculate the size
1. filesize()
Returns the number of bytes of the file size. If an error occurs, it returns FALSE and generates an E_WARNING level error.
eg:

// 输出类似:somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
Copy after login


2. disk_free_space()
Get the available space (in bytes) of the disk partition where the directory is located
eg

// $df 包含根目录下可用的字节数
$df = disk_free_space("/");
//在 Windows 下:
disk_free_space("C:");
disk_free_space("D:");
Copy after login


3. disk_total_space()
Returns the total disk size of a directory
eg: (same as above, replace the function)

Another: If you need to calculate the size of a directory, you can write A recursive function to implement

Code

function dir_size($dir){
$dir_size = 0;
if($dh = @opendir($dir)){
while(($filename = readdir($dh)) != false){
if($filename !='.' and $filename !='..'){
     if(is_file($dir.'/'.$filename)){
$dir_size +=filesize($dir.'/'.$filename);
}else if(is_dir($dir.'/'.$filename)){
      $dir_size +=dir_size($dir.'/'.$filename);
}
}
                   }#end while
            }# end opendir
@closedir($dh);
return $dir_size;
} #end function
Copy after login

5. Access and modification time
1. fileatime(): Last access time
2 . filectime(): Last change time (modification of any data)
3. filemtime(): Last modification time (referring to content modification only)

6. File I /O operation

1. fopen -- Open a file or URL

mode Description
'r' Open in read-only mode and point the file pointer to the file header.
'r+' Open in read-write mode and point the file pointer to the file header.
'w' turns on writing mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it.
'w+' Open in read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.
'a' opens in writing mode and points the file pointer to the end of the file. If the file does not exist, try to create it.
'a+' Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it.
'x' creates and opens for writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE,
'x+' is created and opened for reading and writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE
eg:

$handle = fopen("/home/rasmus/file.txt", "r");

2. file -- Read the entire file into an array (this function is very useful)
Same as file_get_contents(), except that file() treats the file as an Array returned. Each cell in the array is a corresponding line in the file, including newlines. If file() fails, it returns FALSE.
eg:

Code

$lines = file('http://www.example.com/');
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode(&#39;&#39;, file (&#39;http://www.example.com/&#39;));
Copy after login


3. fgets -- Read a line from the file pointer
Pointed to by handle Reads a line from the file and returns a string with a length of at most length - 1 bytes. Stops when a newline character (included in the return value), EOF, or length - 1 bytes has been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.
eg:

$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
Copy after login

4. fgetss -- Read a line from the file pointer and filter out HTML tags
Same as fgets(), except fgetss Try stripping any HTML and PHP markup from the text you read.

You can use the optional third parameter to specify which tags will not be removed


Another: Operations on the directory:
1. opendir -- open the directory handle, Opens a directory handle that can be used in subsequent closedir(), readdir(), and rewinddir() calls.
2. readdir -- Read the entry from the directory handle and return the file name of the next file in the directory. File names are returned in order in the file system.
eg:

Code

// 注意在 4.0.0-RC2 之前不存在 !== 运算符
if ($handle = opendir(&#39;/path/to/files&#39;)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
  
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
   
while ($file = readdir($handle)) {
echo "$file\n";
}
     closedir($handle);
}
Copy after login


3. scandir -- List the files and directories in the specified path (very Useful), returns an array containing the files and directories in directory.
The default sort order is in ascending alphabetical order. If the optional parameter sorting_order is used (set to 1), the sort order is descending alphabetical order.
eg:

$dir    = &#39;/tmp&#39;;
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
Copy after login

另外注:

七、 对文件属性的操作(操作系统环境不同,可能有所不一样,这点要注意)

1文件是否可读:

       boolis_readable ( string filename )
Copy after login

如果由 filename 指定的文件或目录存在并且可读则返回 TRUE。

记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。

2 文件是否可写

         bool is_writable ( string filename )
Copy after login

如果文件存在并且可写则返回 TRUE。filename 参数可以是一个允许进行是否可写检查的目录名。

记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制

3 检查文件是否存在

    boolfile_exists ( string filename )
Copy after login

      如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE


以上就是(进阶篇) PHP常用的文件操作函数的内容,更多相关内容请关注PHP中文网(www.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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

See all articles