Monday, April 14, 2008
Multiple Language Welcome PHP Script
If you would like to welcome visitors to your own website, by directing visitors based on their prefered language, this is how I do it.
The technology is PHP, which is a simple language that adds a level of capability and dynamic that you can't have with Javascript and HTML. Obviously you need access to PHP. Most hosts do provide it.. but this is one step beyond Geocities. If your host doesn't offer PHP.. maybe get one that does - it's not expensive.
The script below simply redirects incoming requests to pages associated with the first two letters of the code in the language preference of the visitors browser settings.
The two files you need are index.txt and fish-config.txt
Download these text files by right-clicking the links and choosing save-as. Rename the first 'index.html' and the second 'fish-config.php'.
The index.html is the root index file you'll likely recognise. This doesn't actually do any more than redirect requests to files listed in the config file. fish-config.php is a file that index includes when it is run. i.e. you need PHP includes enabled, and to put this file in the PHP includes folder.
The script is an improved version of one I found on the net years ago. It has better security and handles more variety of input from browsers language preference.. stripping the dialects to find the core language.. it can also now handle upto 100 languages. Don't try changing it unless you are confident in PHP, you can open holes in security with badly coded PHP.
Four things to do..
1. fish-config.php - add lines to as needed but adjust the $count variable, keeping it one above the last array record number.
2. fish-config.php & index.html - change the http://www.example.com/ to reflect your own site.
3. index.html - Change line 40 $redirect = 'babel/index.html'; to suggest the location of a default file.. for when someone doesn't have a language preference in the get request.
4. index.html - Change line 35 $redirect = 'error/bad-request.html'; to suggest the location of your error file for HTTP code 400 Bad Request
That's about it..
You can find the codes for languages on The ISO639-1 language code list
Good luck.. any problems let me know.
Wednesday, April 9, 2008
The PNG problem in Windows Internet Explorer
This site is all about a JavaScript-based PNG fix for Internet Explorer 5.5 and 6 on Windows. The fix allows IE to properly render PNG alpha transparency. If you want to get straight to the script, go to the how-to page and follow the instructions there. If you have the time for a description and demo of the problem, then read on...
Why only versions 5.5 & 6? Because Windows IE versions prior to 5.5 do not support the filter which fixes the PNG problem, and version 7 (not yet released at the time of writing in January 2006) is reported to have fixed the issue entirely.
The code can be used either by a one-time copy-and-paste or as an include file. The entire thing is completely ignored by all other browsers - in fact it is treated as an HTML comment - thanks to IE's conditional comments. This solution is therefore light, portable and non-invasive to other browsers.
Already use the script? You can check the change log for details of what's new. Please feel free to use or amend this routine you as see fit.
March 2008: This script has been up for over 4 years now but I'm afraid I haven't the time to update it. I will leave it here for those who still can use it, but there may be better solutions around these days, such as Drew McLellans. I'm very sorry but I can no longer respond to any email about it - I just don't have the time. There is no official licence of any kind on this - it's simply freeware. Use it or change it as you wish.
Consider a standard GIF image with the halo problem. GIFs only allow one colour for background transparency, so a GIF placed over the intersection of another colour looks ghastly:


Drag me around the page!
Compare the above GIF to the same image below saved as a PNG. On modern browsers (Firefox, Opera etc), the halo problem is solved - but not in Windows Internet Explorer prior to version 7. IE 6 and under render the image with an ugly background which looks even worse than the GIF halo.

Finally, here is the same PNG right-aligned to this paragraph using the very common (deprecated) img align="right" construct. The PNG can be positioned in the same way as JPGs or GIFs, but the transparency issue remains a problem.
The GIF with the halo is still here, but the PNGs should now be working in IE versions 5.5 and 6. The only difference between this page and the previous one is a chunk of JavaScript.


Drag me around the page!
Compare the above GIF to the same image below saved as a PNG. The transparency should now be working in IE. Try dragging the car image around the screen and notice how it is "see-through".

Finally, here is the same PNG right-aligned to this paragraph using the very common (deprecated) img align="right" construct. The PNG can be positioned in the same way as JPGs or GIFs, and the transparency issue is now fixed.
The JS code can be seen if you do a "View Source" on the Solution page. There are two ways to use it - simple copy & paste or the JS include file method. Note that you must have height and width attributes specified for each image. Other attributes (class, alt, title & style) are optional so far as this routine is concerned, but are respected if specified.
There is also an imagemap version if you want to use imagemaps and/or form input images and a rollover version which enables the use of transparent PNGs in rollovers.
Method 1: Copy & Paste
For single page or occasional usage, copy the JS code in its entirety (from ) and paste it into your page somewhere in the the section. That's it.
Method 2: (recommended) JS Include File
If you wish to use the code on multiples of pages, you may prefer to use a JS include file. First, download the JS file here: pngfix.js. Place the file in your webpage directory, then add the following construct on each of your pages somewhere in the section:
Note the use of the defer keyword. This trick causes the images to be replaced before they are rendered. Earlier versions of this script did not use this method, occasionally resulting in an unpleasant screen flicker as the PNGs were being filtered. The code in the include file is slightly different from the copy and paste code referred to above, so I recommend downloading my file rather than making your own.
Here is a demo page using the Include file method. This method is arguably better for use with multiples of pages, as it only requires three lines of code per page. The JS file is only 2KB in size and will be cached after the first download. It will therefore incur no further download overhead on subsequent pages. The download time should be around 0.3 seconds on an average 48kbps dial-up modem connection.
Monday, March 24, 2008
PHP Coding Tips - Strings
PHP Code:
// OK
echo $row[$key];
// Wrong, unless key is a constant
echo $row[key];
// Right
echo $row['key'];
// OK, since it's in a string
echo "Text: $row[key]";
3) Remember, you can break out of PHP mode for large sections of HTML. This is faster than echo'ing and you don't need to escape quotes.
-------------------------------------------------------------------------------------------------
Personally I avoid any code that looks like this:
PHP Code:
$something = 'this';
$something .= 'and this';
$something .= 'and this';
$something .= 'and this';
$something .= 'and this';
or this:
PHP Code:
$something = 'this'
. 'and this'
. 'and this'
. 'and this'
. 'and this'
. 'and this'
. 'and this';
I much prefer the following:
PHP Code:
$something = 'this
and this
and this
and this';
Why? Because in the first two examples PHP is having to allocate memory for multiple strings and then go through the (relatively) expensive process of "sticking" them together again. If you just declare a string over multiple lines you are avoiding that overhead. You have to be careful to make code readable if you do this but I've never had any problems with it.Here's a handy (relatively undocumented) tip. PHP supports the following method of assigning strings (borrowed from Perl):
PHP Code:
$string = <<
It can include both 'single' and "double" quotes
without needing to escape them. However, $variables
will still be interpolated as they are in double
quoted strings. Complex variable expressions such as
{$array['element']} or {$object->property} can also
be included and will be evaluated if they are included
in curly braces (they may work without curly braces
but I tend to include them for added clarity). The
string will terminate with whatever you specified
at the start like this:
ENDOFSTRING;
>>>>See php.net for more info.<<<<
-------------------------------------------------------------------------------------------------
You can eek a bit more speed out of your code, especially if you have LOTS of strings, by using single quotes and concanetating variables in (I can't spell today...sigh)
PHP Code:
$string = 'this is a string with '.$foo.' in it';
// is marginally faster than
$string = "this is a string with $foo in it";
The reason is php has to search through the string to find the variable.
-------------------------------------------------------------------------------------------------
It's better to use a comma instead of a dot, because it saves some overhead (no string concatenation).
PHP Code:
// Example:
echo 'foo', 'bar';
// translates to:
echo 'foo';
echo 'bar';
// whereas:
echo 'foo' . 'bar'
// translates to:
echo 'foobar'
The first is cheaper, because PHP doesn't first have to create the new string 'foobar', but can instead send the two strings to output directly.
-------------------------------------------------------------------------------------------------
to echo big chunks of html with vars in the middle using single quotes, instead of double quotes (slower) or jumping in and out of php, even if using shorthand, I do it like this
PHP Code:
echo '
Hello,
My name is ',$name,' ',$lastname,' and am ',$age,' years old.
I live in ',$city,', ',$country,' since I was born.
You can contact me at ',$email,' or by phone at ',$phone,'
Regards,
',$name,' ',$lastname,'
';
it's very shorthand and fast... it can be very comfortable to use in a simple php template system
-------------------------------------------------------------------------------------------------
Consider using str_replace instead of the preg_replace or ereg_replace functions. The only reason why you would use preg_replace or ereg_replace functions would be that you REALLY need to use regular expressions. Also, as of PHP 4.0.5, every parameter in str_replace() can be an array, so theres no excuse to use preg or ereg fucntions when replacing simpel strings anymore.A useful use of str_replace() :
PHP Code:
$string="The quick brown fox jumps over the lazy dog.";
$patterns[0] = "quick";
$patterns[1] = "brown";
$patterns[2] = "fox";
$replacements[0] = "slow";
$replacements[1] = "black";
$replacements[2] = "bear";
$string=str_replace($patterns, $replacements, $string);
//$string="The slow black bear jumps over the lazy dog."
-------------------------------------------------------------------------------------------------
ereg vs pregWhen it comes to the regular expression functions, ereg* and preg*, the preg functions are the clear choice. The preg functions are generally twice as fast as their ereg counterpart. They also support more advanced regular expression operations. I can't think of any reason why you would need to use the ereg functions.preg manual page and pattern syntax (long and confusing but pretty good).
-------------------------------------------------------------------------------------------------
Here's a bit of code I use to change new lines into XHTML
's and
's.
PHP Code:
// the first bit is to make both "\r\n" and "\r" line endings into "\n"
$string = str_replace("\r\n", "\n", $string);
$string = str_replace("\r", "\n", $string);
// this next bit first adds an opening
then makes all double line breaks into
$string = "
".str_replace("\n\n", "
", $string);
// finally this turns any single line breaks into
's and closes the last
$string = str_replace("\n", "
", $string)."
-------------------------------------------------------------------------------------------------
Wednesday, March 19, 2008
Joomla! Wins Best PHP Open Source Web CMS
As Packt Press continues to rattle off the awards this week, its Joomla’s turn in the spotlight. Today’s prize is for “Best PHP Open Source Content Management System”.
Quoting the Packt site, “Joomla! is possibly one of the biggest success stories in open source of late. Its first release came in only September 2005 and since then has grown to be one of the most downloaded Content Management Systems on the web.”
The runners up in this category were Drupal and e107 respectively. Previous winners this week were WordPress for Best Open Source Social Networking CMS and mojoPortal for Best Other Open Source Content Management System.
And the fun’s not over yet. No sir. Rolling right along you avid CMS’ers have both the Most Promising Open Source CMS award and the Overall Winner award to look forward to.
Export ASP.NET page to Word, Excel or PDF
Many times we would like to export our page as an Excel sheet, Word doc or PDF file. This can be simply achieved by changing the ContentType of the Response object and overriding the RenderControl method of the control to be exported:
Page Load()
{
//bind data to data bound controls and do other stuff
Response.Clear(); //this clears the Response of any headers or previous output
Response.Buffer = true; //make sure that the entire output is rendered simultaneously
///
///Use "application/msword" for MS Word doc files
///"application/pdf" for PDF files
///
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
///
///We can render individual controls also, like a DataGrid to be
///exported in custom format (excel, word etc)
///
this.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
} //end page load
For exporting ASP.NET pages as PDF files, you need to know the Adobe PDF specs for generating the PDf correctly. There is already a wonderful component which does the same and its free! See this article along with sample source code on how to export a page to PDF:
http://www.codeproject.com/cs/library/giospdfnetlibrary.asp
Hope this would be helpful...!
Backing Up and Restoring Your MySQL Database
The easiest way to backup your database would be to telnet to the your database server machine and use the mysqldump command to dump your whole database to a backup file. If you do not have telnet or shell access to your server, don't worry about it; I shall outline a method of doing so using the PHPMyAdmin web interface, which you can setup on any web server which executes PHP scripts.
Playing with mysqldump
If you have either a shell or telnet access to your database server, you can backup the database using mysqldump. By default, the output of the command will dump the contents of the database in SQL statements to your console. This output can then be piped or redirected to any location you want. If you plan to backup your database, you can pipe the output to a sql file, which will contain the SQL statements to recreate and populate the database tables when you wish to restore your database. There are more adventurous ways to use the output of mysqldump.
A Simple Database Backup:
You can use mysqldump to create a simple backup of your database using the following syntax.
mysqldump -u [username] -p [password] [databasename] > [backupfile.sql]
- [username] - this is your database username
- [password] - this is the password for your database
- [databasename] - the name of your database
- [backupfile.sql] - the file to which the backup should be written.
The resultant dump file will contain all the SQL statements needed to create the table and populate the table in a new database server. To backup your database 'Customers' with the username 'sadmin' and password 'pass21' to a file custback.sql, you would issue the command:
mysqldump -u sadmin -p pass21 Customers > custback.sql
You can also ask mysqldump to add a drop table command before every create command by using the option --add-drop-table. This option is useful if you would like to create a backup file which can rewrite an existing database without having to delete the older database manually first.
mysqldump --add-drop-table -u sadmin -p pass21 Customers > custback.sql
Backing up only specified tables
If you'd like restrict the backup to only certain tables of your database, you can also specify the tables you want to backup. Let's say that you want to backup only customer_master & customer_details from the Customers database, you do that by issuing
mysqldump --add-drop-table -u sadmin -p pass21 Customers customer_master customer_details> custback.sql
So the syntax for the command to issue is:
mysqldump -u [username] -p [password] [databasename] [table1 table2 ....]
- [tables] - This is a list of tables to backup. Each table is separated by a space
If you are a database administrator who has to look after multiple databases, you'll need to back up more than one database at a time. Here's how you can backup multiple databases in one shot.
If you want to specify the databases to backup, you can use the --databases parameter followed by the list of databases you would like to backup. Each database name has to be separated by at least one space when you type in the command. So if you have to backup 3 databases, let say Customers, Orders and Comments, you can issue the following command to back them up. Make sure the username you specify has permissions to access the databases you would like to backup.
mysqldump -u root -p pass21 --databases Customers Orders Comments > multibackup.sql
This is okay if you have a small set of databases you want to backup. Now how about backing up all the databases in the server? That's an easy one, just use the --all-databases parameter to backup all the databases in the server in one step.
mysqldump --all-databases> alldatabases.sql
Backing up only the Database Structure
Most developers need to backup only the database structure to while they are developing their applications. You can backup only the database structure by telling mysqldump not to back up the data. You can do this by using the --no-data parameter when you call mysqldump.
mysqldump --no-data --databases Customers Orders Comments > structurebackup.sql
Compressing your Backup file on the Fly
Backups of databases take up a lot of space. You can compress the output of mysqldump to save valuable space while you're backing up your databases. Since mysqldump sends its output to the console, we can pipe the output through gzip or bzip2 and send the compressed dump to the backup file. Here's how you would do that with bzip2 and gzip respectively.
mysqldump --all-databases | bzip2 -c >databasebackup.sql.bz2
mysqldump --all-databases | gzip >databasebackup.sql.gz
A Shell Script for Automating Backups?
You can automate the backup process by making a small shell script which will create a daily backup file. How do you get cron to back up your database without overwriting the older backup? You can use a tiny shell script to add the date to your backup file. An example of a shell script you could use is shown below.
#!/bin/sh
date=`date -I`
mysqldump --all-databases | gzip > /var/backup/backup-$date.sql.gzNow that you've got backups of your database, let's learn how to restore your backup in case your database goes down. Here's how you can restore your backed up database using the mysql command.
Restore using mysql
If you have to re-build your database from scratch, you can easily restore the mysqldump file by using the mysql command. This method is usually used to recreate or rebuild the database from scratch.
Here's how you would restore your custback.sql file to the Customers database.
mysql -u sadmin -p pass21 Customers <>
Easy isn't it ? Here's the general format you would follow:
mysql -u [username] -p [password] [database_to_restore] < [backupfile]
Now how about those zipped files? You can restore your zipped backup files by first uncompressing its contents and then sending it to mysql.
gunzip <>
You can also combine two or more backup files to restore at the same time, using the cat command. Here's how you can do that.
cat backup1.sql backup.sql | mysql -u sadmin -p pass21
Moving Data Directly Between Databases
How would you like to replicate your present database to a new location? When you are shifting web hosts or database servers, you can directly copy data to the new database without having to create a database backup on your machine and restoring the same on the new server. mysql allows you to connect to a remote database server to run sql commands. Using this feature, we can pipe the output from mysqldump and ask mysql to connect to the remote database server to populate the new database. Let's say we want to recreate the Customers database on a new database server located at 202.32.12.32, we can run the following set of commands to replicate the present database at the new server.
mysqldump -u sadmin -p pass21 Customers | mysql --host=202.32.12.32 -C Customers
Creating a CAPTCHA with PHP
To put it simply a captcha works by generating a random string, writing it to an image, then storing the string inside of a session or cookie or by some other method. This is then checked when the form or operation is performed. Below is a step by step layout of how it works. 1. Random text generated 2. Text written to image 3. Text stored in session/cookie/database 4. Image displayed to user 5. User enters the code 6. User entered code is checked against the stored key 7. If they match then something is done
Creating the random text
Right now we are up to generating the random text. To do this I will use the php functions, microtime() and mktime() to generate a number. This number will then be encrypted using md5(). With this 32 character long encrypted string we will then use substr() to cut it down to a 5 letter long string. This is our random text.
Note: You may notice session_start() at the top of this script, this is to start the session which will be used later....
//Start the session so we can store what the code actually is. |
Writing the text to the image
Now that we have the text to write we actually need to write it to the image and display it to the user. This is made fairly easy with GD.
/* |
As you can see from the code above we are loading the basic image from CAPTCHA.png instead of building the image itself which could be a little complex for this basic tutorial. When we use colour in GD we need to allocate the colour to a variable, we do this with imagecolorallocate(). Once we have the colours stored inside of the respected variables we then use them to draw the lines through the image. This is to make the robots job of cracking the captcha just that little bit harder, because we are nice to the robots like that :)
Finally we have to write the text to the image which is made easy with imagestring() . The only thing left to do on this image is to output it which is done by setting the content type of the page to image/png with header() and outputting the image to the browser with imagepng(). It is also worth mentioning that the string is encrypted and stored in the session variable $_SESSION['key']
/* |
Check if the user entered the code correctly
To check if the user entered the code correctly you must first allow the user to do this. You can do this with a simple text form that requires a code to be entered, a simple text field called code or something similar should do nicely. Then you just display the image to the user with a simple tag. It is really too low a level to show you how to make a form like this, if you don't know how to make a form like I described above then this tutorial is probably not for you.
Now assuming that this form has been submitted we need to check if the code matches what was on the image, after all this is the whole point of a captcha system. You can do this in any php file as long as the form described above submits to it. For basic checking we will use the code below.
session_start(); |
The session_start() you see here simply continues the session from the previous page, easy enough. Then its just a case of simple text matching which you can see is done by the if statement
Improvements and Conclusion
Well that is all there is to CAPTCHA images just a simple writing of text to an image and storing of the text (key). However the captcha I just described how to build is not the best in the world by a long shot. If you're feeling adventurous you could try the following things: