Taming the Wild Wild Web:

PHP

Sep 22 2008   3:56PM GMT

Server Side Switch: A No-Javascript CSS Style Switcher



Posted by: Jeffrey Olchovy
PHP, Web development, CSS, Web design, Web standards

Navigate through our previous posts in Taming the Wild Wild Web to view both the overview of this project and the HTML/CSS of our dynamic server side CSS style switcher.

Now that we have the markup and declaratives written, we want our page to be able to switch its stylesheet when the “View alternative page style” link is clicked.

In our example, we’ll achieve such an effect by employing the use of some PHP. Our script will let us know a few things about the page itself; namely, where the request is coming from, what style the page currently has, and what page style the user desires.

We’ll save this information in PHP Sessions rather than cookies; so let’s add the session initialization to the very top of our page.

<?php session_start();  ?>

Next, let’s add some session variables to determine what page our request is coming from and the style currently set by the browser.

$_SESSION['page'] = $_SERVER['REQUEST_URI'];
if (!isset($_SESSION['style'])) {
$_SESSION['style']=’default’;
}

switch ($_SESSION['style']) {
case ‘default’:
$href = ‘css/default.css’;
$title = ‘Default’;
$altHref = ‘css/alt.css’;
$altTitle = ‘Alternate’;
break;
case ‘alt’:
$href = ‘css/alt.css’;
$title = ‘Alternate’;
$altHref = ‘css/default.css’;
$altTitle = ‘Default’;
break;
}

Because this is an awful lot of code to add to the beginning of each of your pages, we’ll throw it into a simple PHP file (style-swap.include.php) and call for it at the top of each page, after our session initialization.

<?php
session_start();
include ’style-swap.include.php’;
?>

The variables that we are setting in our switch will be inserted into our link elements that set the current and alternate style sheets for the Web document.

Therefore, let’s modify our markup to receive these dynamic variables:

<link rel=”stylesheet” type=”text/css” href=”<?=$href;?>” title=”<?=$title;?>” />
<link rel=”alternate stylesheet” type=”text/css” href=”<?=$altHref;?>”  title=”<?=$altTitle;?>” />
Now, we’re almost ready to test our page. We still need to construct our trigger when the link to view the new page style is clicked.

We’ll cover that in the next entry at Taming the Wild Wild Web.

Sep 22 2008   3:44PM GMT

The Markup and Declaratives: A No-Javascript CSS Style Switcher



Posted by: Jeffrey Olchovy
PHP, Development, Web development, CSS, Web design, Web standards

In the previous installment of Taming the Wild Wild Web, we discussed a new method for switching the CSS of a page without using Javascript.

Now is the time when we’ll begin constructing an example to showcase such server side functionality.

To begin, we’ll build a simple HTML page that has both a default and an alternate stylesheet.

First, let’s get to the markup:
You can view the entire HTML markup here.

The most important part of our document is the declaration for the two style sheets.

<link rel=“stylesheet” type=“text/css” href=“default.css” title=“Default” />

<link rel=“alternate stylesheet” type=“text/css” href=“alt.css” title=“Alternate” />

The corresponding styles for our document can be found here and here, respectively.

It is worth noting that in this example we redeclare our properties and values for every selector, but in a production level implementation you may want to only use a core style sheet and have the selectors’ properties and values that change only be present on your CSS files that will get the swap.

Notice that we have a link in our footer that references our PHP file which will route our style change request.

In the next installment of Taming the Wild Wild Web, we’ll go over the procedural aspects of this PHP router and the server side includes necessary to give our page its dynamic style switching capability.


Sep 22 2008   3:25PM GMT

A CSS Style Switcher Without Javascript



Posted by: Jeffrey Olchovy
PHP, Javascript, Development, CSS, Web design, Web standards

There has been a recent trend as of late for Web sites to provide visitors with alternate page view styles to enliven the browsing experience.

While this is a positive for Web standards and accessibility (as it gives those users with vision impairments an option to view high contrast page styles), it also makes for a pretty cool way to spice up a page with a previous-had or down-right different user interface.

Most solutions to this CSS Style Switcher require that users click a link which triggers a Javascript behavior-level function to switch the current stylesheet and set a cookie to the user’s computer to save their page-style preference for the remainder of the browsing session.

While I don’t feel that this is a bad solution - I actually have employed this in the past - I do feel that there are quite a few different ways one can achieve this same effect.

In the following entries on Taming the Wild Wild Web, we’ll be constructing a Server Side CSS Style Switcher using a small amount of PHP, HTML and CSS only.

Our Style Switcher will be a cursory introduction to a simple method that gives users the ability to switch page view styles via an on-screen link while keeping the toolbar functionality of choosing the Web page’s stylesheet. The style switcher will also save their preference in a PHP Session, thereby requiring no cookies being set on the user’s machine.

What is required for this project:

  • One HTML file
  • One PHP include (to keep our markup a little cleaner)
  • One PHP file to route our page style request
  • Two CSS files (to provide our choice of page views)

In the next installation of Taming the Wild Wild Web, we’ll construct our two different page styles so that we can get ready for some dynamic server side switching.


Aug 23 2008   4:53PM GMT

Minimize MySQL Queries With Custom Exception Handling



Posted by: Jeffrey Olchovy
PHP, MySQL, Development, Web development

When optimizing the load time of any given dynamic Web page, one should make sure that they are performing the minimum number of back-end database queries required in order to generate their desired result.

When reviewing my database integration classes from a PHP based application, I noticed that the method used to register a new user employed three individual queries: one to check if there already was a duplicate username in the system, another to check if there already was a project name assigned against the one requested, and one to insert the user’s inputted data. Granted, not all three would execute every time a user tried to register, but all three were required for a successful registration. Combine this with n amount of failed attempts, each resulting in either one or two added queries, and you can see that this particularly simple registration process was adding a lot of unnecessary overhead.

To minimize the above processing, I turned to custom exception handling with PHP.

By employing PHP 5’s exception class in simple Java-esque try/catch blocks, I was able to parse the MySQL error on a single failed insert query, returning the problem property (duplicate username or project name - unfortunately not both, if such was raised) back to the user. In order to do this, simply suppress any errors (use PHP’s @ operator) upon your INSERT query, and pattern or substring match the returned error. The MySQL error will return both the number of your key and the problem value. With such information, one can easily process the problem information and funnel it back in a helpful display to the user.

Jeffrey Olchovy is a Web developer, designer and marketing strategist.


Aug 16 2008   3:50AM GMT

jQuery Tutorial: SELECT-to-INPUT Toggle



Posted by: Jeffrey Olchovy
PHP, Javascript, Development, Web development, Web design, Web standards, jQuery

* I’m having a hard time describing this tutorial in the least amount of words possible. Think about it as a jQuery solution to a select box - input toggle, where if you don’t see the option you want in a given select box, you can write-in your desired option via an input element. - JO *

* Update: I did not anticipate the traffic that this article has been receiving, and as such I am sort of embarrassed by the rather inefficient coding and implementation. Like I said in the post, this was a scaled down, simple solution to a problem that I encountered on a larger project - but that does not make it the best way to go about it countering it.

Read the comments on Ajaxian, where you’ll find more efficient renderings of this code and a Prototype version as well (courtesy of davecardwell and jdalton, respectively) *

Recently, when scripting an application that needed to provide users with the functionality to either select an option from a drop-down list or to enter their own text as an option value for the same data item, I began to think that a solution to this situation was going to unachievable via front-end and behavior-level code alone.

You see, similar form field options also appeared in two other instances within the same form and each had to pre-populate themselves with results from a relational database. Things were starting to get a little murky.

Luckily, by employing jQuery for this project, I was able to solve this issue in a mere dozen or so lines of Javascript coding.

The example I will walk you through below will not feature the back-end database connection or the data pre-load, but alas, if requested, I’ll show how simple it is to cross that bridge after you utilize the following method:

First let’s create our form:

SELECT-to-INPUT Toggle - the Form

Notice that both the select boxes and their corresponding input elements have the same name attribute. This will be important for toggling between the select and input modes. You can find this same value attached to the id attribute of each select box as well. Again, these are key in the implementation of our model.

If Javascript is disabled, the input box becomes the sole provider of our data input. We can handle non-Javascript situations in any way, shape or form due to jQuery’s ability to separate the behavior level code from our front-end HTML structure. This example is not production level, and as such, I did not make all attempts to allow for maximum progressive enhancement. A quick and dirty accessible workaround would be to keep the input field onscreen while setting the default display of the select box to none, or vice-versa.

Also note that each select box gets the class ‘leader’. This class will be the hook for our onChange() function, which we will use to toggle between the two input options.

And now for the script:

SELECT-to-INPUT Toggle - the Script - onChange()

In the most primitive sense, this script checks a given element with a class of ‘leader’ and assigns its name attribute to a variable. We check against that same select box via its id. If the select box was changed to ‘other’, we remove the name attribute from the select box and display the input field. If the select box is set to anything else, we remove the name attribute from the input field.

You may be wondering why I continue to wrap my elements via their attributes rather than using the $(this) selector (as it already is assigned to my select box). While testing a more complex application of this method, the $(this) selector did not provide the functionality I required of it and was therefore dropped for this slightly more verbose workaround.

If you test the script, you’ll notice that it indeed works! However, on document load, the input field is still present.

Let’s fix that:

SELECT-to-INPUT Toggle - the Script - onLoad

We’ll use the same skeletal structure of our onChange() function, save for setting it to iterate over each instance of the ‘leader’ class on document load.

In my script I use the fadeIn() and fadeOut() functions, but show() and hide() will work just fine. (What can I say? I’m a sucker for jQuery’s mediocre effects).

So that concludes our tutorial, and with that - there you have it - a simple jQuery solution to your select-input field toggling troubles.

View the Live Demo at Flexible Philosophy.

Jeffrey Olchovy is a Web developer, designer and marketing strategist.


Aug 9 2008   11:24PM GMT

Losing Data in PHP Session Variables?



Posted by: Jeffrey Olchovy
PHP, Development, Web development

If you are losing data in your PHP session variables, chances are, something in your Web application has gone wrong.

Sessions are quite reliable and are, in my opinion, a better replacement than cookies for script control in your applications. Think of sessions as the new accepted standard for user-authentication and the like.

The first thing you should do when checking for problems is to make sure that your session initialization (session_start()) appears across the top of every page. session_start() must be present (and should appear as the first thing in your script) before any code is output to the screen, or it will cause a warning.

If this does not fix your problem, the next most likely happenstance that is causing your session data to be lost is that you are not properly closing your sessions before making a redirection request.

Do this by adding session_write_close() before any redirect.

session_write_close() will end your current session and will properly store all session data. If you do not do this, there is a chance that your session variables may not make it through to the next location. Normally, it is not necessary to call session_write_close() as all session data is stored after your script is terminated, but when trying to redirect to a new location such is not the case.


Aug 7 2008   6:56PM GMT

User Authentication in PHP 5: Sessions Vs. Cookies



Posted by: Jeffrey Olchovy
PHP, Development, Web development, Web services

Web applications in today’s volatile Internet environment need to be able to have tight control over their scripts.

Scripts form the backbone of the functionality behind such programmed interfaces, and without them, an application would be little more than a static Web page. User authentication is one of the hallmarks of Web development, and is natively the prime candidate for such strict script control. When developing with PHP, developers have the choice to refine their scripts to maximize workability and efficiency by employing the use of either sessions or cookies.*

* - There various other methods for user authentication such as HTTP authentication and querystrings, however these are largely tools of the past and/or no longer scalable to the functional level of today’s demanding Web applications.

Each method of script control that we described has its pros and cons:

With the advent of PHP 5, it seems that more developers are turning toward session usage in order to authenticate users and to provide for richer Web application experiences. Let’s take a look at why this is so.

Sessions:

  • Do not store physical files on the client’s computer
  • Files are instead stored on the actual server
  • Sessions must be enabled in order to use them effectively
  • Can be accessed in the global sense (by using the $_SESSION superglobal)
  • Easy to manipulate, update, create or destroy
  • Less overhead as session implementation is largely controlled through the initial PHP configuration file
  • Can store both simple (string, floats, etc.) and complex data types (entire instantiations of objects)

After viewing this list, cookies seem near archaic.

Cookies:

  • Written to a temporary file on the user’s computer
  • This file lets applications know if a user is unique
  • Potential for various security issues
  • Because of these issues, there is a trend for users to not browse with cookies enabled
  • If a user happens across a Web application that uses cookies and their browse is set to reject them, the application will not work properly
  • Cookies are highly customizable, offering much OOP functionality (ex. you can create your own classes for dealing with cookies)
  • Access via $_COOKIE superglobal

I personally recommended that developers use sessions when programming their applications if and only if for the accessibility and usability issues. A Web application need be accessed by the greatest number of users as possible (security matters aside). However, both cookies and sessions are effective ways to tighten the controls of your scripts and each should be in the toolkit of any PHP developer.


Aug 2 2008   5:03PM GMT

Exception Handling in PHP 5



Posted by: Jeffrey Olchovy
PHP, Development, Web development

Because of PHP 5’s Object Oriented capabilities, we see an advanced suite of features for dealing with errors. By implementing an Exception class, we can handle errors like Java by way of segregating them from our “work-horse” code.

Forget about making explicit error checks every time you connect or query your database (the typical or die() method). Instead, use PHP 5’s capability to throw a new instance of its Exception class using try and catch blocks.

Like I said above, this is very similar to Java programming. Anyone familiar with such languages will be able to take advantage of such opportunistic error handling. Be sure to establish an error handler function (use the set_error_handler()) to call a function when an error is generated. This error handler function will throw the new instance of the Exception class, passing an error message and error code as its arguments. Both arguments are user defined, making your code both easy to debug and friendly for your users.

For more information about PHP 5’s Excpetion class, check out its entry in the PHP manual: Exception class.


Jul 27 2008   5:33PM GMT

An Example in the Wild



Posted by: Jeffrey Olchovy
PHP, Javascript, Development, Web development, CSS, API, Web standards, jQuery, Prototype

Over the past week and a half we’ve covered a lot of development material here at Taming the Wild Wild Web.

Now’s the time to admit that my inspiration for these entries came entirely from a project that I was working on during that time period. While it had a very close deadline, it was ultimately a practice in efficient development. Continued »


Jul 23 2008   2:33AM GMT

Building Your News Service API - Adding Fresh Content and Interactivity to Your Web Site



Posted by: Jeffrey Olchovy
PHP, Development, Web development, Yahoo!, API, Web services

In the previous installment of Taming the Wild Wild Web, we managed to get a hold of the necessary components so that we can begin to assemble our Yahoo! News Service API Mashup. When fully complete, we will have a page division that will auto-populate the latest news stories’ descriptions, URLs, and titles into our Web site. As stated in Part II of this series, this will ultimately be helpful in generating fresh content for our Web site on a daily basis. One caveat that I will mention again is that Yahoo! limits the requests made from a single IP address each day - so proper attention must be paid before implementing such an application at the production level.

Let’s continue where we left off: Continued »