search
HomeBackend DevelopmentPHP TutorialSummary of php file system processing methods, _PHP tutorial

A summary of php file system processing methods,

This article summarizes and analyzes the php file system processing methods. Share it with everyone for your reference, the details are as follows:

File Type

Based on Linux, in Windows you can only get three types: file, dir or unknown
Under Linux/Unix, block, char, dir, fifo, file, link, unknown7 types

block : block configuration files, disk partitions, floppy drives, cd-rom, etc.
char: character device, I/O (input and output) device in character units, such as keyboard, printer, etc.
dir: Directory is also a type of file/directory file
fifo: Information pipe, transferred from one program to another
file: Common file types such as text files, executable files
link: Link file, equivalent to shortcut under windows
unknown :Unknown type

1. File attribute processing function

filetype("directory or file name") gets the type
is_dir -- Determine whether the given file name is a directory
is_file -- Determine whether the given file name is a normal file
is_link -- Determine whether the given file name is a symbolic link
is_executable(); -- Determine whether the given file name is executable
file_exists();--whether the file exists
filesize();--Return file size
is_readable();--whether the file is readable
is_writeable();--whether the file is writable
filectime();--File creation time
filemtime();--File modification time
fileacttime();--The last access time of the file
stat();--File status, returns an array of information about the given file

bool ftruncate (resource handle, int size);

Accepts the file pointer handle as a parameter and truncates the file size to size. Returns TRUE on success, FALSE on failure.

bool rename ( string oldname, string newname [, resource context] );

2. Table of Contents

Directory Properties

* basename(url[,扩展名]);   //返回文件名
* dirname(url);   //目录名
* pathinfo(url);  //路径信息

Example:

$path="/var/www/html/page.php";
echo basename($path);// 返回page.php
echo basename($path,".php"); //page
echo dirname($paht);// /var/www/html
$arr=pathinfo($paht);
$arr["dirname"] // /var/www/html
$arr["basename"]// page.php
$arr["extension"]// .php

Traverse directories

opendir(url);
readdir(url);//返回当前目录指针只为的一个文件名,并将目录指针向后移动一位
closedir(url);
rewinddir(url);//把目录指针重置到开始处

Statistics directory size

To count the size of a directory, you can only create a recursive function to add up all the files in the directory;

To count disk size, you can use disk_free_space(url); and disk_total_space(url);

Create and delete directories

mkdir(url);//建立目录
rmdir(url);//删除空目录
unlink(url);//删除文件

To delete a non-empty directory, you can only create a recursive function yourself;

Copy directory

copy($scrfile,$to);//复制文件

Have a custom recursive function to implement directory copy function

3. Basic file operations

fopen(url);
fclose(url);

Write to file

int fwrite(resoure handle,strint string[,int length]);

Returns the number of characters written or FALSE

fputs() is an alias of fwrite()

int file_put_contents ( string filename, string data [, int flags [, resource context]] );

The function is the same as calling fopen(), fwrite() and fclose() in sequence.

Read file

string fread ( resource handle, int length );

Read up to length bytes from the file pointer handle. This function finishes reading length bytes or reaches EOF

string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] );
array file ( string filename [, int use_include_path [, resource context]] );

Each unit in the array is a corresponding line in the file, including newlines.

string fgets ( resource handle [, int length] );

string fgetc ( resource handle );

int readfile ( string filename [, bool use_include_path [, resource context]] );

Read in a file and write to the output buffer.

If you access remote files, you must activate the "allow_url_fopen" option in the PHP configuration file before you can use the fopen() function to open the remote file

When using the FTP protocol to connect to remote files, you can only open the file in "read-only" or "write-only" mode.

Move file pointer

int ftell ( resource handle );

Returns the position of the file pointer specified by handle, which is the offset in the file stream.

int fseek ( resource handle, int offset [, int whence] );

Set the file pointer position in the file associated with handle. The new position, measured in bytes from the beginning of the file, is the position specified by whence plus offset. whence de value is defined as:

SEEK_SET - Set position equal to offset bytes.
SEEK_CUR - Set the position to the current position plus offset.
SEEK_END - Set the position to the end of the file plus offset. (To move before the end of the file, pass a negative value for offset.)

bool rewind ( resource handle );

Set handle's file position pointer to the beginning of the file stream

Readers who are interested in more PHP related content can check out the special topics of this site: "Summary of PHP File Operations", "Summary of PHP Operations and Operator Usage", "Summary of PHP Network Programming Skills", "Introduction Tutorial on PHP Basic Grammar" ", "Summary of PHP office document operation skills (including word, excel, access, ppt)", "Summary of PHP date and time usage", "Introduction to PHP object-oriented programming tutorial", "Summary of PHP string (string) usage" , "Introduction Tutorial on PHP MySQL Database Operation" and "Summary of Common PHP Database Operation Skills"

I hope this article will be helpful to everyone in PHP programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133092.htmlTechArticleSummary of php file system processing methods. This article summarizes and analyzes the php file system processing methods. Share it with everyone for your reference, the details are as follows: File type is modeled on Linux, in Win...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools