Setting PHP.INI path (or file) for PHP CLI shell scripts

Running a PHP script from the command-line, or CLI, is quite useful at times and is often used to perform some automated task, like a CRON cleanup script, to send out reminders, etc.

It’s common that these CLI scripts need some, but possibly not all, settings that are similar to the main application’s. I may, for example want to include the database configuration settings shared with the main application. So I often create a separate php.ini file for this purpose.

Running /usr/bin/php -c /my/very/special/path cronScript.php is simple enough, but what if I want to be able to create an “executable” PHP shell script? The obvious answer would be something like:

#!/usr/bin/php -c /my/very/special/path

at the top of the .php file, followed by my PHP code, right? Except that may not do what you want. I could not get the PHP interpreter to load anything in /my/very/special/path by using the above construct, even if it works from the actual command-line. After banging my head against the wall for a while, this turns out to work for these “shell scripts”:

#!/usr/bin/php -c=/my/very/special/path

Note the use of the = (equal) sign between the -c and the path (or file).

Carry on.

PHP is_numeric () fails WordPress version string check

This is, perhaps, obvious to most PHP developers. But it came somewhat as a surprise to me.

Using is_numeric () for validating a WordPress version string, such as ‘4.7’, does not seem to work very well when WordPress introduces minor releases such as ‘4.7.1’.

Since I cannot be bothered to figure out why it behaves in this (erratic, IMHO) way, I have since replaced the call to is_numeric () with a small function using a simple regular expression (regexp):

    function wpVersionStringCheck ($vs)                                                                                                 
    {                                                                                                                                   
        return (preg_match ('/^(\d+\.)+\d+$/', $vs));                                                                                   
    }

I’m sure there is a hole in there somewhere, but on the following strings at least, it gives me the desired result:

1.0 is valid
1.0. is invalid
1.0.1 is valid
1.banana.0 is invalid

Making SimpleXML truly simple using JSON in PHP

JSON_vs_XML
So using SimpleXML in PHP is possibly one of the worst hells of typecasting and data extraction procedures one can encounter, or close to it 🙂 But more the point, you don’t need to walk down that road alone, enter JSON.

In the simplest of ways, this will typically get you something useful:

    $pvar = json_decode ($xml);

 

(Where $xml is a SimpleXML-type object) This returns a “slightly easier to manage” PHP array.

If you want an associative array, do this:

    $pvar = json_decode ($xml, true);

 

To get it back to JSON, you simply use:

    $json = json_encode ($pvar).

 

You may need to handle XML data, but you don’t necessarily need to work with it in XML form inside your application. The above examples may not work fully for you if you have to deal with “foreign” files or clean the input data prior to conversion, but you get the idea.

This is, obviously, obvious to many. It’s a lifesaver for others 🙂

LinkedIn:
www.linkedin.com/pulse/making-simplexml-truly-simple-using-json-php-joaquim-homrighausen

Look inside, think outside (the box)

20150816_183520_IKEA

Doing things the same way as they have always been done isn’t necessarily a good idea. In the case of IKEA, I cannot recall the last time they did NOT include their “universal tool”. This is the first time I remember opening one of their self-assembly products and finding this type of mistake. Though in the case of IKEA, it may be that they’re just too lazy to change the production system.

You must not fear change 🙂

Bye bye NetBeans, still fails on remote projects, cannot detect source file changes

So NetBeans 7.x is out since a few months. With many new functions, new and updated plugins, a lot of bugfixes, etc. Fantastic! Go NetBeans!

And just because I’m a sucker for punishment, I open up a new PHP project, select a WordPress site where I do some plugin sandbox development, enter all the parameters NetBeans wants, and click “OK”.

And … NetBeans starts doing its normal routine of scanning the remote (via SSH) directories, asks me to confirm that I want to download some 1714 files to my local computer, and when I do (why wouldn’t I, right?), it begins its glorious work.

In the meantime, I set-up a new project using ActiveState’s Komodo 6.13 IDE, I point it to the same server and directory and click “OK”. Three seconds later, I have my project.

NetBeans you ask? Oh, it’s still downloading. My Internet connection is too slow (it’ll max out around 20 mbit/s) of course .. I should have at least 100 mbit/s, or possibly GB/s. Because if you want to do NetBeans development on remote servers and do it the “proper NetBeans way”, you STILL have to download your entire project locally.

I could live with that rather awkward way of doing things if NetBeans could only detect changes to the file(s) on the remote. As it is now, and as it has been for many years with NetBeans, it’ll simply consider itself to be the master, and overwrite whatever is on the server.

Of course I’m doing it all wrong. I should use version control, I should not expect myself to be able to use my workstation as a terminal to the server. I mean, those days are gone, right? We ARE in the MODEM ERA of Internet, where you REALLY wanted to do EVERYTHING LOCALLY due to bandwidth limitations, etc.

Oh no, wait .. this is 2011 .. everyone but your pet is connected 24/7/365.

So, I think now that NetBeans have shown (again), that they have no intention of EVER fixing this problem, I’ll just do rm -r -f and be happy. And what’s more, so will the rest of the NetBeans community, because they won’t need to listen to me whining about it 🙂

Bye Bye NetBeans.

#NetBeans #IDE #PHP #fail #SSH #remote #development

Increasing the phpMyAdmin session timeout

When phpMyAdmin is installed, the default session timeout value is too low for many users, making your phpMyAdmin session expire too soon. One could argue that a low session timeout value is a good idea from a security perspective. If you do not think this is an issue, here are a few simple steps that’ll let you change how long phpMyAdmin will keep your session(s) alive.

Open config.inc.php in the phpMyAdmin “root” directory. Look for a line that contains this: $cfg[‘LoginCookieValidity’]. Set the value to the desired number of seconds you want the session to stay alive (3600 = one hour, which is reasonable for most users). If you do not have that line in your config.inc.php file, add it like this:

$cfg[‘LoginCookieValidity’] = 3600;

Don’t forget to save the file, and then login again to phpMyAdmin. You may need to close the browser and re-open your phpMyAdmin URL.

This also assumes that the PHP session garbage collection is set-up accordingly. This can be done in a number of ways:

  • php.ini; add a line (or change an existing) that contains session.gc_maxlifetime = <seconds>
  • Apache configuration; add a line to the appropriate <Directory> block that says “php_admin_value session.gc_maxlifetime <seconds>”
  • config.inc.php (phpMyAdmin); after the previously edited line, add a line with “ini_set(‘session.gc_maxlifetime’, <seconds>);”

The <seconds> above is the same value that you set your variable to in config.inc.php at the beginning of this post, “3600” (sans quotes) in my case. (Some of these methods may or may not work on the server you’re using.)

This isn’t the only way to circumvent phpMyAdmin sessions expiring on you in the middle of that important work; you can, of course, configure phpMyAdmin to have appropriate access directly, thus allowing you to access your MySQL database(s) without entering a username and a password. You’ll find more information about this on the phpMyAdmin website.

(phpMyAdmin is, IMHO, one of the best tools ever written in its class. My only gripe is that I’d really like to have a much less bloated visual display theme as the default, but you can accomplish this yourself quite easily.)

So long Serendipity (S9Y), JoHo is converting to WordPress

Well, I guess it had to happen at some point. I’ve been running Serendipity (S9Y) for as long as I can remember “blogging”. At one point I was coding something that looked a lot like some early version of WordPress and S9Y, but I gave up on it. Since there are so many talented developers out there, I didn’t have to wait long for some nice alternatives to show up.

When WordPress 3 arrived, I decided it was time to move away from S9Y. I do a lot of WordPress-related stuff at work, and the time when I thought tinkering with “odd” bits and pieces just because I had nothing better to do has long since passed. These days I do it because I have something better to do but can’t keep my hands away 🙂

During the next few weeks, I’ll get a lot of stuff back here again, but I’d like to extend a big “THANK YOU” to this post:

Serendipity to WordPress – Post import

Application event tracker (or really simple debugging) for PHP

DISCLAIMER: There’s nothing revolutionary with what you are about to read, should you continue 🙂 This is simply something I did to avoid having to use a debugger where using a debugger wasn’t practical; and also to avoid having to emit “debug output” throughout the application. There are a number of ways to accomplish this, and many people have done it before me. What I describe here works for me. If you break it, you own all the pieces, be it thirteen or four.

The problem, that I had, was to track the progress of an application that did some heavy data processing. During the processing, a number of things could go wrong. It didn’t necessarily have to terminate the application (I don’t like the good old tits up-method of ending a PHP-script, i.e. “die (‘Error’);”), but I needed to track a number of variables and states throughout the execution of the script.

Using “echo ‘The value of x=’.$x” constructs works for really small implementations. It’s a proven “debugging” method and has been used for a long time in the history of computer programming (well, something similar to that construct anyway, considering PHP hasn’t been along for that long).

I have a base class, upon which I base all other classes. If you don’t have one, simply derive the class you want to debug from the code that follows. Also, please note, this method can be extended in a zillion (possibly more) ways. My example doesn’t quite reflect my actual implementation, but it should give you an idea of where this is going.

The class (tested with PHP 5):

[php]
class ezPHPdebug {
protected //We do this to avoid non-derived external modification
$__rBuf;//Recording buffer

function __construct ()
{
$this->rBufReset ();//Clear recording buffer
}

function __destruct ()
{ }

function rBufRecord ($s)
{
$this->__rBuf .= $s . “\n”;
}

function rBufReset ()
{
$this->__rBuf = ”;
}

function rBufRead ($forHtml)
{
if ($forHtml)
return (nl2br ($this->__rBuf));
else
return ($this->__rBuf);
}

}//ezPHPdebug
[/php]

Nothing to it, right? Alright, let’s say we create an example class that uses this “debugger”.

[php]
class myClass extends ezPHPdebug {
function __construct ()
{
parent::__construct ();
}

function __destruct ()
{
parent::__destruct ();
}

function doSomethingImportant ($x)
{
$this->rBufRecord (‘{doSomethingImportant}’);
$this->rBufRecord (‘x=’.$x);
echo ‘Hello, this is a cool function, it does nothing.’;
echo ‘Oh yes, I forgot, $x is ‘.$x.’
‘;
$this->rBufRecord (‘{/doSomethingImportant}’);
}

function doSomethingElseImportant ($x)
{
$this->rBufRecord (‘{doSomethingElseImportant}’);
$this->rBufRecord (‘x=’.$x);
echo ‘Hello, this is an uncool function, it does something.’;
echo ‘Oh yes, I forgot, $x is ‘.$x.’
‘;
$this->rBufRecord (‘{/doSomethingElseImportant}’);
}

}//myClass
[/php]

This is (obviously) a very simplified way of using the “debugger” class, but it’ll do the job for now.

Now, in the “application” or “main” script, we do something like:

[php]
$r = new myClass ();
$r->doSomethingImportant (‘This is a string’);
$r->doSomethingElseImportant (1024);
[/php]

What does this do? Nothing much .. it’ll call the two methods (in myClass), which outputs some data and that’s it. But, what if we wanted to know what happened inside the class (myClass).. well, do this:

[php]
$r = new myClass ();
$r->doSomethingImportant (‘This is a string’);
$r->doSomethingElseImportant (1024);
echo ‘TRACKER: ‘.$r->rBufRead (true);
[/php]

This will output the same thing as the first example, plus an additional debug output.

By “recording” entry and exit names, we clearly show that we’re in a function (and that we’re not).

One could add automated timestamping to this, by forcing a timestamp to be inserted each time a line is “recorded”.
Another possible extension is of course to do logging directly to a file or a database; but part of the beauty (IMHO) of the in-memory tracker is that I can output the debug output in one go, and determine when I want to see it.