Archive for the ‘PHP’ Category
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:
- Add a content-type header into your script
- 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).
Easy PHP Debugging
Posted in PHP on August 9th, 2006
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
Adding and Stripping Slashes with Arrays in PHP
Posted in PHP on July 5th, 2006
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
PHP Class: Paypal Button Generator
Posted in PHP on June 12th, 2006
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
- Download Version 1.1 (30-11-2005) (Zip file)
PHP Class: Image Snapshot 1.3
Posted in PHP on June 11th, 2006
Inspired by Backpackit.com’s image management, Image Snapshot can take a portion of an image (crop) to specific dimensions, from different areas of the original image.
This class has been created for the purpose of manipulating an uploaded image, and creating a Thumbnail image that does not alter the aspect ratio, and yet represents the contents of the original image. I’m sure other uses can be found for the Image Snapshot class, but I’ll leave that to you. I use it for Photo Galleries, and Shopping Cart systems.
View the manual to get a clearer picture.
This class supports:
- Jpg, Gif, Png files
- Output to Jpg
- Can resize images before applying the crop
- Can crop from any part of the image
Sites using this class:
| Change Log | |
|---|---|
| 05-12-2005 | 1.3 Release |
| 05-12-2005 | Added: ImageFile field, can now load image from saved file. |
| 05-12-2005 | Added: custom position type, specify by percentages. Read updated manual for help with this. |
| 28-11-2005 | 1.2 Release |
| 28-11-2005 | Added: ReturnedWidth and ReturnedHeight variables, for more feedback. |
| 28-11-2005 | Fixed: if crop area was bigger than original image, mixed results ocurred. |
| 28-11-2005 | 1.1 Release |
| 28-11-2005 | Added: support for Image input with a variable |
| 27-11-2005 | 1.0 Release |
Downloads
- Download Version 1.3 (05-12-2005) (Zip file)
- Download Manual (highly recommended) (Pdf file)