Archive for the ‘PHP’ category

How to use Google Charts API in your Secure, HTTPS webpage

November 9th, 2009

So you love Google Charts API and want to spice up your app with lots of pretty bar charts, Venn diagrams, Google-o-meters and 2D bar codes (QR Codes) – only problem is, you require that users connect to your site using a secure connection (https://yoursite.com/whatever). Well, as you are probably aware, the Google Charts API doesn’t ex

actly support SSL connections… directly.

Have no fear! If you are willing to give up a little bit of your own bandwidth, you can work around this problem. We are going to do this using a simple PHP script and if you want to get really fancy, Memcached to keep the redundant API calls to a minimum.

Let’s get started.
» Read more: How to use Google Charts API in your Secure, HTTPS webpage

PHP Object Get/Set Generator

April 17th, 2009

Well, I know I haven’t created anything new here – but as Frank said, “I did it my way!”

I recently found myself creating more and more objects to store data within apps. I’m not going to get into all the ins and outs of why this is good practice, but it lead me to whipping up this simple script. I had seen a few other similar tools on the inter-webs but none of them worked quite like I needed.

If you’e not familiar with the OO approach for storing data within a script (is there a better way to describe this?) here the gist.

Say you are storing user profile information in your favorite RDBMS. You have a user profile page and will pull data for a specific profile to use in that page. Well, instead of just doing a fetch and grabbing data – creating a bunch of variables, etc., you can take the OO approach. Load all those vars into an object, with nice features like getters and setters – which may manipulate the data, etc. Then you have a clean interface to the data.

My IDE doesn’t have any wizards for this stuff (I think Eclipse can – or has plugins that can) and it can be a bit time consuming to do. Also – its very repetitive to get your basic class structure together. SO – why not write a little script to do this! Like I said, I have seen some others out there that were apparently written for PHP4 or just didn’t format the methods like I prefer.

Check it out and let me know what you think.
http://webguru.org/getset

The resulting class allows you to do stuff like this:

<?php

// create an array of basic user data
$data = array();
$data["user_id"] = 3;
$data["name"] = "Brian Bell";
$data["email"] = "brian@example.com";

$user = new UserDataObj( $data );
echo "User {$user->get_name()} has an id of {$user->get_id()} and an email address of {$user->get_email()}. ";

/*
  You can also instantiate the object with no argument,
  and set things manually
*/
$user = new UserDataObj();
$user->set_name("Brian Bell");
$user->set_email("brian@example.com");

// also comes in handy to pass the data object to your CrUD methods
$new = new Users();
/*
  pass in the data object from above so
  the create_user() method has everything it needs.
*/
$new->create_user( $user );

?>

Let me know if you have any comments or suggestions. I don’t have a lot of time to contribute to it – but I can easily see how it could be extended to give the user some options on formatting, etc.

Memory-tight, multi-threaded PHP Daemon

November 17th, 2008

Came across this nifty project on Google Code. It’s a multi-threaded, object-oriented PHP daemon which is very nicely written and easy to use.

http://code.google.com/p/phpmultithreadeddaemon/

Here’s their example of how to implement it. Everything needed to run the daemon is in the single included file “class.MTDaemon.php” – cool!


<?php

error_reporting(E_ALL);

require_once(include/class.MTDaemon.php);

class MTTest extends MTDaemon {

public function getNext($slot)
{
$this->lock();
$num = $this->getVar("num");
if ($num == null) $num = 1;
if ($num > 100) {
$this->unlock();
return null;
}
$this->unlock();

$rand = rand(0, 5);
echo "Next for slot " . $slot . " : " . $rand . "\n";
if ($rand == 0) return null;
else return $rand;
}

public function run($next, $slot)
{
$rand = rand(3, 10);
$this->lock();
$num = $this->getVar("num");
$this->setVar("num", $this->getVar("num") + 1);
$this->unlock();
echo "## Iteration #" . number_format($num) . " in " . $rand . "sec" . "\n";

sleep($rand);
return 0;
}

}

$mttest = new MTTest(2);
$mttest->handle();

?>

How to use PHP’s sprintf() on a MySQL query utilizing DATE_FORMAT()

August 2nd, 2008

It is good practice (common sense?) to filter your SQL queries.  One way to accomplish this in PHP is to utilize a function like sprintf() which will format a given string and integrate values into the string using conversion specifications which are passed in as arguments to the function.  In plain english, that means you can call the function, pass in a value and require that value to be a integer, for example.  If the value you passed in is a string, roughly speaking, it will sanitize your output.

An example in a MySQL query would be this.

<?php
// build our sql string.
$sql = "SELECT * FROM table WHERE field=%d";
$sqlf = sprintf( $sql, $somevalue );
$db->query($sqlf);
?>

As you can see, you can designate where the substitution will take place in the $sql string. That’s easy. But what happens if you need to use MySQL’s DATE_FORMAT() function? It requires that you pass in arguments to define its output (ie. Day as a word, day as a date, month as a number, etc).

<?php
// build our sql string.
$sql = "SELECT DATE_FORMAT( %b %M %d %Y, some_date_field ) as myDate FROM table WHERE field=%d";
$sqlf = sprintf( $sql, $somevalue );
$db->query($sqlf);
?>

This will fail. sprintf() will complain because you haven’t passed in enough arguments. It is expecting 5 values as part of the call, instead of just the one that you are trying to replace (in the SQL WHERE clause).

So what’s the solution? You have to “comment-out” the % that aren’t part of your sprintf() substitution. You can do this by putting another % in front of the ‘%’ symbols in the DATE_FORMAT() function. This deems them as a literal percent-sign instead of the start of another sprintf() “variable”.

<?php
// build our sql string.
$sql = "SELECT DATE_FORMAT( %%b %%M %%d %%Y, some_date_field ) as myDate FROM table WHERE field=%d";
$sqlf = sprintf( $sql, $somevalue );
$db->query($sqlf);

Hope that helps!

I may need protection from myself…

August 1st, 2008

Today, I spent almost an hour staring at this line of code:
if ($this->dbi->affectedRows>0) {

Oh – and it would be helpful for you to know that affectedRows is a method in a database class.

A method, that’s right.  Unfortunately for me, method is not spelled, v-a-r-i-a-b-l-e.

Amazing what two little ( ) can do to your stress level.
if ($this->dbi->affectedRows()>0) {

Trouble with PHP regular expression; REG_ERANGE error

November 29th, 2007

I had a situation where I needed to validate an email address that included an apostrophe. It is not widely known that the apostrophe (and a bunch of other symbols for that matter) are valid characters in the official RFC2822 specification for email address formats.

Anyway, I kept getting an error when I tried to add the apostrophe to my character classes in my regex. It gave me a strange error referencing REG_ERANGE. After some googling, I came across this blog post which led me to the answer. The problem is related to the placement of the dash (”-”) character in the regex.

Example 1:

if (ereg("[^a-zA-Z0-9_-.]", $userid)) {
    echo 'bad';
}
else {
    echo 'good';
}

The problem? The dash, or hyphen, being before the period. It thinks it’s a range, like you see in a-z. This may not be a bug, per se, but it’s certainly not smart enough for me.

The solution? Simply put the dash at the end of the regex.

Example 2:

if (ereg("[^a-zA-Z0-9_.-]", $userid)) {
    echo 'bad';
}
else {
    echo 'good';
}

Why I switched to a new IDE for PHP development

November 27th, 2007

I’ve been using Dreamweaver for about 10 years in some form or fashion. It actually started when I purchased Allaire HomeSite 3.0 in 1997. Macromedia purchased Allaire in 2001 and eventually merged HomeSite with their Dreamweaver product. Dreamweaver 8 is what I’ve been using for the past 2 years; that is, until I found PHP nirvana!

I have tried other IDE’s off and on for the past 5 years – trying to get more of a Visual Studio experience. I was really jealous of the code-completion and hinting features that were available in VS. Dreamweaver does ok at basic function hints for PHP, but nothing I found did a great job of combining all the site management features of Dreamweaver with the intelligent code parsing (ie. reading my classes and adding them to the code-completion hints). I’ve tried Eclipse with its PHP plug-in, UltraEdit, Zend Studio, phpDesigner and probably some others that I’m not listing.

PhpED Workspace

» Read more: Why I switched to a new IDE for PHP development