Programming Languages

Building Dynamic Web Pages with PHP - This article will explain how to build dynamic web pages with PHP. PHP is a very popular and easy to learn script language. Regardless if you are starting to build your website, or if you are already a pro, just read on to learn more about dynamic web pages and PHP.

PHP Tutorial - It covers all the basic in neat and clean manner. Its recommended for beginner and those that have just passed the beginners mark. Also good for those who want to brush up on the basics. Its intent was to make PHP welcoming for the beginners and not to make the whole intro sound too technical.

TW Tech Glossary - Misplaced your bible? Well here it is! This truly took a while to complete and should be used by all from beginners to advance techies. Look into it, you won't be sorry. (Very Resourceful)

Understanding PHP - This article is mainly to provide beginners of PHP a bit more background into the language then just a bunch of codes. A bit more history, a bit more discussion on the version and syntax of PHP.

Flat File Counter - OK guys, this script is a simple file based counter. This is meant for sites that do not run a db and instead, use a file and a cookie. It isn't the best I've seen but it's simple. Consider this as a tutorial.

PHP Sessions - Building web applications with membership management is one of the most frequent tasks that every programmer does. Read this small tutorial to learn more...

Using Cookies in PHP - Like the title, this tutorial teaches you how to create a cookie. What does a cookie do and why do you need it.

Connecting to a Database Account - How to connect to a password protected database and access an existing table of values.

Creating a New Database Table - Learn how to create a new table and specify the qualities of the various database fields in the table in MySQL.

How to Create a Simple Query Using SELECT - Learn how to display information that is stored n the database table in various ways with MySQL.

Updating Database Tables - Learn how to insert, modify, and delete entries in a database table with mySQL.

Best of the Web Hosting Show Guides - When moving from house to house, you have to pack up all of your belongings in the old house before you can move, right? The same could be said when you are moving from web host to web host. The first and most important thing you can do is backup your web site and get it ready for the move. Remember to grab all of your static files. This would be all of your non-dynamic pages, images, templates and more. The exact files that you do backup might change depending on how your site is setup.

WikiLeaks, The Technical Aspect - Wikileaks has been in the news for quite some time now as it has rocked many nations, embroiling itself in controversy over the fact that it has been releasing classified documents which have been termed as potentially harmful for national security as well as international diplomacy. Amidst all the confusion related to it's ethical and moral standards, people around the world have also speculated how the site functions technically, as a site which has been so controversial, might be technologically sound as well because various steps have already been taken in order to shut the Website down but none of them have availed any results.

Getting Started with WAMP - The tutorial answers many common questions people have about WAMP. The ultimate goal of this tutorial is to help you determine if WAMP is the solution you are looking for by providing the advantages and disadvantages of WAMP.

Choose the Right CMS: WordPress, Drupal, Joomla! - So you want to build a website. You essentially have two options: build it from the ground up with tedious HTML code, or look into a content management system (CMS). A CMS is a web application that allows you to create, manage, and edit your website. If you wanted to add an announcement, post an update, or edit the site in any way, a CMS allows you to do so without going into the code yourself or needing to contact the web developer to do it for you. A CMS makes your life simpler.

Basic Object-Oriented Concepts - There is an old story of how several blind men set out to understand what an elephant was by examining a live specimen. Each of them explored a different part of the elephant's body. One blind man, falling against the elephant's side, proclaimed that an elephant must be very much like a wall. Another, grasping the elephant's ear, decided that an elephant must closely resemble a leaf. One grabbed the elephant's tail and determined that elephants must resemble ropes. Yet another felt the elephant's leg and came away convinced that elephants are very much like trees. Still another held the elephant's trunk and exclaimed that elephants had much in common with snakes.

What Programming Language To Learn - One of the most common questions we hear from individuals hoping to enter the IT industry is, "What programming languages do I need to know?" Obviously this is a complex question, and the answer will depend on what field the questioner is going into. However, those already in IT know that the greatest skill you can have is to be a jack-of-all-trades. A well-prepared worker can switch between computer programming jobs with only minimal training, thanks to a wide knowledge of multiple programming languages.

What is PHP?

PHP is a server-side, HTML embedded scripting language used to create dynamic Web pages . In an HTML document, PHP script (similar syntax to that of Perl. or C) is enclosed within special PHP tags.

Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and ColdFusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code.

PHP can perform any task any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.

PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3). Today, PHP is standard with a number of Web servers, including RedHat Linux.


Tips

Installing PHP as an Apache DSO

PHP is most often paired with the Apache Web server on a Linux/Unix platform. When installing PHP with Apache, you have three installation options: static module, dynamic module (DSO), and CGI binary.



I recommend the DSO installation option as it's extremely easy to maintain and upgrade. For example, suppose you do a simple installation of PHP with just database support. A few days later, you decide that you want to install encryption support. All you have to do is type make clean, add the new configuration option, and followed by make and make install. A new PHP module will be dumped in the proper location for Apache, and all you have to do is restart Apache, not recompile it.

Include files are your friends

If you do Web site development on any scale, you'll recognize the importance of reusable code snippets, whether it's blocks of HTML or PHP. For example, you'll change a footer containing your copyright information at least once a year, and if you have 1,000 pages (or even 10), it's a pain to have to do it all manually.



With PHP, you have a few different functions that help you to reuse code. The function you use depends on what you're reusing.



The main functions are:

* include() and include_once()* require() and require_once()

The include() function includes and evaluates the given file. For example:


include('/home/me/myfile');

Any code in the included file will be executed with a variable scope equal to that point at which the include() occurred in the parent code. You can include static files on your server or target files on another server, using a combination of include() and fopen().

The include_once() function does the same thing as the include() function, only it will check to see if the code from a file has already been included in the current script. If the code has already been included, the function will not include it again.

The require() function replaces itself with the contents of the given file. This replacement happens when the PHP engine is compiling your code, and not at the time it's executing it, unlike include(), which is evaluated first. The require() function should be used for more static elements, leaving include() for the dynamic elements. Like include_once(), the require_once() function checks to see if the given code has been inserted already and will not insert the code again, should it already exist.

Using native sessions

One of the more long-awaited features of PHP 4.0 was its session support. Users of PHP 3.0 had to use a third-party library or nothing at all, and the lack of session support was one of PHP's biggest detractions. No more, though, as session support has been part of PHP 4.0 since the early beta releases.



You can use sessions to maintain user-specific variables throughout a user's stay at your Web site without setting multiple cookies, using hidden form fields, or storing information in a database to which you'd probably have to connect way too often.



Starting a session on a page tells the PHP engine that you want to either start a session (if one isn't already started) or continue a current session:



The most common example used to show sessions in action is an access counter:

PHP and COM

If you're an adventurous soul, and you're running PHP on Windows using the CGI, ISAPI or Apache module version, you can access the COM functions. Now, explaining COM (Microsoft's Component Object Model) is left to Microsoft and very large books. However, for a little taste of what COM can do, here's a common (no pun intended) code snippet.



This code snippet uses PHP to open Microsoft Word in the background, open a new document, type some text, save the document, and close the application:

Version}
"; // set the visibility of the application to 0 (false) // to open the application in the forefront, use 1 (true)$word->Visible = 0; // create a new document in Word$word->Documents->Add(); // add text to the new document$word->Selection->TypeText("Testing 1-2-3..."); //save the document in the Windows temp directory$word->Documents[1]->SaveAs("/Windows/temp/comtest.doc"); // close the connection to the COM component$word->Quit(); // print another message to the screenecho "Check for the file..."; ?>

Suppose you're running an intranet Web site that has data stored in Microsoft SQL Server, and your users need that data in Excel format. You can have PHP run the necessary SQL queries and format the output, then use COM to open Excel, dump the data stream into it, and save the file on the user's desktop.

PHP-based user authentication

If you are looking to password-protect on a per-script basis, you can use a combination of header() statements and the $PHP_AUTH_USER and $PHP_AUTH_PW global variables to create a basic authentication scheme. The usual server-based challenge/response sequence goes something like this:

  1. The user requests a file from a Web server. If th e file is within a protected area the server responds by sending out a 401(Unauthorized User) string in the header of the response.
  2. The browser sees that response and pops up the Username/Password dialog box.
  3. The user enters a username and password in the dialog box, then clicks OK to send the information back to the server for authentication.
  4. If the username and password pair is valid, the protected file will be displayed to the user, and the validation will be carried through for as long as the now-authenticated user is within the protected area.

A simple PHP script can mimic the HTTP authentication challenge/response system by sending the appropriate HTTP headers that cause the automatic display of the username/password dialog box. PHP stores the information entered in the dialog box in

$PHP_AUTH_USER and $PHP_AUTH_PW.

Using these variables, you can validate input against a username/password list kept in a text file, database, or whatever your pleasure might be.



The $PHP_AUTH_USER, $PHP_AUTH_PW, and $PHP_AUTH_TYPE global variables are available only when PHP is installed as a module. If you're using the CGI version of PHP, you're limited to .htaccess-based authentication or database-driven authentication using HTML forms to input the username and password, and PHP to validate matches.

PHP and Java

Another fancy bit of PHP functionality is its ability to invoke methods of existing Java objects, letting you integrate PHP into existing Java-based applications. This ability is pretty snazzy if you're pushing PHP in your workplace and the answer you get is, "But everything's Java here."



To utilize this functionality, you need to have a Java Virtual Machine (JVM) installed on the server. If you install (or have installed) JDKs from Sun, Kaffe, IBM, or Blackdown, you'll be up to speed.



When you configure PHP, you'll need to add --with-java to the configuration directives, then modify some elements of your php.ini file. The php.ini modifications are usually along the lines of adding the following:


[Java]

java.library.path=/path/to/libraryjava.class.path=/classpath/
extension_dir=/path/to/extensionsextension=libphp_java.so

Please note, however, that these modifications depend on your type of installation. You should read the README in the ext/java directory in your PHP installation directory to learn more about configuring for Java functionality.

Here's a very simple example of a PHP script creating a new Java object. The script will then access and print to the screen certain Java properties. It's about as exciting as the COM example, but it gives you an idea of the possibilities.

Java version = " . $system->getProperty("java.version") . "
";echo "Java vendor = " . $system->getProperty("java.vendor") . ""; ?>

If you have Java knowledge, by all means jump in and help the developers with this project. These types of integration capabilities will be key in the future growth and acceptance of PHP, so the more people working on these types of things, the better.

Turn On Error Reporting Immediately

The single most important thing I tell people who use PHP is to turn error reporting to its maximum level. Why would I want to do this? Generally the error reporting is set at a level that will hide many little things like: declaring a variable ahead of time, referencing a variable that isn't available in that segment of code, or using a define that isn't set.



These factors might not seem like that big a deal -- until you develop structured or object oriented programs with functions and classes. Too often, writing code with the error reporting turned up high would cost your hours as you scoured long functions that didn't work because a variable was misspelled or not accessible.



PHP won't tell you anything in that case ? it'll just create the new variable for you and initialize it to zero. The remedy is to put the following line at the top of every PHP document as you develop:


error_reporting(E_ALL);

It simply forces the error reporting to be at its highest level. Try putting this line in other PHP programs, and more often than not you'll receive a barrage of warning messages that identify all the potentially wrong elements of the code.

Single Quotes and Double Quotes are Very Different

I never recommend using " (double quotes) when programming with PHP. Always use ' (single quotes) unless you need the features of " (double quotes). You might think it's much easier to write code as:


echo "Today is the $day of $month";

However, using single quotes forces variables to be outside the quotes; instead, you must use theperiod (.) to combine strings. It makes for faster coding but can be more difficult for other programmers to read. Let's look at what would happen if we put an associative array value in the previous code:

echo "Today is the $date[?day?] of $date[?month?]";

You would receive a parse error and it would be harder for another team member to read. Two correct ways to write that line of code would be:

echo 'Today is the ' . $date[?day?] ' of ' . $date['month'];

and

echo "Today is the {$date['day']} of {$date['month']}";


These might not look as pretty as the original code, but syntactically they are both correct. Additionally, I believe the first method, with single quotes, is easier to read.



The use of single and double quotes also applies to associative arrays. Consider this code:


$SESSION[team] = $SESSION["old_team"];

One main problem exists in that line of code. The associative entry team on the left side needs to have single quotes around it; otherwise, PHP will think it's a define and give you a warning message (only if error reporting is at maximum). I would recommend that the code should look like this:

$SESSION['team'] = $SESSION['old_team'];

I wish I'd known the difference between single and double quotes as they pertain to strings when I first learned PHP.

Appl ying a Screen to an Image

Basically, the usage is very simple. This function applies a black 50% screen to your image, making every second pixel (in alternating positions on each row) black. It takes a single to image pointer as a parameter, and uses pass-by-reference to make changes directly to that image without creating a copy to work from.



It has a lot of interesting uses (for example, it could be called on the fly in a JavaScript image replace call to gray out a selected image, etc.), and works great with photos. It's also quite tweakable, so feel free to modify the gradient pattern or color of the screen to suit your needs. Just beware of using it as-is on a black image, 'cause you won't see anything. :) 

Generating Dates in the Past

I recently ran into a question in a PHP message forum where someone was trying to get a date from one week ago, but didn't understand the use of timestamps.



All PHP dates are based on Unix timestamps. A Unix timestamp is simply an integer specifying the number of seconds since the epoch (12:00am GMT on January 1st, 1970, I believe :).



Subtracting dates is actually quite simple. You can add, subtract, etc. from Unix timestamps to generate future and past dates, or to get the time difference between two timestamps. Using the microtime functions in PHP, you can even figure out the precise differences in milliseconds.



However, for this example, we'll simply use seconds, since we're only trying to get rounded dates.



So, how can we get a date one week in the past?



Here's how: Perform a subtraction on the current date's timestamp.



Try this:

Today:

One week ago: 

The output:

Today: 2001-08-27 One week ago: 2001-08-20

Pretty cool, eh? Now you can mess around it on your own to figure out date/time spans, intervals, etc. Enjoy!

Last Modified Date

Tired of using JavaScript to get last updated dates and times on web pages? Try this:

 Also, swap in filectime() (replacing filemtime()) if you want to return the file's creation date instead.

SQL as a Localization Exercise

In general to provide real portability, you will have to treat SQL coding as a localization exercise. In PHP, it has become common to define separate language files for English, Russian, Korean, etc. Similarly, I would suggest you have separate Sybase, Intebase, MySQL, etc files, and conditionally include the SQL based on the database. For example, each MySQL SQL statement would be stored in a separate variable, in a file called 'mysql-lang.inc.php'.


$sqlGetPassword = 'select password from users where userid=%s';$sqlSearchKeyword = "SELECT * FROM articles WHERE match(title,body) against (%s)";


In our main PHP file:


# define which database to load...$database = 'mysql';include_once("$database-lang.inc.php");$db = NewADOConnection($database);$db->PConnect(...) or die('Failed to connect to database');# search for a keyword $word$rs = $db->Execute(sprintf($sqlSearchKeyWord,$db->qstr($word)));


Note that we quote the $word variable using the qstr( ) function. This is because each database quotes strings using different conventions.

Properly Capitalizing a String

Ever run into a problem where you have a whole lot of non-standard formatted strings that you need to properly capitalize?



Let's say, for example, that you have a collection of movie titles in a database. However, all of the information came out of an old legacy system, and the data is all in upper case. Here's a handy little function that'll clean up those titles for you:

Usage:

The output should look something like this:



The Revenge Of The Pink Panther



Also, if you add a little logic to the function, you can look for normally lower-cased words like "a", "the", or "of" in the middle of a sentence, and ignore them.

Reversing an Array

I noticed that PHP doesn't seem to have a reverse() function to reverse an array, but instead has reverse sorting, which isn't that useful in some cases. Try this instead:

The above uses a pass-by-reference to avoid having to reassign your array afterwards. To use, all you need to do is call the function with the array you want to modify as the only argument: 

Throw it into a library, saves you writing it yourself.

Verify the Domain of an E-mail Address

Here's another quickie - this function will allow you to verify the domain portion of an e-mail address if you're trying to restrict access on your site and don't have access to the web server config files. This function could definitely be tweaked up a lot if you want to narrow things down, but I haven't made the effort to soup it up yet.


Did You Know?

  • PHP is one of the hottest language on the web today. It is adopted by over 3million websites and growing by the hour.



AlarmPlanet: Web's First Home Security Portal


Links