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:
|
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:
- 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.
- The browser sees that response and pops up the Username/Password dialog box.
- The user enters a username and password in the dialog box, then clicks OK to send the information back to the server for authentication.
- 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:
|
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:
|
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:
|
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:
|
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:
|
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.
|
|||