What are the PHP file manipulation functions? Summary of PHP Common file operation function (with code)

Source: Internet
Author: User
PHP file Operation function There are many kinds of, today here I will share with you PHP commonly used file operation function, say, let us look at the PHP file operation what is the function of it.

1 php Gets the file name:
basename-returns the file name portion of the path

give a string containing a full path to a file, this function returns the base file name. If the file name ends in suffix, then this part will be removed as well.

String basename (String $path [, String $suffix])

$path = "/home/cate/index/index2.php"; $file = basename ($path); Echo $file. ' <br> '; index2.php
$file 2 = basename ($path, '. php '); Echo $file 2;    Index2
$file 3 = basename ($path, ' 2.php '); Echo $file 2;    Index

2 PHP Get directory Name

dirname-returns the directory portion of the path

String dirname (string $path)

Gives a string containing a full path to a file, which returns the directory name after removing the file name.

echo dirname (__file__);

__file__ the path to the current file is the same as GETCWD ();

3 PHP Get path associative array

pathinfo-return the file path information

pathinfo () returns an associative array containing a Path the information. The following array elements are included:dirname,basename , and extension.

you can specify which cells to return through the parameters options. They include:pathinfo_dirname,pathinfo_basename and pathinfo_extension. The default is to return all cells. This function returns a string if it is not required to get all the cells.

<?php$path_parts = PathInfo ("/home/cate/index.action.html");///home/cate   file directory echo $path _parts["DirName"]. "<br/>";  index.action.html  file name echo $path _parts["basename"]. "<br/>";  HTML        extension echo $path _parts["extension"]. "<br/>";//Direct access to the extension       echo pathinfo ("/home/cate/index.action.html", pathinfo_extension);

4 fopen Function-Open file or URL

Resource fopen (String $filename, String $mode [, bool $use _include_path [, Resource $zcontext]])

' R '

Read-only opens, pointing the file pointer to the file header.

' R+ '

Read-write mode opens, pointing the file pointer to the file header.

' W '

The Write method opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.

' w+ '

Read-write mode opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.

A

Write to open, pointing the file pointer to the end of the file. If the file does not exist, try to create it.

' A + '

Read-write mode opens, pointing the file pointer to the end of the file. If the file does not exist, try to create it.

' X '

Creates and opens in 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, try to create it. This specifies o_excl| for the underlying open (2) system call The O_creat tag is equivalent. This option is supported by PHP 4.3.2 and later versions and can only be used on local files.

' x+ '

Creates and opens read-write, 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, try to create it. This specifies o_excl| for the underlying open (2) system call The O_creat tag is equivalent. This option is supported by PHP 4.3.2 and later versions and can only be used on local files.

<?php    $handle = fopen ("Doc.txt", "R");    Var_dump ($handle);

D:\wamp\www\test\jsontest.php:3:Resource(3, stream)

<?php    $file = fopen (' Newtxt.txt ', ' w ') or Die (' cannot open file ');//does not exist automatically created    $data = ' You is a coder! ';    Fwrite ($file, $data);    $data = ' You are a man! ';    Fwrite ($file, $data);    Fclose ($file);

5 fstat Function-Get file information from an open file pointer

Array fstat (Resource $handle)

Gets the statistics for the file opened by the file pointer handle. This function is similar to the stat () function except that it acts on an open file pointer instead of a filename.

returns an array with statistics for the file, which is in detail in the stat () page of the manual .

<?php//Open File $fp = fopen ("Doc.txt", "R");//Get statistics $fstat = Fstat ($FP);//Close File fclose ($FP);//show only associative array parts//print_r (array_ Slice ($fstat, 13)); Print_r ($fstat);//Gets a file information array including index and associative array

array_slice-to remove a paragraph from an array to return an array

Array array_slice (array $array, int $offset [, int $length [, bool $preserve _keys]])

array_slice () returns a sequence in an array of arrays specified by the offset and length parameters.

if offset is non-negative, the sequence starts at this offset in the array. If offset is negative, the sequence starts at a distance from the end of the array.

if length is given and is positive, then there will be so many cells in the sequence. If length is given and is negative, the sequence terminates so far away from the end of the array. If omitted, the sequence starts at offset from the end of the array.

<?php$input = Array ("A", "B", "C", "D", "E"), $output = Array_slice ($input, 2);      Returns "C", "D", and "e" $output = Array_slice ($input,-2, 1);  Returns "D" $output = Array_slice ($input, 0, 3);   Returns "A", "B", and "C"//note the differences in the array keysprint_r (Array_slice ($input, 2,-1));p Rint_r (Array_sli CE ($input, 2,-1, true));

Array

(

[0] = C

[1] = d

)

Array

(

[2] = C

[3] = d

)

6 filesize Function-Get file size

int filesize (string $filename)

returns the number of bytes of file size, if an error is returned FALSE and generate a e_warning level of error.

<?php$filename = ' doc.txt '; echo $filename. ': '. FileSize ($filename). ' Bytes ';

Doc.txt:46bytes

7.disk_free_space function-Returns the free space in the directory

float disk_free_space (String $directory)

Given a string containing a directory, this function returns the number of available bytes based on the corresponding file system or disk partition.

<?phpecho disk_free_space ("C:"). ' <br/> '; Echo disk_free_space ("D:"). ' <br/> '; Echo disk_free_space ("/");

71001600000
186459181056

disk_total_space-returns the total disk size of a directory

8 Fileatime Function-Gets the last access time of the file

filectime-Get the Inode modification time of the file

filemtime-Get File modification time

9 file function-reads the entire document into an array

<?php$myfile = ' Doc.txt '; $lines = file ($myfile); for ($i =0, $len = count ($lines); $i < $len; $i + +) {    echo mb_ Convert_encoding ($lines [$i], "UTF-8", "GBK"). ' <br/> ';}

I am a novice programmer, need to work slowly to gain 1!
I am a novice programmer, need to work slowly to gain 2!
I am a novice programmer, need to work slowly to gain 3!
I am a novice programmer, need to work slowly to gain 4!
I am a novice programmer, need to work slowly to gain 5!
I am a novice programmer, need to work slowly to gain 6!

Mb_convert_encoding ($lines [$i], "UTF-8", "GBK")

Place each line of the original GBK formatted Data $lines[$i] converted to UTF-8 format in Windows

String mb_convert_encoding (String $str, String $to _encoding [, Mixed $from _encoding])

<?php$myfile = ' Doc.txt '; $encoding = mb_detect_encoding ($myfile, Array (' GBK ', ' UTF-16 ', ' UCS-2 ', ' UTF-8 ', ' BIG5 ', ' (ASCII ')); Echo $encoding;

CP936 is GBK

mb_detect_encoding- Detection Character Set The first is a file or a path the second is a possible character set

fgets function-Reads a row from the file pointer

String fgets (int $handle [, int $length])

Reads a row from the file pointed to by handle and returns a string of up to length-1 bytes in length. Stop after encountering a newline character (included in the return value), EOF, or having read the length-1 byte (see first the case). If length is not specified, the default is 1 K, or 1024 bytes.

return when error occurs FALSE .

<?php$handle = fopen (' doc.txt ', ' r '), if ($handle) {while    (!feof ($handle)) {        $data [] = Fgets ($handle, 1024x768);    }    Print_r ($data);    Fclose ($handle);}
Array (    [0] = = I am a novice programmer and need to work slowly to gain 1!    [1] = = I am a novice programmer, need to work slowly to gain 2!    [2] = = I am a novice programmer, need to work slowly to gain 3!    [3] = = I am a novice programmer, need to work slowly to gain 4!    [4] = = I am a novice programmer, need to work slowly to gain 5!    [5] = = I am a novice programmer, need to work slowly to gain 6! )

feof-Test If the file pointer is at the end of the file

If the server does not close the connection openedby Fsockopen (),feof () waits until the timeout expires and returns TRUE. The default time-out limit is 60 seconds, and you can use Stream_set_timeout () to change the value.

fclose-Close an open file pointer

FGETSS function--Reads a line from the file pointer and filters out HTML tags
Same as fgets () except that FGETSS attempts to remove any HTML and PHP markup from the text that is being read.

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

file_exists-checking whether a file or directory exists

BOOL file_exists (string $filename)

Returns TRUE If the file or directory specified by filename is present, otherwise FALSE.

file_put_contents function- writes a string to a file

int file_put_contents (String $filename, String $data [, int $flags [, Resource $context]])

and sequentially call fopen (),fwrite (), and the fclose () function.

FileNamethe file name to write the data to
Datathe data to write. Type can bestring,Array(but not for multidimensional arrays), orStreamResources
FlagsOptional, rules how to open/write the file. Possible values:
File_use_include_path: Checkfilenamebuilt-in path to the replica
File_append: Writes data appended to the end of the file
Lock_ex: Lock the file
ContextOptional,Contextis a set of options through which you can modify text properties

    • fopen ()- open file or URL

    • Fwrite ()- write file (can be used safely for binary files)

    • File_get_contents ()- reads the entire file into a string

<?phpecho file_put_contents (' doc.txt ', ' You are a programmer 7 ', file_append);

returns the number of bytes 22

If the file does not exist, the file is created, which is equivalent to the fopen () function behavior.

If the file exists, the contents of the file are emptied by default, and you can set the flags parameter value to file_append to avoid.

The file_put_contents function can be used safely with binary objects.

If it is a good idea to make a decision about a file that already exists,

if (file_exists (' Test.txt ')) {    file_put_contents (' test.txt ', ' contents ');}

Related recommendations:

PHP file operation methods and examples of detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.