Sunday, January 13th, 2008

Execute Linux commands in PHP by using backticks

You can execute linux commands within a php script - all you have to do is put the command line in backticks (`).

Recently, I had to upload an archive to a server which did not allow ssh. For files that I need to transfer, I just package them up in a neat archive and transfer the archive file via scp. Not having ssh access however, I uploaded the archive file via ftp and created a script which extracts the file the file looks like the following:

<?php
#extractarchive.php
echo `tar -xvfz somearchive.tar.gz`;
?>
 

Upon loading up “extractarchive.php”, I can see the output of the tar command through the browser. I did this by using the echo function on the backticked command line - this is not necessary for the backticked command to be executed by php.

Of course, the PHP file will need to have the necessary permissions to execute commands and as always, proceed with caution. I myself do not like doing things this way, I’ve used it in the past as a last resort. But if you ever need to do something like this, at least you know that this can be done with PHP.

» Filed under General Notes by rvdavid at 1:29.

back to top

3 comments
to Execute Linux commands in PHP by using backticks

  1. on Tuesday, August 5th, 2008 at 3:59 am:

    You can also execute commands using exec(), system() and popen().

  2. Robert

    on Friday, August 15th, 2008 at 2:53 am:

    OK, and the sintaxis to pass variables to the linux shell? exec(’tar -xzvf $anyfile’); does not seem to work

  3. on Friday, August 15th, 2008 at 4:05 pm:

    hmmm that seems odd, it should work, but well some servers I’ve come accross have disabled such php features. Maybe that’s the problem.

    for example, the following excerpt produced some output for me.

    – code

    <?php
    $cmd = 'ls -la'; // the linux command
    $files = array(); // init the output array
    exec($cmd, $files); // execute the linux command and put the output in output array

    // dump the output
    echo '<pre>';
    print_r($files);
    echo '</pre>';

    Anyway, check out the php manual site for more info on exec, perhaps they’ll have some more information for you. :)
    http://au2.php.net/manual/en/function.exec.php

Subscribe to comments or TrackBack to Execute Linux commands in PHP by using backticks

Leave a comment





Credits:

© rvdavid blogs: Web Development | Powered by WP 2.3.1

Tree theme modified based on headsetoptions