Home >Backend Development >PHP Tutorial >PHP Advanced Features 2: File Processing

PHP Advanced Features 2: File Processing

WBOY
WBOYOriginal
2016-08-08 09:23:13842browse

File processing in PHP is also a very important module. The main content of this article is an introduction to the file system in PHP.

Purpose of file system

1. Project processing is inseparable from file processing

2. Files can be used to save data for a long time

3. Create cache and perform file operations in the server

File system functions Usage details

1. Basic judgment function

is_dir — judge whether the given file name is a directory

is_file — judge whether the given file name is a file

is_executable — judge whether the given file name is executable

is_link — Determine whether the given file name is a symbolic link

is_readable — Determine whether the given file name is readable

is_uploaded_file — Determine whether the file was uploaded through HTTP POST

is_writable — Determine the given file name Whether it is writable

is_writeable — an alias of is_writable

2. Obtain file-related information

file_exists — check whether the file or directory exists

fileatime — get the last access time of the file

filectime — get the inode of the file Modification time

filegroup — Get the group of the file

fileinode — Get the inode of the file

filemtime — Get the file modification time

fileowner — Get the owner of the file

fileperms — Get the permissions of the file

filesize — Get the file size

filetype — Get the file type

Let’s write an example below, pass in the file name and print its details.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

functiongetFileInfo($ filename){

       if(!file_exists($filename)){

                                                                                                                                                                                                                   with with ).'doesn't exist';

}

if(

is_file

($filename))

{

is a file';

                                                                                                                                                                                               'is a directory' ; $filename)){

echo $ filename.. $filename.' is not an executable file';

if(is_readable($filename)) {

hecho

$ Filename.. '' is readable '; }} Lse {

echo$filename.' is not readable';

                                                                                                                     ($filename)){

is writable';

}} Lse

{

echo $ Filename..

echo 文 'file' . $Filename. 'The size is' .getFilesize (Filesize ( $ Filename) .''; ; ; ; ; ;

The type of $filename.' is '.filetype( $filename).'';

echo'File'.$filename.' The owner of is '.fileowner($filename).'';                                                                                       The last access time of file '.$filename.' is '.getTime(fileatime($filename)

)

.''; ode is '.fileinode($filename) .'';

The modification time of 'file'.$filename.' is' .getTime(filemtime($filename)).'';

echo'The permissions of file '.$filename.' are '.fileperms($filename).'';

} functiongetTime($ time){

   return date(

'Y-m-d H:i:s'

,$time

)

; }

functiongetFileSize ($size){                        

                                                             ($size>=pow(2,40)){

                                                                                                                      ($size/pow(2,

40

),2); $dw

='PB'; size>=pow(2, 30)){

           $size=round($size/pow(2,30),2);

            $dw='TB';

}elseif($size> ;=pow(2,20)){

$size=round($ size/pow(2,20),2);

$dw ='GB';

        }elseif($size>=pow (2,10) ){

$size=round($ size/pow(2,10 $$$ dw='MB';         }        return

$size.$dw;

    

}

    

getFileInfo ('1.php');

Run results

1.php is a file
1.php is not an executable file
1.php is readable
1.php is not writable
The size of file 1.php is 2MB
The type of file 1.php is file
The owner of file 1.php is 1000
The last access time of file 1.php is 2015-03-04 12:58:33
The inode of file 1.php is 536185
File 1 The modification time of .php is 2015-03-04 12:58:32
The permission of file 1.php is 33204

3. File path related functions

Relative path: relative to the upper and lower directories of the current directory

. Current directory
.. Previous level directory

Path separator symbol

linux/Unix “/”
windows “”
No matter what operating system PHP’s directory separator symbol is / (Linux)

Absolute path: It can refer to the root of the operating system, or it can refer to the document root directory where the website is stored

If it is executed in the server (executed through PHP file processingfunction), the path "root" refers to The root of the operating system
If the program is a downloaded client, when accessing the files in the server, it can only be accessed through Apache. The "root" also refers to the document root directory

Three related functions

basename — Returns the

file name part of the path

dirname — Returns the directory part of the path

pathinfo — Returns the file path information

For example, the following example

1

2
3
4
5
6
7
8

; $url2=

"../www/yyy/login.rar"

; $url3=

"c:/appserv/www/demo .html"

;                                                              echo basename

(

$url1);

echo basename ($url2); echo

basename

($url3); echo

basename

($url4);

Running results

index.php
login.rar
demo.html
www.gif

It can be seen that the basename function returns the name of the file, which is the last item.
Let’s take a look at the usage of dirname

1
2
3
4
5
6
7
8

$url1 ="./aaa/bbb/index.php";

$url2="../www/yyy/login.rar";

$url3="c:/appserv/www/demo.html";

$ url4="http://localhost /yyy/www.gif";

echo dirname(dirname($url1));

echo dirname($url2);

echo dirname( $url3);

echo dirname($url4);

Running results

./aaa
../www/yyy
c :/appserv/www
http://localhost/yyy

You can find that the dirname function can be used in multiple levels of nesting. What is returned is the path where it is located, that is, all items except the last item.

In addition, all the above information of pathinfo can be obtained, including

file name and extension

For example, the following result

Array ( [dirname] => ../www/yyy [ basename] => login.rar [extension] => rar [filename] => login )

4. File creation, deletion and modification

touch — create a file

unlink — delete file

rename — Rename a file or directory

copy —

Copy a file

For example, the following example

Permission related content

rwx represents the owner of this file r read w write Read w write

For example

1

2

1

2
3
4
5

touch("./php.apahce");//Create file

unlink("C:/AppServ/www/xsphp/apache. php"); //Delete file

rename("./test.txt","d:/test2.txt"); //Rename the file

copy("cache.txt","./cache5.txt"); //Copy file

chmod("a.txt",755); //Set file permissions

34$strWarning: file_get_contents(2.txt): failed to open stream: No such file or directory

=

file_get_contents(

" 1.txt"

);echo$str;

?>

directly opens the content in the 1.txt file and returns the text information in the file.

If the file does not exist, it will prompt
Similarly, the file can also be a remote file, for example, the parameters are passed into http ://www.qq.com

can display the homepage content of Tencent.

Disadvantages: Cannot read the specified part of the content, read all at once.

2. file_put_contents(filename,content)

Write the file, filename is the file name of the written file, content is the written content, and the return value is the length of characters successfully written.

1

2

3echo3.file(filename)

file_put_ contents

("2.txt",

'abcd'

);?>

2.txt file will be created if it does not exist. file and write the character abcd String, returns 4, which is the length of the string. If the file exists, the file will be emptied, then the string will be written, and the write length will be returned.

Disadvantages: Files cannot be written in append mode.
file opens a file directly, and the returned result is an array, and each line is an element of the array. In other words, getting the number of rows only requires outputting the size of the array. For example

1

2

34$str

5

=

file(

"1.txt"

);var_dump($str);

echocount( $str)

;

?>

You can get the row content in the form of an array and output the number of rows.

Disadvantage: The content of the specified part cannot be read.

4.fopen(filename,mode)

filename is the file name, which can be a path plus name or a remote server file.

mode is the way to open a file

r, open the file in read-only mode
r+, in addition to reading, you can also write.
w, open in write-only mode. If the file does not exist, create the file and write the content. If the file exists and originally has content, all the content in the original file will be cleared and then written (open the existing file) Important files)
w+, in addition to writing with fwrite, you can also read fread
a, which is opened in write-only mode. If the file does not exist, create the file and write the content. If the file exists, it originally has content. , the original file content is not cleared, and new content is written at the end of the original file content, (append)
a+, in addition to writing with fwrite, you can also read fread
b, and open the file in binary mode (pictures, movies)
t, open the file in text mode

Note:

r+ has read and write attributes, starts writing from the beginning of the file, and retains the content that has not been overwritten in the original file;

w+ has read and write attributes, if when writing If the file exists, it will be cleared and written from scratch.

Returns a file resource

5.fwrite(file,content)

File writing function, file is the file resource, obtained with the fopen function, content is the writing content. Same as fputs function.

For example

1
2
3
4
5
6
7
8
9

php

$file=fopen("1.txt","r+");

$result =fwrite($file,"xx");

if ($result){

echo"Success"; "Failed";

}

?>

then write the resource from scratch, that is, set the first two characters to xx6. fread(file,size)read The length of the specified part of the file, file is the file resource, the object returned by fopen, and size is the length of the read characters.

For example

1

2

3

4

5

"r"

$file

=

fopen
(

"1.txt"

,
)

;

$content=fread ($file,filesize ("1.txt"));

echo$content ;?> ;

However, the above filesize method can only obtain the local file size, and a different method is needed to read remote files.

For example

1

2

3

4

5

6

7

8

$file=fopen("http://www.qq.com","r");

$str ="";

while(!feof($file)){ / /Judge time to end of file

$str.=fread($file,1024);

}

echo$str;

?>

7.f gets(file)

file is a file resource, read every time Take a row. For example, we read how many lines there are in Tencent's homepage.

1
2
3
4
5
6
7
8
9
10

$file=fopen("http://www.qq.com","r");

$str="";

$count=0;

while(! feof($file)){

$str.=fgets($file );

$count++;

}

echo $count;

? >

The result will be 8893. We can check the source file to see how many lines it has in total and just verify it.

7.fgetc(file)

is very similar to the fgets method. file is a file resource and reads characters each time. For example, we read how many characters there are in Tencent's homepage.

1
2
3
4
5
6
7
8
9
10

$file=fopen("http://www.qq.com","r");

$str="";

$count=0;

while(! feof($file)){

$str.=fgetc($file );

$count++;

}

echo $count;

? >

The above code will output all the number of characters.

8.ftell(file)

ftell returns the pointer position of the currently read file, file is the file resource, and is the object returned by fopen.

9.fseek(file,offset,whence)

file

The file system pointer is a resource typically created by fopen().

offset

Offset.

To move to the position before the end of the file, you need to pass a negative value to offset and set whence to SEEK_END.

whence

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.

10.rewind($file)

Back to the file header, file is a file resource

For example

11.flock(file, operation[,wouldblock])file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

php

$file =fopen("1.txt","r");

echoftell($file )."
";//Output the pointer position before reading

echofread( $file, 10)."
";//Read 10 characters, the pointer moves 10 units

echo ftell($file)."
";//Output the current pointer position after reading

fseek ($file,20,SEEK_CUR);//The current pointer moves forward 20 units

echoftell($ file)."
";//Output the position of the pointer after movement

echof read($file ,10)."
";//Output the 10 characters read

echoftell ($file)."
";//Output the position of the pointer after reading 10 characters

f seek( $file,-20,SEEK_END);//Move the pointer to the first 20 characters of the end of the file

echo ftell($file)."
";//Output the position of the pointer after movement

echofread ($file,10)."
";//Output the last 20 characters of the file

echo ftell($file)."
";//Output the position of the pointer after reading 10 characters

rewind($file);//Return to the head of the file

echoftell($file)."
";//Output the position of the pointer after movement

> 840

The file resource pointer is a resource typically created by fopen().

operation

operation can be one of the following values:



LOCK_SH takes the shared lock (reading program).

LOCK_EX Gets an exclusive lock (written program).

LOCK_UN Releases the lock (whether shared or exclusive).


If you don’t want flock() to block on lock, LOCK_NB (not yet supported on Windows).

wouldblock

If the lock would block (in case of EWOULDBLOCK error code), the optional third parameter will be set to TRUE. (Not supported on Windows)

For example

1

2

3

4

5

6

7

;
php

$file

=

fopen
(

"1.txt "
,

"a"

)

if(flock($file,LOCK_EX )){

fwrite($file,"xxx");

flock

($file,LOCK_UN );

}

?> The above has introduced PHP advanced feature 2: file processing, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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