File related functions/file IO

File information correlation

filetype()

filetype($filepath); Get the type of the file; Returns the type of the file

  • Returns the type of the file
  • Parameters:filepathFile path
  • The possible values arefifo.char.dir.block.link.fileunknown
  • Returns if there is an errorFALSE

      

$file_path = 'sort.php';
$dir_path = '.. / 0809 ';

var_dump(filetype($file_path)); // file
var_dump(filetype($dir_path)); // dir
Copy the code
D:\php20190701\php_code\0810\filetype.php:6:string 'file' (length=4)
D:\php20190701\php_code\0810\filetype.php:7:string 'dir' (length=3)
Copy the code

filesize()

filesize($filename); Get the size of the file; Returns the number of bytes;

  • Returns the number of bytes of file size, or if there is an errorFALSEAn E_WARNING error is generated
  • Note: Because PHP’s integer type is a signed integer and many platforms use 32-bit integers, some file system functions may return unexpected results for files larger than 2GB
  • Parameter :filename Specifies the path to the file


      

$file_path = 'sort.php';

var_dump(filesize($file_path)); / / 101 bytes
Copy the code

filectime()

filectime($filename); Get the creation time of the file; It returns a timestamp;

  • Returns the time when the file was created, or on failureFALSE
  • The time is returned as a Unix timestamp
  • Because it returns a timestamp, you can use the date() function to change the date and time zone;
    • Change timezone: date_default_timezone_set(‘PRC’);
    • Date (‘ y-m-d H: I :s’,filectime($filename));
  • Parameter :filename Specifies the path to the file

filemtime()

filemtime($filename); Get the modification time of the file; It returns a timestamp;

  • Returns the last time the file was modified, or on failureFALSE
  • The time is returned as a Unix timestamp and can be used for date()
  • (The date() function above)
  • Parameter :filename Specifies the path to the file

fileatime()

fileatime($filename); Get the last access time of the file; It returns a timestamp;

  • Returns the last time the file was accessed, or on failureFALSE
  • The time is returned as a Unix timestamp
  • Because it returns a timestamp, you can use the date() function to change the date and time zone;
    • The date() function looks like this; Change time zone and change to visible date;
  • Parameter :filename Specifies the path to the file

      

$file_path = 'sort.php';

var_dump(date('Y-m-d H:i:s',filectime($file_path))); 
var_dump(date('Y-m-d H:i:s',filemtime($file_path))); 
var_dump(date('Y-m-d H:i:s',fileatime($file_path))); 
Copy the code
D:\php20190701\php_code\0810\filetype.php:5:string 'the 2019-08-10 10:52:53' (length=19)
D:\php20190701\php_code\0810\filetype.php:6:string 'the 2019-08-10 11:15:33' (length=19)
D:\php20190701\php_code\0810\filetype.php:7:string 'the 2019-08-10 10:52:53' (length=19)
Copy the code

is_readable()

is_readable($filename); Check whether the file is readable; Returns a Boolean value;

  • Returns if the file or directory specified by filename exists and is readableTRUEOtherwise returnFALSE
  • Parameter :filename Specifies the path to the file

is_writable()/is_writeable()

is_writable($filename)/is_writeable($filename); Check whether the file is writable; Returns a Boolean value;

  • Returns if the file filename exists and is writableTRUE
  • The filename argument can be a directory name that allows writability checks
  • Is_writeable () is an alias of is_writable()
  • Parameters:filenameThe name of the file to check

      

$file_path = 'sort.php';

var_dump(is_readable($file_path));
var_dump(is_writable($file_path));
var_dump(is_writeable($file_path));
Copy the code
D:\php20190701\php_code\0810\filetype.php:5:boolean true
D:\php20190701\php_code\0810\filetype.php:6:boolean true
D:\php20190701\php_code\0810\filetype.php:7:boolean true
Copy the code

is_executable()

is_executable($filename); Check whether the file is executable; Returns a Boolean value;

  • Determines whether the given filename is executable
  • Returns if the file exists and is executableTRUE, returns if there is an errorFALSE
  • FALSEIndicates that the file is not executable.
  • Parameters:filenameFile path

      

$file_path = "C:\Users\Administrator\AppData\Local\Programs\Microsoft VS Code\Code.exe";

var_dump(is_executable($file_path)); // true
Copy the code

is_file()

is_file($filename); Check whether it is a file; Returns a Boolean value;

  • Determines whether the given filename is a normal file
  • Returns if the file exists and is a normal fileTRUEOtherwise returnFALSE
  • Note: Because PHP’s integer type is a signed integer and many platforms use 32-bit integers, some file system functions may return unexpected results for files larger than 2GB
  • Parameter :filename Specifies the path to the file

      

$file_path = 'sort.php';
$dir_path = '.. / 0809 ';

var_dump(is_file($file_path)); // true
var_dump(is_file($dir_path)); // false
var_dump(is_dir($dir_path)); // true
Copy the code

pathinfo()

pathinfo($filename); Obtain file path information. Returns an associative array;

  • The parameter is the file path
  • Returns information about an associative array that contains path
  • Returns an associative array or a string depending on options
  • If no options are passed, an array containing the following elements is returned: dirName, basename, and extension (if any), and filename
  • The options examples:
    • echo pathinfo($filename,PATHINFO_EXTENSION);——- Obtain the file name extension
  • Options If specified, returns the specified element; They include:
    • PATHINFO_DIRNAME
    • PATHINFO_BASENAME
    • PATHINFO_EXTENSION
    • PATHINFO_FILENAME
  • If no options are specified, all units are returned by default
  • __FILE__saidThe full path and filename of the file

      

$file_path = 'sort.php';

var_dump(pathinfo($file_path)); // true
Copy the code
D:\php20190701\php_code\0810\filetype.php:5:
array (size=4)
  'dirname' => string '. ' (length=1)
  'basename' => string 'sort.php' (length=8)
  'extension' => string 'php' (length=3)
  'filename' => string 'sort' (length=4)
Copy the code

dirname()

dirname($path); Returns the path portion of the file;

  • Given a string containing the full path to a file, this function returns the directory name with the filename removed
  • Return value: Returns the parent directory of path
  • Parameter: path A path
  • In Windows, both slashes (/) and backslashes (\) can be used as directory separators
  • Slash (/) in other contexts

      

$file_path = 'C: \ Users \ \ Administrator \ Downloads \ Firefox Setup 69.0 b11 exe';
$file_path2 = 'C: / Users/Administrator/Downloads/Firefox Setup 69.0 b11. Exe';

var_dump(dirname($file_path)); 
var_dump(dirname($file_path2));
Copy the code
D:\php20190701\php_code\0810\filetype.php:6:string 'C:\Users\Administrator\Downloads' (length=32)
D:\php20190701\php_code\0810\filetype.php:7:string 'C:/Users/Administrator/Downloads' (length=32)
Copy the code

basename()

basename($filename,$suffix); Returns the file name part of the path;

  • Given a string containing the full path to a file, this function returns the base filename
  • Parameter: path A path
  • In Windows, both slashes (/) and backslashes (\) can be used as directory separators
  • Slash (/) in other contexts
  • The second parameter is optional. Specifies the file extension. If the file has suffix, this extension is not printed.

      

$file_path = 'C: \ Users \ \ Administrator \ Downloads \ Firefox Setup 69.0 b11 exe';

var_dump(basename($file_path));
Copy the code
D:\php20190701\php_code\0810\filetype.php:6:string 'Firefox Setup 69.0 b11. Exe' (length=25)
Copy the code

      

$file_path = 'C: \ Users \ \ Administrator \ Downloads \ Firefox Setup 69.0 b11 exe';

var_dump(basename($file_path,".exe")); / / 'Firefox Setup 69.0 b11'

Copy the code

file_exists()

file_exists($filename); Check whether files or directories exist; Returns a Boolean value;

  • Return value: Returns if the file or directory specified by filename existsTRUEOtherwise returnFALSE
  • Parameter: filename Specifies the path to a file or directory

      

$file_path = "sort.php";
$dir_path = ".. / 0809";
$dir_path2 = ".. / 080911";

var_dump(file_exists($file_path)); // true
var_dump(file_exists($dir_path)); // true
var_dump(file_exists($dir_path2)); // false
Copy the code

File operation correlation

touch()

The touch ($filename, $time, $atime); Set the access and modification time of the file. If the file does not exist, the file will be created. Returns a Boolean value

  • Parameter: filename Specifies the name of the file to be set
  • If the file does not exist, it will be created
  • Return value: Returned on successTRUEOr return on failureFALSE
  • Time Time to be set. If no time parameter is provided, the current system time is used
  • Atime If given, the access time of the given file is set to atime, otherwise it is set to time
  • If these two parameters are not given, the current system time is used
  • The second parameter: sets the modification time
  • Third parameter: Sets the access time

unlink()

unlink($filename,$context); Delete files; Returns a Boolean value;

  • Delete the filename
  • Parameter: filename Specifies the path to the file
  • An E_WARNING level error is generated when an error occurs
  • Return value: Returned on successTRUEOr return on failureFALSE

      

$file_path = "sort.php";


var_dump(unlink($file_path)); // true
Copy the code

rename()

Rename ($oldname, $newname, $path); Rename or cut a file or directory; Returns a Boolean value;

  • Try to put theoldnamerenamenewname
  • Return value: Returned on successTRUEOr return on failureFALSE
  • Path Path to cut a file or directory
  • Same path, usually rename

      

$old_name = "sort.php";
$new_name = "sort2.php";

var_dump(rename($old_name,$new_name)); Sort2.php will be added to sort2.php
Copy the code
  • If the path is different, you can achieve the effect of shearing

      

$old_name = "sort2.php";
$new_name = ".. /sort2.php";

var_dump(rename($old_name,$new_name)); // true to achieve the clipping effect
Copy the code

copy()

copy($filename,$path); Copy a file; Returns a Boolean value;

  • $filename, the file name
  • $path: indicates the path to be copied
  • Return value: Returned on successTRUEOr return on failureFALSE
  • Pay attention toTo copy remote files, enable the PHP configuration optionsallow_url_fopen=On
  • Remote copy, equivalent to download

      

$old_name = "sort.php";
$new_name = "sort2.php";

var_dump(copy($old_name,$new_name)); // true
Copy the code

      

$old_name = "http://pic68.nipic.com/file/20150601/2692994_151045402000_2.jpg";
$new_name = "1.jpg";

var_dump(copy($old_name,$new_name)); / / download
Copy the code

The file content is related to the operation

fopen()

fopen(filename,mode)

  • The fopen() function opens a file or URL.
  • If fopen() fails, it returns FALSE with an error message.
  • Error output can be hidden by prefixing the function name with an ‘@’.
  • Returns a file handle, which is a resource type that needs to be used with other functions
  • Second parameter: how to open, how to open
    • “R” (open read-only, pointer to file header)
    • “R +” (open read/write mode, pointer to file header)
    • “W” (open write mode, clear file contents, try to create file if it doesn’t exist)
    • “W +” (read/write open, clear file contents, try to create file if it doesn’t exist)
    • “A” (write mode on, write file pointer to end of file, try to create file if it doesn’t exist)
    • “A +” (open in read/write mode, save the contents of the file by writing the file pointer to the end)
    • If the file is not found, r will report an error, but A and W will create a new file

      

$file_path = "test.txt";


var_dump(fopen($file_path, 'r')); // resource
Copy the code

fread()

string fread ( resource length )

  • The fread() function reads the open file.

  • The function stops running when the specified length is reached or the end of the file (EOF) is read, whichever comes first.

  • This function returns the string read, or FALSE on failure.


      

$file_path = "test.txt";


$file = fopen($file_path, 'r');

var_dump(fread($file,99)); // hello world !
Copy the code

      

$file_path = "test.txt";


$file = fopen($file_path, 'r');

var_dump(filesize($file_path));

var_dump(fread($file,filesize($file_path))); // hello world !
Copy the code

fwrite()|fput()

fwrite(file,string[,length])

  • The fwrite() function writes to an open file.
  • The function stops running when the specified length is reached or the end of the file (EOF) is read, whichever comes first.
  • The second argument, optional, is the maximum number of characters that can be written
  • If the function executes successfully, the number of bytes written is returned. On failure, return FALSE.

      
$file = fopen("test.txt"."w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
Copy the code

fclose()

fclose($file)

  • The fclose() function closes the open file.

  • This function returns TRUE on success and FALSE on failure.


      
$file = fopen("test.txt"."r");
//some code to be executed
fclose($file);
Copy the code

fgetc()

fgetc(file)

  • Read one character at a time

      


$file = fopen("test.txt"."r");

for ($i=0; $i < filesize('test.txt'); $i++) { 
	echo fgetc($file);
}


while(! feof($file)) {echo fgetc($file);
}
Copy the code

fgets()

fgets(file[,length])
Copy the code
  • Reads one line of characters at a time, including the trailing newline character

      

$file = fopen("test.txt"."r");

while(! feof($file)) {echo fgets($file);
}
Copy the code

fgetss()

fgetss(file[,length[,tags]])
Copy the code
  • Read one line at a time, filtering HTML tags

fgetcsv()

fgetcsv(file[,length[,separator[,enclosure]]])
Copy the code
  • Get one line of the CSV file at a time and convert the line into an indexed array

      


$file = fopen("index.csv"."r");

while ($arr = fgetcsv($file)) {
	var_dump($arr);
}

fclose($file);

Copy the code

fputcsv()

fputcsv(file,fields[,seperator[,enclosure]])
Copy the code
  • Turn the CSV array

      


$file = fopen("index.csv"."r+");

$arr = [
	'hello'.'world'.'!!!!!!! '
];


var_dump(fputcsv($file, $arr));
Copy the code

file_get_contents()

  • Saves the contents of the file in a string, based on the path
  • This parameter is mandatory. The opening mode is not specified. If the parameter is a web address, the HTML source code corresponding to the web address is returned
  • To enable openSSL in php.ini,extension=php_openssl.dll

      


$str = file_get_contents("index.csv");

var_dump($str);
Copy the code

file_put_contents()

  • Save the string to a file
  • Save the baidu source code to the local

      

file_put_contents('baidu.html', file_get_contents('https://www.baidu.com'));
Copy the code

file()

  • The file () function reads the entire file into an array.
  • According to line breaks, a line is an element that preserves the following line breaks

readfile()

  • Read the contents of the file and save them to a variable
  • The first parameter: the file path

      

$str = readfile('test.txt');
var_dump($str);
Copy the code

parse_ini_file()

  • The number parses a configuration file and returns its Settings as an array with a path

      

var_dump(parse_ini_file("C: \ phpStudy \ PHPTutorial \ PHP \ PHP - 7.2.1 - NTS \ PHP ini"));
Copy the code

parse_ini_string()

  • Convert the configuration file string to an associative array

      

$ini_string = ' xdebug.profiler_output_dir="C:\phpStudy\PHPTutorial\tmp\xdebug" xdebug.trace_output_dir="C:\phpStudy\PHPTutorial\tmp\xdebug" Zend_extension = "C: \ phpStudy - 7.2.1 - NTS \ PHPTutorial \ PHP \ PHP \ ext \ php_xdebug - 2.8.0 beta1-7.2 - vc15 - NTS. DLL." " xdebug.remote_enable = 1 xdebug.remote_autostart = 1 ';


var_dump(parse_ini_string($ini_string));
Copy the code

highlight_string()

  • Highlight the PHP code in the string. The argument is a string

highlight_file()

  • Highlight the PHP code in the file with the file path

      

var_dump(highlight_file('test.php'));
Copy the code