Tutorials

Multiple ethernet interfaces? Don’t settle for just one.

If you’re using a server that has multiple IP’s, you may want to use a random one with each call of a script, or outbound call. Here’s how you could do that.

<?php
// use the system to provide a neat and tidy comma separated string
// explode it by those commas
$ips = explode(',',`ip -4 addr | grep -oP "(10\.98\.76\.5.)" | sort -u | tr "\\n" "," | sed 's/,$//'`);
 
// get some closure
$ip = function(&$ips) {
        return $ips[array_rand($ips)];
};
 
// create options for the web socket-to-be
$options = array(
    'socket' => array(
        // calling the closure to get a random IP address
        'bindto' => $ip().':'.rand(1234,54321),
    ),
);
 
// create the context...
$context = stream_context_create($options);
 
// ...and use it to fetch the data
// , using the context, with the options
// , containing the IP to be bound.
echo file_get_contents('http://freegeoip.net/json/', false, $context).PHP_EOL;
 
exit;
?>

Hope you find that useful.

By Mike on May 14, 2015 | PHP, Tutorials

PHP-CLi basic functions

The following functions can help you quickly get going with a CLi project.

#!/usr/bin/env php
<?php
 
// Clear the terminal screen.
// Using the passthru function to fun the local system's clear command
// returns none
function clearTerm()
{
        passthru('clear');
}
 
// Short wrapper for fwrite
// Permits easier explicit writing to STDOUT
// returns none
function toSTDOUT($string)
{
        fwrite(STDOUT,$string);
}
 
// Output with default prefix and suffix
function sendOutput($output = '> ',$NL=PHP_EOL)
{
        toSTDOUT($output.$NL);
}
 
// New exit allowing simple debugging via var_dump()
// Otherwise exits normally
// returns none
function nuExit($str=0)
{
        clearTerm();
        if(is_array($str))
        {
                var_dump($str);
                exit(0);
        }
        exit($str.PHP_EOL);
}
 
// get a trimmed string from STDIN
// returns a string
function getSTDIN()
{
        return trim(fgets(STDIN));
}
 
// get input with a prompt
// built in quit catching
// returns a string or nothing
function getInput($prompt = "> ", $silent = FALSE)
{
        if( ! $silent) { sendOutput($prompt); }
        $var = getSTDIN();
 
        if('quit' == $var) nuExit('Quit entered at prompt.');
 
        return $var;
}
 
// Check input with regex
// returns boolean
function checkMatch($needle,$haystack)
{
        if(preg_match('/^'.$needle.'$/i',$haystack)) return TRUE;
        return FALSE;
}

Now that we have those in place, something like the following is easy enough.

#!/usr/bin/env php
<?php
 
// include the functions here
include "functions.file.php";
 
clearTerm();
sendOutput('Hi there, welcome to a simple CLi functions tutorials.');
$response = getInput('Have you done this before?');
if( checkMatch('([Yy][Ee]?(?:[Ss]|[Aa])?)',$response) )
{
        nuExit('Okay, bye!');
}
else
{
        sendOutput('Welcome to PHP-CLi.');
        nuExit();
}

That’s it.

By Mike on December 18, 2014 | PHP, Tutorials
Tags: , , , ,

PHP Standard input and loops on the command line

Getting input from standard in (STDIN) is fairly simple. There are two really easy ways: fgets() and fgetc(), for a string and character, respectively.

Usage of the two is straight-forward. Both take a resource as the first argument, in our case that resource will be STDIN. Let’s try that, shall we?

#!/usr/local/bin/php
<?php
/* Start with a string */
print 'A string: ';
$astring = fgets(STDIN);
print 'A typed string: '.$astring."\n";
 
/* Now a Character */
print 'A character: ';
$achar = fgetc(STDIN);
print 'A typed character: '.$achar."\n";
 
/* Exit cleanly */
exit;

So there it is, getting input from the user of your program.
Now let’s look at the same functionality, in a looping sense. Type q to exit, or use CTRL+C.

#!/usr/local/bin/php
<?php
while(!$exit) {
        /* clear the screen, using execution operators (backticks) */
        print `clear`;
 
        /* Request input */
        print 'Type something: ';
        /* Use fgets with the STDIN resource, and throw it in a variable */
        $var = trim(fgets(STDIN));
 
        /* break if it's q, otherwise keep going
           Redundant exit strategies, make $exit == 1,
                    and thus !$exit is no longer true.
           And break; explicitly tells the while() to 
                        end without going any further. */
        if ($var == 'q') {$exit++; break;}
 
        /* print the response */
        print 'You typed: '.$var."\n";
 
        /* require at least a press of enter to continue */
         fgetc(STDIN);
}
print 'Bye'."\n";
print `sleep 2s;clear`;
exit;

So, there it is! Getting input from standard in (STDIN) with PHP, and using the STDIN in a loop. Also, these functions are great friends with trim(), sanitizing user input is a very important step when dealing with security in your programs. You could even go one step further, and use regular expressions to ensure the type of data coming in, and ensure it’s what you want and need. Hope this was helpful!

By Mike on May 8, 2013 | PHP, Tutorials