Question

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?

Was it helpful?

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.

OTHER TIPS

OK, I may have found a way that allows the Apple script to be called from PHP from within a browser.

It is not fully satisfactory but this is what I'm going to do:

So basically instead of using the default macOS apache server, I use this one that sets up a web server & also MySQL: http://www.mamp.info/en/index.html

I mention MAMP but there may be other.

my Apple script is finally run fully using that solution.

I had the same trouble and realised that apache executes as user www. You can change this by editing etc/apache2/httpd.conf . Change user to your user short name and group to staff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top