Linux Server Administration Tips PHP Tips & Tutorials

PHP: Back tick `

Back tick ` in PHP is used to read the output from another program, usually external commands in Linux shell, much like the way a pipe does the job with bash.

In PHP, Backtick “ embraced string is treated a command and executed externally in shell, returning the execution results from the standard output. For example,

$files = `ls -l`

And $files now contain the files and directory listing by the bash command ‘ls -l’.

PHP Tips & Tutorials

PHP: Randomizing All Lines of a File – Shuffle Lines in a Text File

Of course, you will have to read in the file first, preferably in an array.

To read a file in an array, you just need the file() function:

$lines = file('quotes.txt');

Then, you shuffle the array with shuffle() function that randomizes all the items in the array thus shuffling the lines in the file quotes.txt:

$lines = shuffle($lines);
PHP Tips & Tutorials

PHP: Count Lines of a File and Get the Number of Lines in a Text File

As we know, lines are separated from each other by line breaks indicated by “\n” in PHP, therefore, one method would be to explode() the entire file content string by “\n” into an array and then count() the number of the array items to come to the number of lines of that file.

However, there’s already a native built php function able to recognize line breaks, and that is fgets().

So, to count the lines of a file and get the line count:

$lines = 0;

if ($fh = fopen('orders.txt', 'r')) {
  while (!feof($fh)) {
    if (fgets($fh)) {
echo $lines; // line count
PHP Tips & Tutorials

PHP: Reading a File into a String or Reading the File into an Array

Aside from the common approach in reading a file with php fopen() function which is a little annoying in that it requires extra steps before actually reading the contents of the file.

PHP has other file reading functions to enable you instantly get what you want and read the contents of the file without the need to create a file handler manually. It’s automatically taken care of in the process.

To read a file into a string

Go with file_get_contents():

$book = file_get_contents('book.txt'); // $book is a single string containing the entire contents of book.txt
To read a file into an array with each line an item

Go with file():

$book = file('book.txt'); // $book is an array with all the lines from book.txt
PHP Tips & Tutorials

PHP: Open Remote File

By remote file, I mean files from another website or web server identified by a remote URL.

Usually, you can open such a file via the normal procedures you would take to open a local file with php file functions such as fopen() or file_get_contents(). However, to make this work, you will first make sure the value of allow_url_fopen in php.ini is set to on, otherwise it’d impossible to open a remote file just as you would do with a local one.

To open and possibly read a remotely hosted file in PHP:

$fh = fopen ('', 'r') or die('Unable to open remote file.');

If allow_url_fopen is set to true, $fh will be a file handler which you can use to read the contents of the robots.txt file hosted on

Another way is to use file_get_contents() function which will prove more handy if you want to read the remote file in just one PHP line:

$robotstxt = file_get_contents('') or die('Unable to open remote file.');
PHP Tips & Tutorials

PHP: Create a Temporary File

So you need a temporary file to hold some middle data. There are 2 functions in PHP you can use for creating temporary files:

  1. PHP function tmpfile() creates a temporary file, opens it and returns the file handler:

    $temp_fh = tmpfile();
    f write($temp_fh, "The current time is ".strftime('%c'));
    // the file automatically goes away when the script ends

    Very handy for temporary uses.

  2. PHP function tempnam() is a little more sophisticated in that it takes 2 parameters to create a custom file and returns the path to the new file:

    $tempfilename = tempnam('/tmp', 'data-');
    $temp_fh = f open($tempfilename, 'w');
    f write($temp_fh, "The current time is ".strftime('%c'));
PHP Tips & Tutorials

PHP: Copy, Rename or Move a File

PHP can only copy, rename or move files that are of the same owner with who is running the PHP script. After making sure of this, you can proceed to:

Copy a file to another place in PHP:

$old = '/tmp/yesterday.txt';
$new = '/tmp/today.txt';
copy($old, $new) or die("Unable to copy $old to $new.");

Rename a file and give it a new name:

$old = '/tmp/today.txt';
$new = '/tmp/tomorrow.txt';
rename($old, $new) or die("Unable to rename $old to $new.");

Move a file to a new place in PHP:

if (copy("/tmp/code.c","/usr/local/src/code.c")) {

Apparently you must make sure the copying is successful before doing the deletion.

Of course you can always execute a native Linux shell command such as ‘cp’ and ‘mv’ to do the dirty work for you instead of resorting to a PHP function. In this situation, you need the php function exec() to execute an external command.

PHP Tips & Tutorials

PHP: Make or Create A Directory

The function in PHP that’s used to create a directory is just the same with that in Linux bash shell: mkdir.

First make sure the current working directory is where you want the new directory to be, then run this line of PHP:

mkdir('new_dir'); // creates a new directory named new_dir under the current directory
PHP Tips & Tutorials

PHP: Change Current Working Directory

Every PHP script process has its own current working directory, files and directory are created under this directory by default if not otherwise specified.

The default working directory of any php script is the home directory of the php owner or the current working directory returned by Linux shell command pwd. As most of the time, PHP scripts are run from the Web, if not otherwise specified, the current working directory would be the home directory of the user.

However, you can always change the current working directory in PHP itself. The function needed is chdir(). For example,


changes the current working directory to ‘/home/john/temp’. And after this in the same php script,


changes the working directory to ‘/home/john/temp/0845’. It’s just like traversing the file structure under Linux.

PHP Tips & Tutorials

PHP: Delete File / Erase File / Remove File

As long as the owner of the php script has the necessary privilege to delete a file, the php script has the ability to delete it.

To delete a file with PHP, use the unlink() function:

unlink('tmpfile.txt') or die('Unable to delete the file');

It returns true if the deletion is successful and false otherwise.