Write file manipulation cross-platform PHP code

As we use Windows computers to develop our PHP scripts and Linux servers in production, we must be careful about what we use in our PHP script, especially when manipulating files.

A lot of PHP function work well in cross-platform, rename(), unlink(), copy(), realpath(), glob() … all of them will do the job, whether they are called in Linux, or Windows, but when playing with temporary directory (That can be at different places, even on same platform), parsing file paths or include_path, we need some tools.

One thing to avoid is doing specific part of code for Windows, and specific for Linux.
So I will focus in this post on some functions and constants around file manipulation that are helpful when writing cross-platform code.

Temporary directory with sys_get_temp_dir()

sys_get_temp_dir() function is useful to find the path of the directory PHP stores temporary files by default.

Will output on Windows

and on Linux

If you want to put some files in temporary directory, and don’t want to check what is the temporary directory path, sys_get_temp_dir() is the function made for that.

DIRECTORY_SEPARATOR

Even if some people tell you that / will do the job in both Windows and Linux, using DIRECTORY_SEPARATOR is the good way to go.
Nothing tell us that next PHP Version or next OS you will deploy your PHP on will not change this, it’s not about if it works or not with /, but if you really want to do cross-platform PHP at 100%, not just when you find it useful.

So DIRECTORY_SEPARATOR will produce / on Linux, and \ on Windows.

Where it’s again useful, is for exploding or applying regular expression on paths

will look and perform better than doing

PATH_SEPARATOR

When playing with include_path, one difference between Windows and Linux, is the path separator between each include path, : for Linux and ; for Windows.
PATH_SEPARATOR will contain the right path separator for the actual platform.

Will output in Linux

And on Windows

Creating and managing temporary files with tmpfile()

tmpfile() function is useful as it will create a temporary file with a unique name in read-write mode and will returns a file handle to use with fwrite(), fread(), …
The file is then removed by PHP when closed (fclose()), or when the script ends, you don’t have to worry about cleaning or doing platform dependent code.

Will output on Linux

And on Windows

As you see, temporary file is created by PHP, and then removed without any action.

Conclusion

As you see, writing cross-platform PHP code is quick and simple, and can save you a lot of time, simply check PHP documentation if you have any doubt in a function.

Leave a Reply