Since PHP only has a way to convert a real binary string into hex, couldn't I find a function that can convert binary information written in ascii (like 0110). This function will convert that
<?
function asciibin2hex($str) {
$str = str_replace(" ", "", $str); //delete some probably spaces
//Binary to HEX list
$binary['0000'] = "0";
$binary['0001'] = "1";
$binary['0010'] = "2";
$binary['0011'] = "3";
$binary['0100'] = "4";
$binary['0101'] = "5";
$binary['0110'] = "6";
$binary['0111'] = "7";
$binary['1000'] = "8";
$binary['1001'] = "9";
$binary['1010'] = "a";
$binary['1011'] = "b";
$binary['1100'] = "c";
$binary['1101'] = "d";
$binary['1110'] = "e";
$binary['1111'] = "f";
//make sets of 4
for( ; ; ) {
$calc = strlen($str) / 4;
if(is_numeric($calc)&&(intval($calc)==floatval($calc))) {
break;
}
else {
$str .= 0;
}
}
//translate binary to hex
for($i = 0 ; $i < strlen($str) ; $i = $i + 4) {
$set = substr($str, $i, 4);
$inhex .= $binary[$set];
}
return $inhex;
}
//Examples:
echo asciibin2hex("101101011100"); //prints: b5c
echo asciibin2hex("1011 1000 1111 1100") //prints: b8fc
echo asciibin2hex("1000 1011 1101 001") //prints: 8bd2
?>
I hope I didn't make it too hard for myself writing this all, but hé, it works :)
Sunday, September 23, 2007
POSTED BY
Oriol
AT
3:26 PM
Money Format
<?php
$number = 1234.56;
// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// L. 1.234,56
// Using a negative number
$number = -1234.5672;
// US national format, using () for negative numbers
// and 10 digits for left precision
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($ 1,234.57)
// Similar format as above, adding the use of 2 digits of right
// precision and '*' as a fill character
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)
// Let's justify to the left, with 14 positions of width, 8 digits of
// left precision, 2 of right precision, withouth grouping character
// and using the international format for the de_DE locale.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// DEM 1234,56****
// Let's add some blurb before and after the conversion specification
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is GBP 1,234.56 (after a 10% discount)
?>
POSTED BY
Oriol
AT
3:25 PM
Wednesday, September 5, 2007
Integration of Spry and PHP/MySQL
Adobe have recently released its Spry Ajax framework for public beta-test by developers and I've been playing with this baby for a while. And here's some kind of report of what I have learned.
Spry is Adobe's Ajax library for manipulating XML data. It has some very unique and pretty useful functions like regions handling, related auto-updating data and stuff like that. For example, you can load XML file into your HTML document, created a template-like markup for with some spry: tags in it, and Spry will do the rest - will read the XML file and output it into your web-page in the format you have defined. Not only that. You can have several connected data sets so that when you select a row in the main table generated by Spry, and if you have a region on your web-page which is somehow depends on selected row in main table, this region will be updated automatically.
Not only that - you can also sort data by any column which is really-really useful. Spry will take care of details for you. Well that's kind of a short description of the library.
You really will be better with a description of the technology if you just visit Spry's site as I'm not the best teacher in the world.Anyways, when you want to use Spry to output some data from XML into your web-page, you need that XML file. And if you do programming using PHP and MySQL - you will get data for your tables in format of MySQL result which is far from XML. Below you will find a pretty basic function for converting MySQL result into XML file. A simple description will follow.
function createXML_fromSQLResult(&$result, $containerName="container", $elementName="element", $encoding="Shift_JIS")
{
//this functions creates XML output from the SQL result.
$xml = <<<EOF
<?xml version="1.0" encoding="{$encoding}" ?>
<{$containerName}>
EOF;
while ($stuff = mysql_fetch_assoc($result)) {
$xml .= "<{$elementName} id=\"{$stuff[id]}\">";
foreach($stuff as $key=>$value) {
$value = htmlspecialchars($value);
$xml .= <<<EOF
<{$key}>{$value}</{$key}>\n
EOF;
}
$xml .= "</{$elementName}>\n";
}
$xml .= <<<EOF
</{$containerName}>
EOF;
return $xml;
}
The function will take <strong>mysql_query</strong>'s result as input parameter, and will convert the result into XML file in the following format:
<?xml …… ?>
<containerName>
<element id=…>
<resultFieldName_1>resulttFieldValue_1</resultFieldName_1>
…….
<resultFieldName_n>resulttFieldValue_n</resultFieldName_n>
</element>
</containerName>
so for example if you have a table consisting of the following data:
table name: <b>people</b>
———–
id name place
———–
1 mike japan
2 alex russia
3 john usa
after you execute the following PHP code:
$qstring = "select * from people";
$result = mysql_query($qstring);
echo createXML_fromSQLResult($result);
you will get the following XML code generated for you:
<?xml version="1.0" encoding="Shift_JIS" ?>
<container>
<element id="1">
<id>1</id>
<name>mike</name>
<place>japan</place>
</element>
<element id="2">
<id>2</id>
<name>alex</name>
<place>russia</place>
</element>
<element id="3">
<id>3</id>
<name>john</name>
<place>usa</place>
</element>
<container>
This is a proper XML data ready to be used with Spry! So, assuming you have already went to Adobe's site and downloaded the Spry library, I will proceed to the real integration of Spry into your web page.
First, you need to include required Spry libraries.
<script type="text/javascript" xsrc="includes/xpath.js"></script>
<script type="text/javascript" xsrc="includes/SpryData.js"></script>
You need also define data for Spry to use. This will be a data from any table you like (just for testing!). And since this is a test, I put code to generate XML and HTML into single file. So once there's a trigger with action="gen" the page will generate XML data and finish. If not, just the HTML code will be output to a browser.
Here's how you define data for use in Spry:
<script type="text/javascript">
var dsTest = new Spry.Data.XMLDataSet("sprytest.html?action=gen", "container/element");
</script>
For Spry to output anything, you will need some special markup on your page. Here's a snippet:
<div spry:region="dsTest">
<table border="1">
<tr spry:repeat="dsTest">
<td>{@id}</td>
<td>{name}</td>
<td>{place}</td>
</tr>
</table>
</div>
This code tells Spry that we have a region on our HTML page which uses data from dataset dsTest (that is: the spry:region tag). And it also tells Spry that we want to use the block <tr></tr> as a template to output data from dsTest dataset. That is, the <tr> block will be output the times of number of lines you have in the dataset (that's why the tag name is spry:repeat).You can as well apply the spry:repeat tag to almost any block element in HTML (but there are elements you can not use - more info in Adobe's manual).
Well basically that' all you need to generate a table with data from an SQL query. But remember I was telling about that you can for example sort data in the table without any effort? Here's how.
First, we output id field which is actually a number so we need to tell Spry that we want that column elements to be sorted as numbers. You just need to modify Spry data definition in the following way:
<script type="text/javascript">
var dsTest = new Spry.Data.XMLDataSet("sprytest.html?action=gen", "container/element");
dsTest.setColumnType("id", "number");
</script>
And to keep things simple, you just define 3 buttons which tell Spry to sort collumns you have defined. There buttons could look like that:
<input type="button" value="sort id" onclick="dsTest.sort('id','toggle')"">
<input type="button" value="sort title" onclick="dsTest.sort('title','toggle')"">
<input type="button" value="sort content" onclick="dsTest.sort('content','toggle')"">
Well NOW it's over finally. And here's the full HTML code:
<?
require_once(getenv("DOCUMENT_ROOT")."/engine/utils.php"); //just some utils I useif ($_REQUEST["action"]=="gen") {
$qstring = "select * from people";
$result = queryDB($qstring); //my own query function. you can just use mysq_query
$xml = createXML_fromSQLResult($result);
header("Content-type: text/xml");
echo $xml;
exit;
}function createXML_fromSQLResult(&$result, $containerName="container", $elementName="element", $encoding="Shift_JIS")
{
//this functions creates XML output from the SQL result.
$xml = <<<EOF
<?xml version="1.0" encoding="{$encoding}" ?>
<{$containerName}>
EOF;
while ($stuff = mysql_fetch_assoc($result)) {$xml .= "<{$elementName} id=\"{$stuff[id]}\">";
foreach($stuff as $key=>$value) {
$value = htmlspecialchars($value);
$xml .= <<<EOF
<{$key}>{$value}</{$key}>\n
EOF;
}
$xml .= "</{$elementName}>\n";
}$xml .= <<<EOF
</{$containerName}>
EOF;return $xml;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=shift_jis"><script type="text/javascript" xsrc="includes/xpath.js"></script>
<script type="text/javascript" xsrc="includes/SpryData.js"></script>
<script type="text/javascript">
var dsTest = new Spry.Data.XMLDataSet("sprytest.html?action=gen", "container/element");
dsTest.setColumnType("id", "number");
</script></head>
<body>
testing stuff
<hr><input type="button" value="sort id" onclick="dsTest.sort('id','toggle')"">
<input type="button" value="sort title" onclick="dsTest.sort('title','toggle')"">
<input type="button" value="sort content" onclick="dsTest.sort('content','toggle')""><div spry:region="dsTest">
<table border="1">
<tr spry:repeat="dsTest">
<td>{@id}</td>
<td>{name}</td>
<td>{place}</td>
</tr>
</table>
</div></body>
</html>
One this you should have noticed is that I actually have changed the document content-type when outputting XML to browser (header("Content-type: text/xml");). Also, as this is the functionality I actually use, the default encoding is Shift_JIS as I work in Japanese environment. You should set your own encoding.
POSTED BY
Oriol
AT
6:42 AM
Tuesday, September 4, 2007
Connect to Mysql
<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
POSTED BY
Oriol
AT
9:23 PM
Monday, September 3, 2007
History of PHP
PHP/FI
PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to » release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code.
PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent.
By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project.
PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.
PHP 3
PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI's existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted.
One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax.
The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor.
By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet.
PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.
PHP 4
By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.
The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.
Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet.
PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.
PHP 5
PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.
POSTED BY
Oriol
AT
11:04 AM