Create your own command line PHP executables

This is remarkably simple! You’ve seen shell scripts that start with #!/bin/bash ? Well check this!
Create a file, call it anything, no need for php extension!

#!/usr/bin/env php
<?php
      echo "Easy as that!\n";

Then make it executable:

chmod +x myfile

Then you can run it with ./myfile ! Not hard at all! Now you can also pass arguments like so:

./myfile --option1=value1 --option2

With or without values. To do this, we add the following:

foreach ($argv as $arg)
{
    preg_match('/\-\-(\w*)\=?(.+)?/', $arg, $value);
    if ($value && isset($value[1]) && $value[1])
    {
       $options[$value[1]] = isset($value[2]) ? $value[2] : null;
    }
}

Now you have access to $options[‘youroption’]; Have fun and play around with it!

Advertisements

One thought on “Create your own command line PHP executables

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s