unknown time to read, 1.72K views since 2016.10.09

Working with files and folders

Php has built-in functions to work with files and folders. Working with files can be very helpfull when you need to read some data from files, for example list of some items, cached data and whatever like. In case you dont have installed mysql or other database you can use files as a persistent storage for information on your websites.

There's much ways to read a file from php, but i'll cover only one that seems very convenient to me, of course he has some drawbacks, which i'll list in the end of paragraph.

I would be talking about file_get_contents and file_put_contents functions to read and write data into files accordingly.

Reading from a file using file_get_contents

Most cases i used reading from files in php i was need to read a whole file from the filesystem into string variable and then i worked with that string (exploding it by lines, by spaces, e.g).

file_get_contents is the most convenient for this purpose: one parameter as an input data and one simple result - string:

<?php

$content = file_get_contents('/var/www/mysite/products.json');

For simple reading function accepts one parameter - path to file, it could be either absolute or relative. In most cases this function used with satelites - functions that checks existance of a file, e.g: is_file and/or file_exists. For example some cache system based entirelly on files:

<?php

function getCached($key){
    $pathToCache = '/var/www/mysite/cache/';

    // encode key name with md5 hashing, so any cache-key would have the same length for the filename.
    $encodedFilename = md5($key);

    // construct proper filepath
    $filePath = ($pathToCache.'/'.$encodedName);

    If(file_exists($filePath)){ // return content of a file 
        return file_get_contents($filePath);
    } else { // if there is no file - return null
        return null;
    }
}

// get some data from cache file if it's exist
$cached = getCached('key');

Attention! This function, as whole php is blocking, and untill the whole file wouldnot be readed - you won'tbe able to proceed next in your app, so would be ready to wait some time if you have huge file. Also, this means that php would reserve amount of memory to keep the whole file in it. If you want to implement filedownload through php - file_get_contents is not a good choice, you'd better need to look at readfile function and do some tricks with output buffering in php. In case of file_get_contents each file download would eat as much memory as filesize is and you're lost whole memory of server incase of much simulatenous downloads.

write to files withfile_put_contents

As with reading - there are a lot of ways to write some data to file, but simplest one is by the help of file_put_content function. She takes two parameters - filepath as in case of file_get_contents and string, content that would be written to file. Lets implement writing to cache using this function:


function putCached($key,$value){

    $pathToCache = '/var/www/mysite/cache/';

    // encode key name with md5 hashing, so any cache-key would have the same length for the filename.
    $encodedFilename = md5($key);

    // construct proper filepath
    $filePath = ($pathToCache.'/'.$encodedName);

    // here's the part when we write data to file
    file_put_contents($filePath,$value);
}

Working with directories. Traversing of directories in php

One's very usefull to get list of files in some directory. For example you have a folder with translation files of your website and you need to list them somewhere. Lets traverse over that directory (walk over each file and folder in directory):

<?php

// path to directory, content of which we would investigate
$path = '/var/www/mysite/translations';

foreach(new DirectoryIteraror($path) as $file) {

    // here $file is instance of .

    If($file->isFile()){
        echo $file->getName().'</br>';
    } else {
        // here you can work with directories
    }
}

Each $file has pretty methods like getName,getPath, getSize and others, names of which are pretty obvious and methods itself are usefull.

Conclusion

Using three features i wrote on this article you can create cool features in php using filesystem: from counters to cahing systems and other interesting stuff. You can write in the comments what interesting you've made withthe help of this article.

Read next article Cookies and session in course Basic PHP