PHP common file operation functions Classic Collection _php Tips

Source: Internet
Author: User
Tags error code error handling explode html tags readable delete cache
The following is a personal summary of the PHP file manipulation function. Of course, that's just part of it, and there's a lot that I haven't listed.
first, parse the path
1 Get FileName:
BaseName ();
Gives a string containing a full path to a file, which returns the base file name. If the filename ends with suffix, that part will also be removed.
eg
Copy Code code as follows:

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

2 Get the Contents section:
DirName ();
Gives a string containing a full path to a file, which returns the name of the directory after the file name is removed.
eg
Copy Code code as follows:

$path = "/etc/passwd";
$file = DirName ($path); $file is set to "/etc"

3 Get path Associative array
PathInfo ();
Gets three parts of a specified path: directory name, base name, extension.
eg
Copy Code code as follows:

$pathinfo = PathInfo ("www/test/index.html");
Var_dump ($pathinfo);
$path [' dirname ']
$path [' basename ']
$path [' Extenssion ']

ii. Types of documents
1. filetype ();
Returns the type of file. The possible values are fifo,char,dir,block,link,file and unknown.
eg
Copy Code code as follows:

echo filetype ('/etc/passwd '); File
echo filetype ('/etc/'); Dir

three, get the given file useful information array (very useful)
1. Fstat ();
Get file information from an open file pointer
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 rather than a filename.
eg
Copy Code code as follows:

Open File
$fp = fopen ("/etc/passwd", "R");
Get statistical information
$fstat = Fstat ($FP);
Close File
Fclose ($FP);
Show only associative array parts
Print_r (Array_slice ($fstat, 13));

2. Stat ()
Gets the statistics for the file specified by filename (analogy fstat ())
four, calculate the size
1. FileSize ()
Returns the number of bytes in the file size, if error returns false and generates a e_warning level error.
eg
Copy Code code as follows:

Output similar to: somefile.txt:1024 bytes
$filename = ' somefile.txt ';
Echo $filename. ': ' . FileSize ($filename). ' bytes ';
2. Disk_free_space ()
Get free Space (in bytes) for the partition on which the directory resides
eg
[Code]
$DF contains the number of bytes available under the root directory
$DF = Disk_free_space ("/");
Under Windows:
Disk_free_space ("C:");
Disk_free_space ("D:");

3. Disk_total_space ()
Returns the total disk size of a directory
Eg: (ditto, change function)
Another: If you need to calculate a directory size, you can write a recursive function to implement
Code
Copy Code code as follows:

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

v. Time of visit and modification
1. Fileatime (): Last Access time
2. Filectime (): Final change of time (any data modification)
3. Filemtime (): Last modification time (refers to content modification only)
vi. file I/O operations
1. fopen--Open file or URL
Mode description
The ' R ' read-only mode opens, pointing the file pointer to the file header.
' r+ ' read-write mode opens, pointing the file pointer to the file header.
The ' W ' 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 creating it.
' w+ ' read-write mode opens, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try creating it.
The ' a ' write mode opens, pointing the file pointer at the end of the file. If the file does not exist, try creating it.
An ' A + ' read-write mode opens, pointing the file pointer to the end of the file. If the file does not exist, try creating it.
' X ' is created and opened in 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 in read-write mode, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE
eg
Copy Code code as follows:

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

2. FILE-read the entire file into an array (this function is useful)
As with file_get_contents (), only file () is returned as an array. Each cell in the array is the corresponding line in the file, including line breaks. If failure file () returns FALSE.
eg
Code
Copy Code code as follows:

$lines = File (' http://www.example.com/');
Loops through the array, displaying the source file for the HTML and adding the line number.
foreach ($lines as $line _num => $line) {
echo "line #<b>{$line _num}</b>:". Htmlspecialchars ($line). "<br/>\n";
}
Another example reads a Web page into a string. See File_get_contents ().
$html = Implode (', File (' http://www.example.com/'));

3. Fgets--reading a row from the file pointer
Reads a row from the file pointed to by handle and returns a string with a maximum length of length-1 bytes. Stops when a line break is encountered (including in the return value), EOF, or after the length-1 byte has been read (see what happens first). If length is not specified, the default is 1 K, or 1024 bytes.
eg
Copy Code code as follows:

$handle = @fopen ("/tmp/inputfile.txt", "R");
if ($handle) {
while (!feof ($handle)) {
$buffer = Fgets ($handle, 4096);
Echo $buffer;
}
Fclose ($handle);
}

4. FGETSS--read a row from the file pointer and filter out the HTML tags
Same as fgets () except that FGETSS tries to remove any HTML and PHP tags from the read text.
You can specify which tags are not removed with the optional third argument
Another: The operation of the directory:
1. Opendir-Opens a directory handle, opens a directory handle, and can be used in subsequent closedir (), Readdir (), and Rewinddir () calls.
2. Readdir-Reads the entry from the directory handle and returns the file name of the next file in the directory. The file name is returned in the sort in the file system.
eg
Code
Copy Code code as follows:

Note that the!== operator does not exist before 4.0.0-RC2
if ($handle = Opendir ('/path/to/files ')) {
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);
}
[Code]
3. Scandir--Lists the files and directories in the specified path (useful), returns an array containing the files and directories in the directory.
The default sort order is sorted alphabetically. If you use the optional parameter Sorting_order (set to 1), the sort order is sorted alphabetically.
eg
[Code]
$dir = '/tmp ';
$files 1 = scandir ($dir);
$files 2 = Scandir ($dir, 1);
Print_r ($files 1);
Print_r ($files 2);

Note also:
Seven, the operation of the file properties (operating system environment, may be different, this should be noted)
1 whether the file is readable:
Boolis_readable (string filename)
Returns TRUE if the file or directory specified by filename exists and is readable.
Remember that PHP may only access files with the username (usually ' nobody ') running webserver. does not count into the security mode limit.
2 whether the file can be written
BOOL Is_writable (string filename)
Returns TRUE if the file exists and is writable. The filename parameter can be a directory name that allows for writable checking.
Remember that PHP may only access files with the username (usually ' nobody ') running webserver. Excluding security mode restrictions
3 Check for file existence
Boolfile_exists (string filename)
Returns TRUE if the file or directory specified by filename is present, otherwise returns FALSE
=====================================php file Operation class =========================================
Copy Code code as follows:

<?php
/***************************************************************************************
FileName: File.cls.php
Introduction to Files: Definition of class clsfile, encapsulation of file operations
Version: 2.0 Last modified: 2011-8-23
****************************************************************************************/
!defined (' INIT_PHPV ') && die (' No Direct script access allowed ');
Class Clsfile
{
Private $fileName _str; The path to the file
Private $fileOpenMethod _str; File open mode
function __construct ($fileName _str= ', $fileOpenMethod _str= ' readOnly ')/path, default is null; mode, default is read-only
{
Constructors, completing initialization of data members
$this->filename_str= $fileName _str;
$this->fileopenmethod_str= $fileOpenMethod _str;
}
function __destruct ()
{
destructor
}
Public Function __get ($valName _val)//The name of the data member you want to obtain
{
A special function that gets the value of the specified name data member
return $this-> $valName _val;
}
Private Function On_error ($errMsg _str= ' unkown error! ', $errNo _int=0)//error message, error code
{
Echo ' program error: '. $ERRMSG _str. ' Error code: '. $errNo _int;//error handling function
}
Public Function open ()
{
Open the file and return to the file resource ID
Select open Mode according to FILEOPENMETHOD_STR
Switch ($this->fileopenmethod_str)
{
Case ' readOnly ':
$openMethod _str= ' R '; Read-only, pointing to file headers
Break
Case ' ReadWrite ':
$openMethod _str= ' r+ '; Read and write, pointer to file header
Break
Case ' Writeandinit ':
$openMethod _str= ' W '; Write-only, pointer to file header to truncate size to zero, not existing to create
Break
Case ' Readwriteandinit ':
$openMethod _str= ' r+ '; Read-write, the pointer points to the file header to truncate the size to zero, and does not exist to create
Break
Case ' Writeandadd ':
$openMethod _str= ' a '; Write-only, pointer to end of file, no existing to create
Break
Case ' Readwriteandadd ':
$openMethod _str= ' A + '; Read-write, pointer to end of file, no existing to create
Break
Default
$this->on_error (' Open method error! ', 310);//error handling
Exit
}
Open File
if (! $fp _res=fopen ($this->filename_str, $openMethod _str))
{
$this->on_error (' can\ ' t open the file! ', 301);//error handling
Exit
}
return $fp _res;
}
Public function Close ($fp _res)//resource identification returned by open
{
Close the Open file
if (!fclose ($fp _res))
{
$this->on_error (' can\ ' t close the file! ', 302);//error handling
Exit
}
}
Public function write ()//$fp _res, $data _str, $length _int: File resource ID, write string, length control
{
Writes the string string_str to the file Fp_res, which controls the length of the write Length_int
To determine the number of parameters, call the correlation function
$argNum _int=func_num_args ()//number of parameters
$FP _res=func_get_arg (0); File Resource Identification
$data _str=func_get_arg (1); String to write
if ($argNum _int==3)
{
$length _int=func_get_arg (2); Length control
if (!fwrite ($fp _res, $data _str, $length _int))
{
$this->on_error (' can\ ' t write the file! ', 303);//error handling
Exit
}
}
Else
{
if (!fwrite ($fp _res, $data _str))
{
$this->on_error (' can\ ' t write the file! ', 303);//error handling
Exit
}
}
}
Public Function Read_line ()//$fp _res, $length _int: File resource ID, read in length
{
Read one line of string from file Fp_res to control length
Determine the number of parameters
$argNum _int=func_num_args ();
$FP _res=func_get_arg (0);
if ($argNum _int==2)
{
$length _int=func_get_arg (1);
if ($string _str=!fgets ($fp _res, $length _int))
{
$this->on_error (' can\ ' t read the file! ', 304);//error handling
Exit
}
return $string _str;
}
Else
{
if (! $string _str=fgets ($fp _res))
{
$this->on_error (' can\ ' t read the file! ', 304);//error handling
Exit
}
return $string _str;
}
}
Public function Read ($fp _res, $length _int)//File resource identification, length control
{
Read the file fp_res, the longest is length_int
if (! $string _str=fread ($fp _res, $length _int))
{
$this->on_error (' can\ ' t read the file! ', 305);//error handling
Exit
}
return $string _str;
}
Public Function is_exists ($fileName _str)//file name
{
To check if the file $filename_str exists, to return true if it exists, and not to return false
Return file_exists ($fileName _str);
}
/****************** Get File Size *********************/
/*
Gets the size of the file Filename_str
$fileName _str is the path and name of the file
Returns the value of the file size
*/
Public Function get_file_size ($fileName _str)//file name
{
return FileSize ($fileName _str);
}
/****************** a representation of the size of the converted file *********************/
/*
$fileSize the size of the _int file, in bytes
Returns the size of the file with units of measure after conversion
*/
Public Function change_size_express ($fileSize _int)//file name
{
if ($fileSize _int>1024)
{
Convert $fileSizeNew _int= $fileSize _int/1024;//to K
$unit _str= ' KB ';
if ($fileSizeNew _int>1024)
{
Convert $fileSizeNew _int= $fileSizeNew _int/1024;//to M
$unit _str= ' MB ';
}
$fileSizeNew _arr=explode ('. ', $fileSizeNew _int);
$fileSizeNew _str= $fileSizeNew _arr[0]. substr ($fileSizeNew _arr[1],0,2). $unit _str;
}
return $fileSizeNew _str;
}
/****************** Rename File *********************/
/*
Rename the file specified by Oldname_str to Newname_str
$oldName _str is the original name of the file
$newName _str is the new name of the file
return error message
*/
Public Function Rename_file ($oldName _str, $newName _str)
{
if (!rename ($oldName _str, $newName _str))
{
$this->on_error (' can\ ' t rename file! ', 308);
Exit
}
}
/****************** Delete File *********************/
/*
Delete the file specified by Filename_str
$fileName _str the path and name of the file to delete
return error message
*/
Public Function Delete_file ($fileName _str)//
{
if (!unlink ($fileName _str))
{
$this->on_error (' can\ ' t delete file! ', 309);//error handling
Exit
}
}
/****************** the file name extension *********************/
/*
Filename_str the file name specified by the extension
$fileName _str the file path and name of the type to be taken
Returns the file name extension
*/
Public Function Get_file_type ($fileName _str)
{
$fileNamePart _arr=explode ('. ', $fileName _str);
while (list (, $fileType _str) =each ($fileNamePart _arr))
{
$type _str= $fileType _str;
}
return $type _str;
}
/****************** determine if the file is a specified file type *********************/
/*
Type of file specified $fileType _str
$fileName _str the file path and name of the type to be taken
Returns False or True
*/
Public Function Is_the_type ($fileName _str, $fileType _arr)
{
$cheakFileType _str= $this->get_file_type ($fileName _str);
if (!in_array ($cheakFileType _str, $fileType _arr))
{
return false;
}
Else
{
return true;
}
}
/****************** upload file, and return the uploaded file information *********************/
/*
$fileName _str Local file name
$filePath the path of the uploaded file, if $filepath is str then upload to the same directory with a file name, the new file name in its add -1,2,3 ... if it is arr, then the order is named
$allowType _arr allowed file types to be uploaded, leave blank
$maxSize _int The maximum allowable file size, leave blank
Returns a two-dimensional array of new file information: $reFileInfo _arr
*/
Public Function Upload_file ($fileName _str, $filePath, $allowType _arr= ', $maxSize _int= ')
{
$fileName _arr=$_files[$fileName _str][' name ']; The name of the file
$fileTempName _arr=$_files[$fileName _str][' tmp_name ']; Cached files for files
$fileSize _arr=$_files[$fileName _str][' size '];//get file sizes
$reFileInfo _arr=array ();
$num =count ($fileName _arr)-1;
for ($i =0; $i <= $num; $i + +)
{
if ($fileName _arr[$i]!= ")
{
if ($allowType _arr!= ' and! $this->is_the_type ($fileName _arr[$i], $allowType _arr))//To determine whether the file type is allowed
{
$this->on_error (' The file is not allowed type! ', 310);//error handling
Break
}
if ($maxSize _int!= ' and $fileSize _arr[$i]> $maxSize _int)
{
$this->on_error (' The file is too big! ', 311);//error handling
Break
}
$j = $i +1;
$fileType _str= $this->get_file_type ($fileName _arr[$i]);//Get file type
if (!is_array ($filePath))
{
$fileNewName _str= $filePath. '-'. ($J). $fileType _str;
}
Else
{
$fileNewName _str= $filePath _arr[$i]. $fileType _str;
}
Copy ($fileTempName _arr[$i], $fileNewName _str);//Upload file
Unlink ($fileTempName _arr[$i]);//Delete cache file
---------------Store file information--------------------//
$doFile _arr=explode ('/', $fileNewName _str);
$doFile _num_int=count ($doFile _arr)-1;
$reFileInfo _arr[$j] [' name ']= $doFile _arr[$doFile _num_int];
$reFileInfo _arr[$j] [' type ']= $fileType _str;
$reFileInfo _arr[$j] [' Size ']= $this->change_size_express ($fileSize _arr[$i]);
}
}
return $reFileInfo _arr;
}
/****************** backup Folder *********************/
}
?>

I hope it works for you.

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.