Connect with us

Writing a PHP command line script that takes options

coding

Writing a PHP command line script that takes options

First of all, we make our file start like this.

#!/usr/bin/env php

This allows us to run the script without prefixing it with the “php” command, and instead we can run it like this:

chmod +x myscript  # This gives execution permissions to the script, do it only once

./myscript --first=option --second --third=option

If we want our script to take options like in the example above, we can use this snippet:

$options = array();

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;

}

The $options array will hold the supplied options. You can then use them like this:

if (!isset($options['somevalue']))

// show an error

if (isset($options['dosomething']))

 // do something

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in coding

About Me:

Szabi Kisded

Hey there, I'm Szabi. At 30 years old, I quit my IT job and started my own business and became a full time WordPress plugin developer, blogger and stay-at-home dad. Here I'm documenting my journey earning an online (semi)passive income. Read more

Sign up for my newsletter and get the YouTube Caption Scraper WordPress plugin for free
(worth 29$)!

All My Plugins In A Bundle:

My AutoBlogging Plugins:

My Online Courses:

A Theme I Recommend:

Featured Posts:

To Top