Sunday, December 29, 2013

Summary of file and directory operation in PHP

1) File Operation in PHP

There are a lot of functions in PHP to do file and directory operations, such as
fopen, 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:
//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
       echo $content."<br />";
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: getcwd
create a new directory: mkdir
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
        echo $filename.'<br />';

Close directory: closedir
scandir:  read all file names in the directory into an array
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