1) File Operation in PHP
There are a lot of functions in PHP to do file and directory operations, such asfopen, fwrite, fread, fcolse, file_put_contents, file_get_contents,
For example fopen is used to open a file, fread to read from a file and fclose to close file handler.
code example:
if($handle=fopen(test.txt','r')){
$content=fread($handle);
fclose($handle);
}
//change file line break to HTML line break: nl2br
echo nl2br($content);
We can also read and get line by line from a file using fgets
code example
if($handle=fopen(test.txt','r')){
while(1feof($handle)(
$content=fgets($handle);
echo $content."<br />";
}
fclose($handle);
}
Other functions related to file operation: filesize: file size
filemtime: modified time (change content)
filectime: changed time (change content or metadata such as chmod)
fileatime: last access time such as read or change.
touch($filename): update file time.
code example:
echo strftime('%m/%d/%Y %H%M', filemtime($filename))."<br />";
2) Directory operation in PHP
To get current working directory: getcwdcreate a new directory: mkdir
Example
makdir('mydir','0777'); //note permission may be overwritten by umask
makdir('mydir/dir1/dir2','0777',true);recursively create new directoy
change directory chdir
remove a directory: rmdir
is_dir: to check if it is a directory
opendir: open directory to get directory handler
readdir: to get each file in a directory
Example:
if($mydir=opendir('test')){
while($filename=readdir($mydir))
echo $filename.'<br />';
}
Close directory: closedir
scandir: read all file names in the directory into an array
Example:
$file_array=scandir('test');
foreach($file_array as $filename)
echo $filename.'<br />';
To remove . and .. in the array which may appear when we scan directory , we can add
if(stripos($filename, '.')>0) // i.e first occurrence of '.' not the first position.
No comments:
Post a Comment