Archive for Php
Building charts with Php
This is pChart and I think its a very handy one and better than the tools I mentioned in last year's post.
This open source charting class has a lot more variety for more complex charts and graphs and I am just playing with it at the moment and will be making use of it on a live site soon.
The last update was a year ago now and its worthwhile to keep check the site should there be more updates.
Simple URL encoding using PHP
Let me state that this type of encoding is not meant to hide some sensitive data or as a security measure but meant to avoid showing a
casual user the IDs being used in a query string so that the user does not try to navigate the site by simply changing parameters in a
query string.
If the user really wants to know what IDs are being used I am sure it wont take them long to figure out.
So say its an application passing the driverid(id1) and teamid(id2) in a query string and I don't want to show these in the query string a
simple way to achieve that in PHP is to use base 64 encoding.
I find it useful to choose a delimiter especially when they are more than one query string parameters in the originating page.
So say you have two parameters id1 and id2 in the form http://www.mysite.com/test2.php?id1=1234&id2=5678,
coming from test1.php page, you can use:
$id = base64_encode($id1.'~'.$id2);
with the tilde(~) acting as a delimiter.
This is then used in the form:
http://www.mysite.com/test2.php?id=$id
To retrieve back the query string parameters on test2.php you use:
$queryParams = explode('~', base64_decode($_GET['id']));
$id1 = $queryParams[0];
$id2 = $queryParams[1];
I think this is the basics of it but one can add a few extra steps for example reverse the string before displaying it using the PHP
strrev function, for example:
$id = base64_encode($id1.'~'.$id2);
$id = strrev($id);
and then on test2.php use:
$id = strrev(($_GET['id']));
$params = explode('~', base64_decode($id));
$id1 = $queryParams[0];
$id2 = $queryParams[1];
I am sure there are other ways to achieve the same thing but this one simple approach that I use sometimes.
Charting and graphing with Php
I think the simplest solution is with Libchart. Libchart offers the
opportunity to do simple line and bar graphs and also pie charts.
Its good to see that the library is constantly being updated and the latest changes have been to fully support PHP 5.
Another package I had a quick look at is Image_Graph. Image_Graph has more graphs but I think its more suitable for those people who already use PEAR or who are prepared to install the PEAR package.
PHPGraphLib is another easy to use, PHP-based graphing library and it can display up to three
datasets on each graph.
Another free graphing solution is Graidle . Here the charts are generated using PHP 4.
According to its website, PHP Graph creates a simple dynamic Php bar graph from session data and that
graph can be customised.
Changing memory setting to show photos
To display photos in my photo gallery I use Php's imagecreatefromjpeg gd function because that enables me to create thumbnails on the fly and then on clicking the thumbnail I get the enlarged version which I can set to whatever size fits the page.
I realised that all the photos that were not showing were from the 7.2 Megapixel camera (a Sony W55)and all the photos from the 4.0 and 5.0 Megapixel camera's were showing. To solve the problem I had to increase the 'memory_limit' setting found in the Resource Limits section of the php.ini file.
I still don't understand why the photos showed for a little while and then suddenly stopped especially as there had been no changes to the php.ini file
End of road for PHP4
I did a little bit of PHP4.* development before jumping onto PHP5 when it was released some three years ago and I have enjoyed using PHP5 ever since. The object oriented nature of PHP5 makes it easier and more interesting to work with.
What I found interesting in the announcement was the fact that PHP6 is on the way. I am keen to see what new features will be introduced in PHP6. In particular I am hoping that it will be far much easier to do constructor overloading like in Java and C# because at the moment its not the easiest of things to do.
To achieve something like constructor overloading at the moment I have to use optional parameters in the constructors and then check those parameters in the constructor and that's not ideal.
Method/function is not a really big issue because one can easily rename the methods accordingly.
Getting first and last day of the month
So I wanted a compact way of doing this using PHP without using a function or method and show the date in format d/m/yyyy. The first day of the month is straight forward and I could have used something simple like this:
$dtFirstDay = "1/" . date("m") ."/" . date("Y") ;
This could have done it but in the end I settled for a method with similar formulations for both first day and last day and hence:
$dtFirstDay = date("j/n/Y", mktime(0, 0, 0, date("m") , date("d")-date("d")+1, date("Y")));
and for last day:
$dtLastDay = date("j/n/Y", mktime(0, 0, 0, date("m")+1 , date("d")-date("d"), date("Y")));
Creating an RSS Feed using Php and MySQL
I have a used a table called post where all the posts are stored. This is a simple table with fields postid, heading, description and timestamp where heading is effectively the title and timestamp is the time of inserting the post in the database.
The class Db is a small class that handles the database side and connects to the MySQL database through the class constructor. The GetFeedData function retrieves feed data and store the data in an array. The FormatDate function formats the date to a format which includes the GMT time difference.
The Feed Class is involved with the creation of the feed.xml file. The CreateFeed function calls three functions which create the head, the body and the footer of the RSS feed. I think putting in three functions makes it easy if you want to add exception handling around the file creation process.
The last file or class not shown will just call the CreateFeed function to start the process. The CreateFeed can be called after inserting data into the post database, say using a form to create the RSS feed.
The code and the table can be expanded upon to include other optional channel elements like copyright, image etc.
Not easy selecting PHP IDE
Two years ago when I did a similar exercise there wasn't as much choice as there is today and I think the quality of the free IDEs available has also improved tremendously.
This time I chose to go with PSPad plus Top Style Lite for the CCS bit. I chose PSPad for its broader functionality and ease of configuration and handling of projects.
One of the best IDEs that I came across though is PHPEdit from Waterproof but you have to pay for this one or you can use their 30 day trial version. The good thing about the 30 day trial version is that it counts the actual number of days its used and not the calendar number of days.
The sites I found useful include PHP Editors and also a thread on Lifehacker.
In the end I think the actual choice of IDE depends on user taste and preferences.
The issue of empty session files
I wrote two small scripts to test:
//first.php
<?php
session_start();
$_SESSION["session_test"] = "session testing";
print $_SESSION["session_test"]."<br>";
print '<a href = "second.php">Second Page</a><br>';
print session_id();
?>
If sessions are working properly then the session id should be the same in both pages and
that offers a very simple test apart from the fact that the test string should also be shown
in the second page.
The second page script looks like this:
//second.php
<?php
session_start();
print $_SESSION["session_test"]."<br>";
print session_id();
?>
On clicking the link to the second page, the second page had a different session id and the
the test string never showed but instead I got this warning : Notice: Undefined index:
session_test in C:\webroot\second.php on line 3. (after enabling all errors and warning
to show).
After hours of toiling I found out that this issue was caused by the Zone Alarm firewall. I
disabled the firewall and the sessions started working. I have looked through the firewall
log and I cant see exactly where localhost or PHPSESSID is blocked and so for now I will
temporarily disable the firewall when testing script involving sessions and if I cant find a
solution then it could be time to move to another firewall.
Getting Apache 2.2 to work with PHP 5
What I will do though is to highlight the small changes I made to make Apache 2.2 work with PHP 5.
Assuming PHP is installed in the C:/php folder normally you would add the following lines to your Apache httpd.conf file:
LoadModule php5_module "C:/php/php5apache2.dll"
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
# configure the path to php.ini
PHPIniDir "C:/php"
With Apache 2.2 I got an error on the LoadModule line. To resolve that error I had to download the latest stable release of PHP from the PHP Snapshots site. I downloaded the zip file for PHP 5.2 and this comes with the php5apache2_2.dll file.
In the Apache httpd conf file I then made changes to the LoadModule line as follows:
LoadModule php5_module "C:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
# configure the path to php.ini
PHPIniDir "C:/php"
and this solved the problem. I prefer using the PHPIniDir directive because this means I
just maintain one copy of the php.ini file in C:/php folder in this case and I don't have to
copy another one to C:/Windows for example and this works fine for me.
Check for Integer value
if (ereg("^[0-9]+$", $var)) {
return true;
}
else
{
return false;
}
This works fine and well but lately I have found myself using the next routine more and more:
if ($var == strval(intval($var))){
return true;
}
else
{
return false;
}
What I need to find out though is which one of these two is more efficient or which one has
more limitations if any.
Script timezone
Because the Php version involved is pre 5.1.* I could not just add:
date.timezone = Africa/Harare
for example to the php.ini file and make all scripts use that timezone as default.
Neither could I use:
date_default_timezone_set('Africa/Harare');
and so the easiest option for me was to use:
putenv('TZ=Africa/Harare');
I just had to make sure that I put this statement in an include file that was available throughout the whole site (or the particular pages that required date and time). This was all good and fine until I
realised that the timestamp recorded in the MySql table was that for the server and not the one for the set timezone. I traced this to the insert query which was using something like this:
..."name = '$strName',timestamp = now(),"...
It realised that the time taken for the 'timestamp = now()' statement was for the MySql server time which is not affected by the the "putenv" command and therefore I changed the above to something like
$timestamp = date('Y-m-d H:i:s');
.."name = '$strName',timestamp = '$timestamp',"...
Now the date function gives the date and time from the timezone as set out in the "putenv" command.
Validating textboxes/combos
function ValidateField($strField,$strEntry, $intMin, $intMax){
if(trim($strEntry)=='' || strlen(trim($strEntry)) <$intMin || strlen(trim($strEntry))
> $intMax) {
echo "Please enter a $strField between $intMin and $intMax characters" ;
}
return true;
}
So say for a product textbox with a minimum length of 2 and maximum of 20 characters, I would validate like this:
ValidateField("Product",$strProduct, 2,20);
and then go on to the next one say product code:
ValidateField("Product Code",$strProductCode, 3,4);
and so on.