skip to Main Content

By Using backtics i can execute some command in the running machine like this –

<?php
      echo `cd ~ && ls -al`
?>

Running this code in the CLI mode ( php index.php ) shows me the output as it should be displaying but how can i print the same thing in a HTML page.

do i have to enable something on php.ini ?? or else ??

I also tried this but doesn’t seems working on the Browser


<?php
    echo shell_exec("cd ~ && ls -la")
?>

Its Working on the CLI mode but not on the Browser

Here is CLI mode output for the above script
enter image description here

2

Answers


  1. You can use a function to execute a command https://www.php.net/manual/fr/function.shell-exec.php

    It will return the output of the command, and null if an error occurred or if the command return nothing

    When you run a script from a web server, you inherit the user that run the web server permissions. Usually www-data for apache2. If you try to run a command without right permissions, shell_exec will return null.

    You can try to use exec() if you want to see errors https://www.php.net/manual/en/function.exec.php

    exec('ls',$output);
    var_dump($output);
    

    Becareful, you should first invoke bash

     shell_exec('/bin/bash -c "cd ~ && ls -la"')
    
    Login or Signup to reply.
  2. Try like this

    $output = shell_exec( 'ls -l /abc_directory' );
    var_dump ( $output );
    

    It will depend on permission.For example, if your web server user like apache uses www-data has permission to access that particular directory like /abc_directory then you will see the output of the command, else nothing will be shown in the output.

    In your screenshot When you are running on the cli using php command, you are running php as user ace ( I assume), but in browser it will be executed as web-server user www-data (apache) .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search