Search code examples
phpapacheexecosascript

PHP exec and OSASCRIPT?


I have a little Apple script as follow:

beep
delay 2
tell application "Finder" to activate

It just makes a sound, wait 2 second and then bring the "Finder" window to the foreground.

When I run it from the command line, it works fine.

Then I want PHP to call that script using the exec() php function.

<?
$cmd = "/usr/bin/osascript \"myscript.scpt\"";
exec($cmd);
?>

It still works fine.

But when I call that same PHP script from the browser, it doesn't work! The PHP starts, the Apple script starts as well since I can hear the beep sound but its last line is not executed.

I thought that would be an environment variable thing so I made sure they were all the same way as in the terminal:

$cmd = "HOME='/Users/mikael' && … && /usr/bin/osascript \"myscript.scpt\"";

The variables are set properly (as check with env|sort) but still no luck with running my apple script inside a php script displayed in the browser and using the standard MacOS apache stuff.

Any idea?


Solution

  • When osascript runs from PHP, through the web server, it's not running with a login context, so it can't send Apple events to applications running on the desktop (like the Finder). You'll find that a similar issue arises if you try to use osascript over SSH.

    Login contexts are a complex, poorly documented area of OS X. You may want to get your hands on a copy of Amit Singh's Mac OS X Internals: A Systems Approach if you want to learn more about them.

    If you don't, though, the answer is generally pretty simple: don't depend on osascript working correctly from the web server.