Archive for the 'PHP' Category

13th Sep 2006

drinks.jc21.com Re-Launched

Years ago I started a Cocktails directory. It grew to include a reference of alcoholic terms, and a database of drinking games. It was the most popular part of my site. I took it down because it seriously needed rewriting, but then I never quite got around to it - until lately.

The new site doesn’t have the reference or games database unfortunately. It doesn’t even have many recipes anymore (long story, bad ending). But I’m working on that, when I can. You can help with that too. It is now a work in progress, and I hope to one day have many of the features that other sites have, such as a “My Recipes” section, and “Print my Recipe Book”. One feature I’ve always wanted to write, is a recipe search based on the alcoholic supplies I have in my disposal. To accomplish that I need to have more recipes first.

So check it out sometime.

Technorati: drinks, alcohol, coktails, shooters, drink recipes

Posted in PHP | No Comments »

07th Sep 2006

How to dynamically return XML data using PHP

This is the second part of a tutorial covering the Front-end browser part of Ajax’ing and the Back-end part of sending data with PHP. The first part can be found here.

So we’ve covered how to request an interpret XML data from a webpage using Sarissa. Now we want to control what data is being returned, dynamically.

The basic principal behind setting up the script is to make the browser think it’s an XML document, not a PHP script. There are 2 ways you can do this:

  1. Add a content-type header into your script
  2. Add an apache handler to treat xml files as scripts (which still involves step 1 anyway)

So I’ll only cover the first option. On top of that, I’m going to throw you in the deep end here, and show you the entire script:

<?php
//simulate a remote connection
sleep(2);
 
//include any libraries you want to use here.
 
//get the $mode var
$mode = stripslashes($_GET['mode']);
//Set the content-type header to xml
header("Content-type: text/xml");
//echo the XML declaration
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
?>
<xmlresponse>
  <?php
  //make a decision based on $mode
  switch ($mode) {
    case 'getitems':
      //set items in a test array
      $items_array[] = array(
        'id'=>15,
        'name'=>'Finger Bun',
        'price'=>'$0.80 ea'
      );
      $items_array[] = array(
        'id'=>16,
        'name'=>'Donuts',
        'price'=>'$0.50 ea'
      );
      $items_array[] = array(
        'id'=>17,
        'name'=>'Apple Pie',
        'price'=>'$1.20 slice'
      );
      $items_array[] = array(
        'id'=>18,
        'name'=>'Double Choc Chip Cup Cakes',
        'price'=>'$1.00 ea'
      );
 
      //echo a count of items
      echo '<item_count>'.count($items_array).'</item_count>';
      //echo the array in XML style
      for ($x=0;$x<count($items_array);$x++) {
        echo '<item>';
        echo '<id>'.htmlspecialchars($items_array[$x]['id']).'</id>';
        echo '<name>'.htmlspecialchars($items_array[$x]['name']).'</name>';
        echo '<price>'.htmlspecialchars($items_array[$x]['price']).'</price>';
        echo '</item>';
      }
 
      //set a No Error response - function defined below
      SetErrorNode();
      break;
 
    default:
      //inccorrect mode, let the hacker know!
      SetErrorNode(404,'Stop hacking. Get a real job.');
      break;
  } //end switch
  ?>
</xmlresponse><?php
 
//FUNCTIONS
//this sets the error code node - essential for every xml document to be returned.
function SetErrorNode($code=0,$text='') {
  echo "<error_code>" . $code . "</error_code>\\n<error>" . htmlspecialchars($text) . "</error>";
}
?>

Download this code: _ajax.php

Here’s an explanation. First we simulate an internet connection delay (for those using local development servers) incase you’ve got any features such as a waiting screen on the front-end that you want to admire for two seconds.

Next we get the $mode variable from the GET array (as used in part one of this tutorial) so we can decide what to do with it later. Then we send the content-type headers to the browser, so that it knows this is an XML document. Then we echo the XML declaration. You might be wondering why I’ve used chr everywhere there. This is so we don’t have to turn off php short tags just to make this thing work, a tip for all you out there.

Then we echo the root tag, xmlresponse. I’m not sure if changing this will affect Sarissa’s interpretations, but I don’t change it anyway.

The rest of the script is echo’ing data for our application to use. The only thing to mention is that any data you want to send within xml tags should be coded using htmlspecialchars. Even HTML code should be coded. Sarissa will automatically convert it back for you on the front-end.

Finally, we use the function SetErrorNode to echo our error tags as we want to.

Well that’s all I’m going to cover this time around, but I’m sure this can help a lot of begginners out there. Leave a comment if you have any questions (like how to get the front-end to recognise more than 500 characters of data within a single tag, muahaha).

Technorati: php, ajax, xml, tutorial

Posted in PHP, Tutorials | 2 Comments »

09th Aug 2006

Easy PHP Debugging

Wether I’m making complex web applications or a five page no brainer site, if I’m using PHP to do something the chances are something’s not going to work out exactly to plan. I quite often find myself spitting out this bit of code to see the contents of my variables: print_r($var);

While this works very well, it can be daunting to look at without some sort of formatting. Another dilemma I’ve found (only on those big projects) is that I can’t remember where I’ve put that piece of code in order to remove or comment it out.

Today I spent a short amount of time making my life easier. I’ve created a function that works very much the same way, but unlike print_r, this function can handle any type of variable. It’s extremely simple to use. Once the function is included to your application, just call it: echo dba($var1,$var2,$var3…);

The function will handle any amount of variables you throw at it. Here’s a sample output from one of my sites:

================================================================================
Debug Called:
/home/vhosts/trade/www/sub-contractors/materials.php on Line 448
/home/vhosts/trade/www/sub-contractors.php on Line 109

================================================================================
Argument #1: String
Hello World!
End Argument #1
================================================================================
Argument #2: Integer
9316729
End Argument #2
================================================================================
Argument #3: Float
4582.55
End Argument #3
================================================================================
Argument #4: Array
(
[0]
=> foo
[1] => bar
)
End Argument #4
================================================================================
Argument #5: db_mysql Object
(
[dbname:private] => trade
[id_link:private] => Resource id #15
[eh] =>
[query_counter] => 8
)
End Argument #5
================================================================================

Notice that the first part explains the trace of pages called before this function. On the first entry and line number you’ll find this function’s call. Subsequent pages are ‘parents’ of this page.

It’s great! Where do I get it?

Technorati: php, programming

Posted in PHP | 3 Comments »

03rd Aug 2006

Custom Smarty Block Function: Loop

For those who haven’t heard of the Smarty Template Engine for PHP, it’s something you should look into. Of course, I fully agree with it’s designers who state that the system is designed for larger scale applications instead of five page websites.

One of the best features (apart from useful documentation) is the ability to include custom functions to the system. One of the features I’ve been missing is a Loop function similar to PHP’s for loop. So I’ve created one:

<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File:     block.loop.php
* Type:     block function
* Name:     loop
* Purpose:  loops over a piece of template content x amount of times
* -------------------------------------------------------------
*/
function smarty_block_loop($params, $content, &$smarty) {
  //check if the block has data
  if (is_null($content)) {
    return;
  }
  //check if the start parameter is set
  if (strlen($params['start']) == 0 || !is_numeric($params['end'])) {
    $smarty->trigger_error("assign: missing 'start' parameter or is ".
      "not a number");
    return;
  }
  //check if the end parameter is set
  if (strlen($params['end']) == 0 || !is_numeric($params['end'])) {
    $smarty->trigger_error("assign: missing 'end' parameter or is ".
      "not a number");
    return;
  }
  //check if the increment is set. If not, default is +1
  if (empty($params['increment']) || !is_numeric($params['increment'])) {
    $params['increment'] = 1;
  }
 
  //do the loop!
  $data = '';
  //check if we're incrementing or decrementing
  if ($params['end'] > $params['start']) {
    //incrementing, check $increment value is positive
    if ($params['increment'] <= 0) {
      $smarty->trigger_error("assign: increment cannot be negative or ".
        "zero when 'start' is less than 'end'");
      return;
    }
    for ($x=$params['start'];$x < $params['end'];$x=$x+$params['increment']) {
      $data .= $content;
    }
  } else {
    //decrementing, check $increment value is negative
    if ($params['increment'] <= 0) {
      $smarty->trigger_error("assign: increment cannot be positive or ".
        "zero when 'start' is greater than 'end'");
      return;
    }
    for ($x=$params['start'];$x > $params['end'];$x=$x+$params['increment']) {
      $data .= $content;
    }
  }
  //return the data
  return $data;
} //end smarty_block_loop
?>

Download this code: block.loop.php

To use this in your Smarty engine, save this file to the plugins directory. It will automatically be available to you in your scripts. Here’s an example of it’s use:

<p>Smarty loop block function example</p>
<p>Assume that $blocks is defined as 10</p>
{loop start=0 end=$blocks increment=2}
  <div>
    Hello World
  </div>
{/loop}
<p>There should be 5 divs displayed.</p>

Download this code: block.loop.example.html

The increment value is not always required. It defaults to 1 if not specified. Also, this loop code works in reverse. Specifying a start value greater than the end value will cause the loop to decrement. Although, the increment value is required in such case and must be a negative value.

Technorati: php, smarty

Posted in PHP | No Comments »

05th Jul 2006

Adding and Stripping Slashes with Arrays in PHP

How often have you ever found out that magic quotes was turned on, but you forgot all about it? Or your result from a database row is fine in its’ result set, except for the slashes?

Not too often for me either. But there are exceptions. Today, for example, I needed to stripslashes from every string in an array of strings. The normal stripslashes function just isn’t equipped to handle arrays of data.

Here’s what I’ve come up with:

<?php
function stripslashesArray($arr) {
  //check if the variable is an array
  if (is_array($arr)) {
    //get the keys of the array
    $keys = array_keys($arr);
    for ($x=0;$x<count($keys);$x++) {
      //check if array item is not an object
      if (!is_object($arr[$keys[$x]])) {
        //strip the slashes of the item, even if it's an array
        $arr[$keys[$x]] = stripslashesArray($arr[$keys[$x]]);
      }
    }
    return $arr; //return the stripped array
  } else {
    //variable is just a string, treat as normal
    return stripslashes($arr); //return the stripped string
  }
} //end stripslashesArray function
?>

Download this code: stripslashesarray.php

So you see, the function makes sure you’re not sending it an object, or an array with an object as an item. The function also calls itself again and again until all branches on the array are stripped. However, if you have an array with an object as an item, and that object has an array of strings, they won’t be stripped. I don’t see many opportunities where that would come up anyway!

Now that we’re stripping slashes, it’s just a simple modification to start adding slashes:

<?php
function addslashesArray($arr) {
  //check if the variable is an array
  if (is_array($arr)) {
    //get the keys of the array
    $keys = array_keys($arr);
    for ($x=0;$x<count($keys);$x++) {
      //check if array item is not an object
      if (!is_object($arr[$keys[$x]])) {
        //add the slashes to the item, even if it's an array
        $arr[$keys[$x]] = addslashesArray($arr[$keys[$x]]);
      }
    }
    return $arr; //return the stripped array
  } else {
    //variable is just a string, treat as normal
    return addslashes($arr); //return the stripped string
  }
} //end addslashesArray function
?>

Download this code: addslashesarray.php

The functions have more use than you’ve thought. For example, if you’ve just transferred your site to a new server, and magic quotes behave differently than before, you can use stripslashesArray or addslashesArray on your $_POST, $_REQUEST and $_GET arrays.

I hope this keeps you all sane.

Technorati: php, programming

Posted in PHP | No Comments »

12th Jun 2006

PHP Class: Paypal Button Generator

Ever tried to make a Paypal button using their Button Creator, or even by getting the information from their Help pages? It’s not easy or dynamic. I’ve made many sites that use Paypal for their payment of both single items and multi item shopping carts. I’ve created this class to make my job easier. I have not come upon something like this in my search on the internet, so I’m sharing it to the world.

This class supports:

  • CSS Styles
  • Custom IPN, Return, and Cancel pages
  • Postage, handling and tax amounts per item
  • Custom pass-through variable

NEW - Version 1.1 now supports PayPal Subscriptions!

Sites using this class:

Download

Technorati: php, paypal, ecommerce

Posted in PHP | 16 Comments »