3

I'm trying to execute a linux command in PHP, here is my sample code:

$command = "last -F";
$o = shell_exec($command);
print_r($o);

Most of the Linux commands gives me an output, but for the Last -F command, I have no output. Why is it so?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
cocoboy
  • 274
  • 1
  • 3
  • 6
  • 1
    Are you sure you have the right permissions? – Mohammad Tomaraei May 13 '14 at 05:24
  • Most likely a permission issue. This works fine for me. – Amal Murali May 13 '14 at 05:27
  • how do you change the permission to have PHP Script execute the command? – cocoboy May 14 '14 at 11:33
  • Well it depends on how you executing your script. If it's CLI, then it uses a user which is executing this command (so this user should have appropriate permissions). If you're executing this script from the web browser, then it's most likely user called www-data. You should give appropriate permissions to this user then. – nikita2206 May 14 '14 at 19:24

2 Answers2

0

Try This Explaination. Your issue MAY be that the last line of last -F is a new-line. shell_exec() only returns the last line of the command, and therefore, if that line is empty, you get nothing, nada.

As an alternative, try exec(), this will allow you to capture the return value (success or failure of execution) as well as the entirety of the command's output. Check it out here

Mike
  • 1,968
  • 18
  • 35
0

You are executing that command as web user (nobody or www-data), which is a limited privileged user.You have to execute that command as root. Unfortunately giving sudo permission or full permission to web user is really a bad idea. So I recommend make a cron or background script that execute last -F and write output to a file. You can read that file from your PHP script.

You can make a script runs in background like this.

   #!/bin/bash

    while [ true ]; do
         last -F > /tmp/myfile
    done

save the code as mycron.sh

chmod +x mycron.sh
mycron.sh &

Read the file /tmp/myfile from your PHP Program. It will give the exact output of that command.

Harikrishnan
  • 9,688
  • 11
  • 84
  • 127