Ryan's Blog

Like Twitter, but longer

RSS

Running PHP Commandline Scripts

Apologies, two code focused posts in a row. I promise I‘ll get back to random waffle soon.

This has been annoying me tonight.

I’m working on a Moodle module for work today, creating a script that executes some feature of the module via the commandline (I’m resetting some records on a timer).

Moodle practice is to put scripts into a cli folder within your module. To get access to your moodle instance you need to “require” the config.php file from your application root.

Looking at some other scripts the standard practice is to have something like

require(dirname(dirname(dirname(__FILE__))) . '/config.php');

Here’s the problem. If your module is symlinked into your mod folder, then __FILE__ lies to you.

Say moodle is installed at /var/www/

Your module should then be at /var/www/mod/your_module_name

But you‘re smart, you keep your module separate from Moodle. You keep it in /var/projects/your_module_name and symlink it in to the mod folder, at least in your development environment. When you call dirname(__FILE__) PHP responds with /var/projects/your_module_name/cli instead of /var/www/mod/your_module_name/cli.

Ok, I can‘t use __FILE__ to find the config.php file. PHP gives me $_SERVER['PWD'] in CLI scripts, that will return the current directory. Yes! Problem solved.

Well, not quite.

It’s not inconceivable that you‘d want to run your script as the web user

sudo -u www-data php /var/www/mod/your_module_name/cli/your_cli_script.php

When you run the script using sudo the $_SERVER['PWD'] is empty!

I ended up using this (for now). It’s not portable, but it lets me get going with the actual task I have to complete.

require('/var/www/config.php');

Next time I‘ll just use ruby.