A potpourri of Web Developmemt, Linux, and Windows tidbits and observations

PHP Passing Function Variables

Posted by dale | PHP | Wednesday 10 March 2010 12:15 am

This obviously is not a new topic. Functions and variables have been around for as long as programming has been around, and passing variables in functions are present in all programming languages. For the sake of completeness, since we just covered “include” and “require,” let’s take a look at functions and variables maybe from a slightly different angle.

So let’s get started. This metric stuff is disorienting at times. To make things easier for folks visiting your web site, you decide to offer them an easy way to convert Celsius temperature to Fahrenheit. Since many user’s may want to do this conversion, let’s create a function to convert Celsius to Fahrenheit.

So here’s the function.


function ConvertCelsius ( $celsius_to_convert ) {

$fahrenheit = (1.8 * $celsius_to_convert ) + 32;

return $fahrenheit;

}

You drop the function in your library.php file, and your all set. Let’s use it. You have a map of a region on your web page that shows temperature in Celsius all over the map. In the upper right corner you have an input named, “celsius.” labeled “Convert Celsius to Fahrenheit.” with a Submit button. Yes, I know it would be nicer to click a button and convert all the readings to Fahrenheit. I’ll leave that to you. For this example, you type a temperature into the box and click the “Submit” button. We’ll use a form “Post” method, and on submit send it back to your controller file. Let’s peak into the controller.php file.


/* Bring the inputted temp in from the form
and assign it a variable name.  */
$celsius = $_POST['celsius'];

/*  Bring in the function in the library.php file  */
include ("library.php");

/*  Call the function to do the conversion  */
$fahrenheit = ConvertCelsius ( $celsius ) ;

Now, we have some things to talk about. First, you do not have to put your function in a library file, you can put it in any file, including the same file where you use it. The function obviously needs to be declared or stated before the function is called.

You can pass more than one variable into a function. Convert ($inch, $foot, $gallon, $fahrenheit); would pass four variables into the function. However, you’re only allowed to pass one variable back from the function with the return, as in “return $fahrenheit”. Not to worry, the one variable, can be an array or an object, which would allow you to pass more than one variable back with a return.

Notice that the variable, “$celsius” you passed into the function does not have to be called “$celsius_to_convert” that you have in the function. It is converted to “$celsius_to_convert” by the function when in the function.

Which brings us to scope. “$celsius_to_convert” is called a local variable. It is valid only inside the function. I can not use it outside the function. The way to use the data coming back from the function is to assign it to a variable outside the function, like so: $farenheit = ConvertCelsuis ( $celsius ). We can use $fahrenheit outside the function. This concept of where a variable is valid is known as scope of a variable. Let’s stop here for now.

PHP Include and Require – Passing Variables

Posted by dale | PHP | Sunday 7 March 2010 11:52 am

Frequently when you write a php application you have a task or functionality in your code that you will use over and over again.  For example, when verifying form inputs, you would want to make sure that a number is an integer, and eliminate all letters and decimal points.  This is handled by creating an integer verification function, you might call checkint().  You usually place the checkint() function in another library file that contains all your other verification functions, maybe called verification.php.

The normal flow of your application runs something like this.  You get your form information from your html web page and with a “post” method, feed it back to your php controller file.  If there is an integer value in the form, you assign it to a variable, “$intvalue” for example, you want to verify the data coming back from the form is what it’s meant to be and is not corrupted, so you call your “checkint($intvalue)” function to check the “$intvalue” variable.

There’s only one problem, since the Internet is stateless, the controller file knows nothing about any other file, function, or variable in the system.  The controller file does not have a clue as to what “checkint($intvalue)” function means, or where it is located.  And it responds with an “undefined function” error message.

The above situation calls for an “include” or “require” function in your controller file.  We want to “include” or “require” the verification.php file, that has the checkint() function in it, to be placed in the controller script.  And that is what the “include” and “require” functions do.  They open the verification.php file, copy, and place its contents in the controller file.  After this operation is completed, the checkint() function is now in the controller file, and you can go ahead and use the checkint function to verify your data.

Here’s the syntax for ways you can include another file in your current file:


/* With includes, all of these are valid */
include " ../files/verification.php";
include ("C:\wamp\www\mysite\files\verification.php");
include "http://www.anothersite.com/index.html?clr=red&style=xhtml";
include_once ("verification.php");

/* You can substitute require for include in all the above examples.  */

require ("verification.php");
require_once "verification.php";

You can use () or not, since most functions use (), it is normal to use the ()’s with your includes and requires.

You’ll notice in line 4, I returned the variables “clr” and “style” with the include file which could have come from another server. You can retrieve the color and style variable with a call to the php get, like so: $scrclr = $_GET['color']; and $varstyle = $_GET['style'];

Include and require do the same thing, the difference is if you can’t find the file with require, it will shut your application down, while with include it will throw an error message and continue with the application.  Other than that include and require are the same, and can be used interchangeably.

You can use include and require in conditional statements to only bring the file in if a certain condition is met, like so. 


if ( $layer = 12 ){
include ("../file/layer12.php");
}

/* the {} are required with an include or require  */

A require will bring in the file even if it is a false condition, while an include will not.

Why use include_once or require_once?  Your not allowed to declare the same variable or function twice within a script, or php will throw an error.   The error message will read something like this:

“Fatal error: Cannot redeclare checkint() (previously declared in :67) in c:\www\wamp\mysite\files\verificaiton.php on line 71″

This error can also come when an included file calls another include, and this is where problems can start that will drive you nuts.

If you use “include_once” or “require_once,”  php will check to see if the file has already been included, if it has it will proceed without including the file, which will prevent the above error.

Another error with includes is improper order.  You call the function you need before you include the file.  PHP runs scripts in order, the include needs to come first.

In a complex application with many files, some of my most frustrating errors have come with includes and trying to figure out why I’m getting the redeclare error message.  I’ve also had problems with include_once, and the undeclared variable error message.

Although the error message may tell you where the problem is, it doesn’t tell you where the original include occurred or why the function has not been declared already, which sometimes causes you to track through your system.  A patch, if you are really hung up by an error message, and are short on time, is to ditch the include and to redundantly repeat the function in the script itself, not what I call eloquent coding, but it works.

Opera 10.50 released

Posted by dale | Browsers, Software | Friday 5 March 2010 4:42 pm

I keep writing about the Opera browser, I can’t help myself.  Opera Software has put the Opera web browser at the forefront of web browser technology with innovative features, some of which are unique to the Opera browser.  Admittedly the browser technology crowd is an incestuous bunch, and steal ideas back and forth from one another, still Opera has been doing it better, and more uniquely than any other browser for a couple of years now.  What I don’t understand is why it only has 3% of the market share, it deserves a larger share of the market.  Here’s why.

With this new release 10.50, Opera has introduced a new JavaScript engine, actually three new engines combined, that together, increase the speed of the browser up to seven times faster than the previous version, which was already fast.  Opera Software claims Opera 10.50 is the “Fastest Browser on Earth.”  It is.  Couple that with a perfect score of 100 on the ACID3 test, and you have a state-of-the art, W3C web compliant, lightning fast, web browser, and there’s so much more.

Opera has joined Cloud Computing in using additional servers on the Internet to enhance your browsing experience in three ways that currently no other browser supports. First, we have Opera Turbo.  Opera Turbo can be used by people with slower Internet connections.  Opera turbo compresses the web page on the server to up to 80% of its original size to speed your download speed.  This will improve your browsing speed on some of the slower wifi connections in retail coffee houses also.

Second, we have Opera Unite. Opera Unite allows you to share music, videos and documents with friends without having to either email the content to them, or uploading the content to a server.  It sets up a virtual server between your friends over the Internet. This means larger content files like movies can be shared with your friends easily.

And finally, we have Opera Link.   For those familiar with Delicious, a web service that allows you to centralize all your bookmarks and put them on the Internet, Opera goes one step further.  You set up your Link account in each of your computer browsers.  From then on Opera Link can keep your Bookmarks, Browser configuration, history, Speed Dial, Notes, and Searches synchronized with all the rest of your Opera browsers automatically.  If you set a new bookmark in your browser at work, it will automatically show up on your home browser.

That brings up Speed Dial, which shows you images of your favorite web pages you can click on when you open a new browser window.  Unique to Opera is Visual Tabs, pull down the menu tab bar and an image of the web pages in your tabs are shown.  For those small fonts on the web page, and for readers who can’t see the page, there is a Page Zoom icon to quickly zoom in to the web page with a simple click of the Page Zoom icon on the bottom right toolbar, that’s nice.   With Notes, you can select some text on a web page, right click, and save it to Notes.  This automatically saves the text and the web URL, for reference later.  And it’s not limited to one note, like Microsoft’s copy and paste.

Then we have faster browsing with a series of enhancements.  Mouse Gestures allow you to customize your mouse movement. To give you an example, right click on your mouse, and move your mouse to the left, and you’ll go back to your previous web page, no more having to place your mouse on the “Back” icon at the top of the browser to go back one page. There’s Fast Forward to go to the next page, like the back button, this one guesses what your next page would be, and takes you to it.  No more going to the bottom of the Google page to find the next page number.  And there’s a fast back to take you to the original page of your search.  Opera will fill out the user name and password for a particular web page automatically if you like with their Password Manager.

You need a Dictionary, an Encyclopedia, or to Translate a word into another language, select the word, and right click, and select what you want to do.

If you close some of the tabs you had open and closed the wrong one by mistake, no problem, there’ a Trash can icon that keeps track of tabs you closed. You can also browse History Free if you prefer.

Have you ever wanted to find a particular word on a web page full of text. One way you could do this is with Alt-F then type in the word, Opera makes this a little easier with Find in page,  just type a period with your word, and it is highlighted on the screen.

Windows7 and Vista introduced Widgets for little applications you wanted on your desktop. There’s Opera Widgets that do the same thing in your browser window.

And now to features that I really like.   Google’s Chrome originally allowed you to type your search into the address bar.  They were the first, then Firefox followed, Opera has done them one better with a Quick Search.  You can type your search into the address bar, like with the other browsers, and in Opera you can assign a one letter url for the address bar.  Let me give you a couple of examples.  I want to search for a JavaScript book on Amazon, type “z javascript” in the address bar and you’ll go to Amazon books and the JavaScript books page pops up.  You can type “w php” and bring up the Wiki for php, or “e ipods” and bring up Ebay on the ipod page.   What’s nice is you can create your own custom key shortcuts also.   If you go to Amazon a lot this really simplifies getting to where you want to be.

And finally, Opera is starting to listen. I have said many times before that if Opera would put out some decent web development tools, I would give up Firefox for web development and use Opera full time.  With this release the Alpha of Opera Dragonfly is being released.  This will be a full-featured development environment allowing you to debug JavaScript, inspect the DOM, the CSS, network traffic and data stores with built-in remote debugging for mobile devices.  To view page source, go to page->Developer’s Tools->source, or validate, or Inspect Element. You can Inspect the element on the page with a right click of the mouse.   This is an Alpha version, some of the choices are not functional yet,  as to be expected with an Alpha release, like the color picker, but Operation Dragonfly, the equivalent to Firebug on Firefox, looks like it has the potential to out do Firebug in functionality once everything gets hooked up.

Opera, now that you are finally moving to be a full fledged web development tools, let me help you.   Things I missed in Opera Dragonfly for Web Development, that I want.  The F12 key to bring up the application, and put it back down, quickly.  The Inspect button in Firebug that allows you to search the screen for an element with your mouse.   Yes, Dragonfly does it with the right click, Inspect Element, but its not the same, or it’s not fully functional yet.  I’d like an Aardvark plug-in type of functionality where I don’t have to bring up Dragonfly to view the DOM element.  I want to see all the CSS affecting the page with file names, like Web Developer, View CSS, in fact the entire Firefox Web Developer plug-in would be nice.

Keep working!  Your doing great work. Your web development tools aren’t quite there yet, but I see you’re actively working on them, as you get closer and closer, you may win me over for Web Development, you already have for general web browsing.  For those who have not tried Opera, I recommend you try it out, you might like it.

Resizing the background image with CSS

Posted by dale | CSS, XHTML | Wednesday 3 March 2010 3:31 pm

With monitor resolutions getting larger and larger, and with the advent of large screen TV’s that can double as computer monitors, web developers have a dilemma. What resolution do you use to build a web site that will look good with all these different resolutions?

It use to be that you built web sites for a 800×600 resolution monitor, those days are gone. Now only about 3% of users have their monitors set at 800×600. The current sweet spot is 1024×768 with 20% of the viewers using this resolution. With more and more people moving to 1280×800 at 19% and 1280×1024 at 15%. The resolutions are all over the place. At this point in time you should optimize your web site design for 1024×768. That means that those folks that are still using 800×600 will have to scroll to see the screen.

The fact that a significant number of users not only have different resolutions, but most are greater than 1024×768 has led web designers to design sites that stretch their width for different resolutions. The CSS term for this type of layout is “liquid layout.” The problem with liquid layouts is that if the screen stretches too wide, and text lines get longer and longer, text becomes difficult to read. The solution for this is the “jello layout,” where the expansion of a web page is limited to a maximum width.

One of the solutions to the changing width is to use a consistent background color to surround your main content. This works and it is the easy way out, the content is set to a maximum width and the background covers whatever width is left. At higher resolutions though this looks ugly, too much background color. The solution is to make your background more interesting with a background picture or composite image, and that’s when you run into some problems.

The traditional way to put a background image on your site is in the CSS file, like so: body {background-image: url(../images/myimage.jpg)}. The only problem with doing that is that you can’t re-size the background image in CSS. To do this you have to move the image to your html file. This allows you to style and re-size your image in the CSS file.

Before we get into how to do this, a word about the background image you will use. If you expect to stretch the background image in width from one resolution to the next, you want an image that is more landscape oriented than portrait oriented. The problem with a portrait image is if you stretch the image too much you will distort the picture, landscape images bend easier in width. You also should scale the image to a size close to the size in width it will be at 1024×768, or 1024px. You can crop the image if it becomes too long in height. Lastly, you should worry about the image load time or the file size, and consider compressing the image to reduce the file size.

OK, we have the image we want for our background set up and ready to go. How do we set the background image to re-size with changing resolutions. First the html structure:




Background Image

Nothing unusual here. We are inserting an image into the web page right after the body. The tricks are in the CSS, let’s get to that…


* {
	margin: 0;
	padding: 0;
}

body {
	text-align: center;
}

#backimg img {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 0;
} 

That’s all there is to it…well, not quite. This will anchor your image to the upper left corner as a start point. The “position: absolute;” takes the image out of other relational groupings with the rest of your web page, and is important to making this work. The width: 100%; tells the browser to stretch the image across the entire monitor window. Well, get to the z-index in a second.

Well, that’s all well and good, if you change browser resolutions, you’ll see the image stretch, depending on your monitor resolution, but how does the content area fit into this set up? Well, the “bodywrap” tags represents the content of your web page. You want that centered in your window with the background image to show on either side of your content. It would be nice if the content would re-size with the background, and well use the same technique to do just that. Here’s the CSS.

#bodywrap {
	position:absolute;
	width: 94%;
	margin-left: 3%;
	margin-right: 3%;
	margin-top: 30px;
	z-index: 20;
}

This will expand your content with a 3% border for your image to show on the edges. Use the margin-top: 30px; if you would like to show a piece of the background image at the top of the screen. If you’d like to have your content have a white backdrop, we need to add another div. It would be background image, then backdrop, then bodywrap for your content, here’s the CSS section for the backdrop, like so…

#backdrop {
	position: absolute;
	background-color: white;
}

Here the color of your backdrop is white and we have also taken the backdrop out of the web page components layout, but it is absolutely embedded in the bodywrap.

Which brings us to the z-index. The z-index tells the browser which layer to put on top of another layer. The higher the number, the more that content block is moved to the front of the screen. Thus our background image is 0 and the bodywrap is in front of that image at a z-index of 20.

Here’s the complete CSS file in a compressed format. Enjoy.


* {margin: 0; padding: 0; }
body {text-align: center; }
#backimg img {position: absolute; top: 0; left: 0; width: 100%;	z-index: 0; }
#bodywrap {position:absolute; width: 94%; margin-left: 3%; margin-right: 3%; margin-top: 30px; z-index: 20; }
#backdrop {position: absolute; background-color: white; }

The php.ini file – Configuring Sessions in your Application

Posted by dale | PHP | Tuesday 2 March 2010 10:28 pm

I mentioned in the last post that there are over 11 different variables in the php.ini file to use to configure how PHP uses sessions in your application.  I thought a post you could use as a reference to help you configure the session portion of your php.ini file might be helpful.

The first problem you’ll encounter though is that there is more than one php.ini file on your computer.  Hmmm…Which one do you use?  On my windows system, I did a search for all the php.ini files on my computer and came up with 23 php.ini files.  What’s going on?  As I looked over the list, I realized that most of these came from back ups of my previous development efforts.  Since I use the WAMP local development server on my windows system.  WAMP stands for Windows, Apache, MySQL, and PHP.  I limited my search on those php.ini files in the WAMP directory.  This cut the list down to two, one in the php directory and one in the apache\bin directory.  The reason for two is that the Apache php.ini file should be used when you are getting ready to deploy your system it is used for better performance and security, while the php.ini in the php directory is used during development and allows for more verbose error messages.  Since we want to configure how php handles sessions, and my applications need to deploy properly, I usually just configure the Apache php.ini file.

If you open the php,ini file in a text editor, you’ll find a text file that has comments, interspersed with variables starting with a semicolon. The semicolons in front of variables means ignore this variable. To make a variable active, you remove the semicolon.

The php.ini file is fairly long.  If you have line numbers turned on in your text editor, the end of the file comes in at about 1885 lines.  Somewhere around line 1435 will start a long list of variable starting with the word “session.” , I counted 24 specific session variables, you can configure.   I was off a bit on the number, let’s go through them.

The default variables, are the ones with no semicolon in front of the variable.  Most of these are standard and do not need to be changed.  For example, the WAMP default save path, stored in “session.save_path” is where all session files are stored. The default is “c:\wamp\tmp”. If you look in that directory, you’ll see past session files. These are dense text files you can view with a text editor, and this is how session information and session  variables are stored and used from page to page.

session.use_cookies = 1” tells php to use cookies to store the session ID, see my previous post for a description of session ID.  If cookies are turned off on a user’s computer, the session ID is transmitted in the URL, like with a GET form method.  This make the session ID public in the URL.  You can tell php not to do this by setting “session.use_only_cookies = 1″  This is the default. Later in the php.ini file you’ll fine “session.use_trans_sid” which tells PHP to detect browsers with cookies disabled and use the GET URL.  The default here is also off or 0.

session.auto_start = 0” tells php to not to start a session when the
user first accesses the server.  A “1′ would start a session automatically.  The default is off.  You’d think you’d want to start sessions automatically when a user goes to your web site, but I prefer not to autostart sessions, because later when we pass objects you’ll find that classes need to be defined before you can pass an object in a session.  If you autostart the session, nothing is defined before the session starts, and objects cannot be passed.  This could give you nightmares trying to figure why your application isn’t working, much more later.

With a lot of these variables, the default is fine.  There are a series of variables used by the setcookie funcion, which let you control the use of the cookie with sessions.  These include session.cookie_lifetime, session.cookie_path, session.cookie_domain, and session.cookie_httponly.  You can restrict cookie use to certain domains for example, the default is cookies can be used on all domains.

session.gc_probability, and session.gc_divisor: PHP has garbage collection it uses to clean up sessions that have expired, otherwise on a site with a lot of users accessing the site could cause a huge amount of session files to be continually generated.  The default is fine. Garbage collection does not happen automatically and needs to be incorporated into your system maintenance routines.

This bring us to “session.gc_maxlifetime = 1440“  This is the lifetime of your session in seconds before the file will be marked for deletion.   PHP cleans out the file as part of its garbage collection.  The default is 24 minutes.  If users are on your site longer selecting items for there shopping cart, for example, you want to make this number larger.

The next series of variables concern with security and using sessions as a global variable, which is bad for the application and security.  These variables,  session.bug_compat_42, session.bug_compat_warn, session.referer_check, session.entropy_length, and session.entropy_file, change from release to release in PHP as PHP gets more secure, and should not be changed.

Browsers cache web pages to improve performance, for security reasons you want to limit page caching with sessions, since page caching can make your session information public, you want to limit browser page caching on pages with sensitive information.  This is controlled with  “session.cache_limiter” and “session.cache_expire.”  I encourage you to use “nocache” which is the default, which will turn off page caching on pages with session information.

The last session variables, “session.hash_function, and session.hash_bits_per_character” concern how the session ID is generated.  The defaults settings are already robust, leave them alone.  That’s about it for configuring sessions in the php.ini file.

Increasing the Joomla 1.5 Search Component character limitation

Posted by nic | Joomla | Monday 1 March 2010 11:50 am

The default character limitation for the native Joomla! Search Module is 20 characters.  Increasing this value requires a bit of Joomla! hacking, and although there are a number of resources for accomplishing this, I could not find any that pertained to the current (or even recent) Joomla 1.5 release.

NOTE:  You should not remove the maxlength entirely.  As long as search times are non-critical to you, and your database is not enormous, making it 50 or 100 characters should make for a more appealing search interface in most cases.

In order to change the search character limitation to 45, make the following changes:

Note: The ” – -”  means delete this, and the “++” means to add this back

/modules/mod_search.php

-- $maxlength		 = $width > 20 ? $width : 20;
++ $maxlength		 = $width > 45 ? $width : 45;

/components/com_search/views/search/tmpl/default_form.php

--

++

/administrator/components/com_search/helpers/search.php

--    // limit searchword to 20 characters
--    		if ( JString::strlen( $searchword ) > 20 ) {
--   			$searchword 	= JString::substr( $searchword, 0, 20 );
++    // limit searchword to 45 characters
++    		if ( JString::strlen( $searchword ) > 45 ) {
++   			$searchword 	= JString::substr( $searchword, 0, 44 );

/language/en-GB/en-GB.com_search.ini

-- SEARCH_MESSAGE=Search term must be a minimum of 3 characters and a maximum of 20 characters.
++ SEARCH_MESSAGE=Search term must be a minimum of 3 characters and a maximum of 45 characters.

There you have it, enjoy!

Thanks to the following:
leeburstroghm – for pointing out that this change requires mods to the admin component in order to function properly on the front-end.

m2d^ – for a helpful post that accomplished this update in an older version of Joomla! / the Joomla! Search Component. It’s close, but just distinct enough to make things tricky.

Ubuntu 10.04 “Lucid Lynx” is coming!

Posted by dale | Ubuntu | Sunday 28 February 2010 3:03 pm

The next release of Ubuntu, version 10.04, “Lucid Lynx” is set for April 29, 2010. The Alpha 3 version is out, and there is much buzz about what to expect from the next release.

This release is set for long term support which offers bug fixes and security patches for three years for desktops and five years for servers. Usually the six month Ubuntu releases are supported for only 18 months.

Something that all the Linux distros have struggled with is keeping up with video drivers. Ubuntu has made a concerted effort to support NIVDIA drivers, even though NIVIDIA keeps its drivers proprietary. With this release, the Nouveau project will be the standard NVIDIA project used by Ubuntu. The Nouveau project specializes in high quality, open source drivers for NIVDIA cards. This is good news for system builders, who are major users of Ubuntu, and favor NIVDIA graphic cards. Currently, Nouveau offers full 2D support for NVIDIA cards. 3D support is not quite there yet, but there working on it.

Along with this, transparency in all areas of the desktop and in applications will be supported.  GNOME 3 will be available in March, before Lucid Lynx, with additional functionality for the desktop.  What all this means is that those fancy aero screens in Vista and Windows 7 with desktop stunning images now will be possible in the Ubuntu desktop. With Gnome 3 and transparency coming to 10.4, we could be pleasantly surprised with a considerable upgrade in “eye candy” for this release.

New applications include easier file sharing between Windows and Ubuntu implemented with Personal File Sharing.   Gwibber will allow for easier social networking by retrieving and combining information from Facebook, Twitter, Flickr, and Digg to name a few social sites.  And there will be  support for Apples  iPhones and iTouch drag and drop in Rythmbox.

Much effort has been put into getting Ubuntu to boot quickly. Ten second boots has been the goal. This new release will be close to that goal. Boots from 10-15 seconds have been reported. That’s incredible! We’re getting closer and closer to “Instant On.”   Microsoft, which touted quick booting as a feature of Windows 7, takes twice as long. A splash screen has been added to start,  so you don’t have a period of time with nothing on your monitor while booting during that 10 seconds that is.  I’m still blown away by this kind of boot time, just amazing.

Ubuntu is getting very close to being a better operating system environment for computer hardware and software than Microsoft Windows. If the public becomes knowledgeable about just how good Ubuntu is, we could see a positive shift in Ubuntu’s market share.

The PHP $_SESSION array – Passing Variables

Posted by dale | PHP | Saturday 27 February 2010 7:40 pm

The problem of storing user information while the user is accessing the web site is solved with sessions in PHP. Essentially, when the user logs into a web site and enters some information, the server assigns the user a 32 character, random, session ID which uniquely identifies the user. It stores this ID on the users computer as a cookie, along with time-out expiration information. Any additional sensitive user information, like the quantity, and item number in the shopping cart, or a credit card number is stored on the server, along with that particular user’s session ID.

I don’t have enough space in this post to go through all the details on how sessions are configured. The “php.ini” file currently contains 24 different session variables that can be set concerning sessions security, session expiration, where sessions will be stored on the server, what to do if the user disabled his cookies, and whether a session should be started automatically when a user arrives on a site. I will cover these in more detail in my next post. Usually the default configuration when you first install PHP is adequate. For now, let’s concentrate on using session to store variables between web pages.

To start a session you call session_start() at the top of the web page file, before anything else. Since your storing the session ID in a cookie, session_start has to be called before any new line in the web page file, please see my cookies post for an explanation. When session_start() is called PHP checks to see if a session has already been started, and if it hasn’t, it will assign that user a session ID and store it in a cookie. It also sets up a unique global session array on the server, identified by, you guessed it, the session ID.

PHP keeps session variables in a $_SESSION[] array. This array is available globally, which means it doesn’t matter which page of the web server application you go to, the information will be available, which is what we want.

To store information in a session that you can use in your application, or specific user information, you do the following:

session_start();
$_SESSION['firstname'] = $fname ;
$_SESSION['lastname'] = $lname ;
$_SESSION['usercity'] = $city ;
$_SESSION['address'] = $addr ; 

That’s it. You now have firstname, lastname, usercity, and address available to you on any web page in your application. Notice that the information is stored in an associative $_SESSION array. To retrieve this information on another page, we do the reverse, at the top of the file, like so:

session_start();
$fname = $_SESSION['firstname'] ;
$lname = $_SESSION['lastname'] ;
$city = $_SESSION['usercity'] ;
$address = $_SESSION['address'] ;

We have to start the session again on the page where you want to retrieve the session information. This will retrieve the session ID from the cookie on the user’s computer, and using that session ID, connect to the $_SESSION array for that particular user.

If cookies are disabled the session ID will be retrieved from information in the web URL. If sensitive user information is being stored, certainly an https encrypted connection should be used to prevent user information from being compromised.

Session variables are common in web applications, and are used frequently, especially internally, within a web application to pass variables from one page to another.

Moving inside your Application – Session Varaibles – An introduction

Posted by dale | PHP | Saturday 27 February 2010 7:34 pm

Our focus for this series of postings has been on the problems associated with getting information from one page to another in a stateless, Internet environment, where nothing is saved from one web page to the next. How do we pass the items you want to purchase from the form submission page to the shopping cart web page, for example.

To this point, we’ve covered passing user generated information to the server with forms using GET and POST, and how to use cookies to store temporary information on the user’s computer. These all involved, to some extent, user interaction.

We now will move on to passing data, variables, around the various files in your web application. This assumes you’ve obtained information from the user with a post, or get, or a cookie, or a call to the database, and have assigned that snippet of information to a variable name, like this:


//using the form GET method
$fname = $_GET['firstname'];

// using the form POST method
$lname = $_POST['lastname'];

// using cookie information
$city = $_COOKIE['usercity'];

// using a function to call the information from the database
$addr = getaddr( $username );

We’ll focus on taking variables, in this example: $fname, $lname, $city, or $addr to the next PHP file on the server, you’ll use to either display the variable, or use the variable in your application. Since php is a scripting, or interpretive language, when you open up a new file it stands on its own, and any data, or variables you’ll need, will have to be explicitly passed to that file. How we do that will be the subject of the next series of posts.

Since most modern languages use object-oriented software, and PHP, is no exception, we will eventually get to passing entire objects to other files and ways to persist objects in your application, but let’s not get ahead of ourselves, we’ll start with sessions and passing information with a session variable.

Opera and Firefox release new Browser Versions – a Review

Posted by dale | Browsers, Software | Friday 12 February 2010 6:02 pm

Opera has just released version 10.10, today, and Firefox recently released version 3.6. Currently of the popular browsers, Chrome is the fastest, followed very, very closely by Opera, and Safari, with Firefox coming before Internet Explorer, but way back from the rest.

Chrome is fast, but the interface is different with its top line tabs and Omnibox combined search and browser address window. It takes getting use to, and I have not been using it, because it was not stable initially.

Internet Explorer is way behind in browser compatibility and speed, and is an after thought in my mind. When and if Microsoft ever gets up to W3C standards, decides to use web standards for determining box widths instead of their proprietary method, and passes the ACID3 test, I might consider it, but not before.

Safari is fast, and it looks nice, but they do this by pumping up the luminance or gamma of their colors from all the other web browser colors, so the browser colors look sharper. Unfortunately, I can’t use their colors system for development when I’m building for all browsers. I’ll leave the Safari browser to Mac Users.

Which brings us to Firefox and Opera. I use Firefox about 70% of the time, mostly because of its web development plugin tools. There are three plugins I recommend for web development: Aardvark, Firebug, and Web Developer. I use all three. This makes Firefox unique as no other browser has these tools. Consequently, it is my web development browser of choice. Yes it loads slow as molasses, but everything runs fine once its up. I had to wait until the Aardvark plugin was ready, but now I’m up and running on 3.6.

What’s with 3.6? Firefox claims speed improvements in page loads, and it looks like this is true, it’s much faster loading both pages and booting, but still doesn’t seem up to the other fast browsers. Last release Firefox reached a 93 on the Acid 3 test, but rather jerkily. It now reaches 94 smoothly, still not 100. You now have type ahead in the address bar, which they call the “Awesome Bar.” Just start typing the site name and possible sites are gradually filtered to give you the correct URL. This is a rip off of the Chrome Omnibox, but there search capability is limited compared to Chrome. You now have one click bookmarks by clicking the star in the “Awesome Bar” window, and there are bookmark tags, like Delicious. Type a tag in the “Awesome Bar” and all your tagged items URL populate. This does not yet synchronize with your other Firefox browsers. They now have a Private Browsing option you can toggle. I’m skeptical of this, as Google keeps a complete record of all your browsing and your searches in its database. For looks, they have 35,000 personas which changes the look of the browser, to me this is just fluff.

And now to my favorite browser, Opera with its new 10.10 release. Opera is fast, and looks great. Only about 2% of the population uses it, so there is very little problem with malware, or virus attacks. It’s safe, secure, meets W3C standards, and passes ACID 3 quickly with flying colors. It’s a great browser. If it had the Internet tools of Firefox, I’d never look back and use Opera full time.

With Version 10.10 Opera claims five things that you can only do in Opera: Application sharing of data with others, compress web pages to load pages faster for people with slow data connections, visual tabs where you see a thumbnail of the web page, in addition to the text tag of the tab like in other browsers; customize your web page thumbnails in the speed dial window, synchronize your tabs, bookmarks, and other data with your other Opera browsers over the Internet. This is like Delicious in its synchronizing. Opera also has integrated themes for looks, and an integrated Opera mail program, although I admit, I prefer Thunderbird at the moment.

If you’re a die-hard Firefox user, you’ll like the improved Firefox speed and tags with the Awesome bar. If your not into web development, I highly recommend you download Opera and give it a test drive, check out the speed, convenient surfing tools, and overall good looks. Change the appearance in tools->appearance, drag the tag bar down to see the visual tabs, and enjoy Opera.

PHP Cookies – Passing Variables

Posted by dale | Browsers, PHP, XHTML | Saturday 6 February 2010 12:29 pm

Before we set some cookies, let’s look at the flow of messages and responses between your computer, and the server, where the web pages are stored. When you click on a link to go to a web site, your browser sends a “HTTP Header” request to the server for that web page. The Header message is variable in length and can get lengthy. The browser sends the HTTP Header, then waits for the server to send a “response header,” followed by the web page. How does the server know that the browser’s Header message is complete so it can respond? A blank line is sent at the end of the HTTP Header. The server when seeing the blank line responds with a “response header,” before passing the page.

Why am I going through this? Because the event that passes the communication baton from browser to server, and back again is a “blank line.” When you pass a cookie to a browser, it is attached to the server’s “response header”, but if a blank line shows up in the web page, before you tell the server to attach the cookie to the response header, you’ll get an error message, something like, “Warning cannot modify header information – headers already sent...” In other words, your command came late, the headers already gone. This can drive you nuts trying to figure out where the bug is in your code, if your not aware of what’s happening. The first thing you want to avoid is a blank line, or even a space at the top of the file before the PHP start tag.

The first step in setting a cookie is to tell the server to attach the cookie to its response header. This is done at the very top of the web page, before any blank lines, or “HTML” or “head” tags, with PHP’s “setcookie” function, like this:


<?php
setcookie( 'message_1', 'I am loaded and ready for bear');
?>

The “setcookie” function can take up to six parameters:

1. “Name”, the name of the cookie, a string, in this case: ‘message_1′ ;

2. “Value”, the value of the cookie, can be a string or number, in this case: ‘I am loaded and ready for bear’ ;

3. “Expire”, when the cookie should expire on the user’s browser. This is expressed in seconds, in linux system time based on seconds since January 1, 1970. I suggest you use a PHP time function, and add to it the number of seconds you’d like the cookie to be active in the browser, or use the browser default, since I’m using Firefox, the browser default is 90 days;

4. “Path”, the path on the server where the cookie will be made available. There’s a lot of files on the server, default is the current path;

5. “Domain”, the domain or url for which the cookie will be available. If you have multiple servers serving pages, on which server will cookie information be made available. The default is the current server.;

6. “Secure”, if you only want the cookie to be sent over a secure connection, like “https://”, set it to “1,” if it’s to be secured, the default is “0,” not secure.

Cookies exist in pairs, a name of the cookie, and its value. The other four parameters are usually not sent, the defaults are used. Normally, only two parameters are passed, name and value.

When your browser receives the cookie from the server it stores it in a set file location on your computer, depending on the browser. When you access that web site again, the browser, if there is a cookie available for that web site, attaches to to the HTTP Header it sends to the server. Cookies are a two-step process, you send it first to set the cookie, and then to get the cookie back you have to ask for the page again.

Ok, we’ve set the cookie in the first response header from the server, how do we get the cookie back from the browser. Well, the cookie, when it comes back, is attached to the HTTP Header, how do we read it? Assuming you’ve refreshed your browser, or asked for the page again. Here’s a block of code to do just that,


// Always check to see if the cookie exists,
// or was not deleted by the user
if (isset($_COOKIE['message_1'])){

   echo "The cookie is loaded: " . $_COOKIE['message_1'] ;
}

If the cookie exists and is set, this will echo: “The cookie is loaded: I am loaded and ready for bear

You also can set cookies in an array. Here’s an example with the cookie’s expiration time set to 10 days :


setcookie ( "myarray[one]" , "My " , time()+ 60*60*24+10 );
setcookie ( "myarray[two])" , "Funny " , time()+ 60*60*24+10 );
setcookie ( "myarray[three]" , "Valentine ", time()+ 60*60*24+10 );

To retrieve this array, we use a loop thus:


if ( isset($_COOKIE['myarray']) ) {
   foreach ( $_COOKIE['myarray'] as $note ) {
      echo $note ;
   }
}

And the output is: “My Funny Valentine“. And finally you can change a cookies value by calling setcookie() again, or delete the cookie by specifying a time in the past, thus: setcookie( “x”, “” , time() – 3600 ) will delete the cookie.

I mentioned cookies are public. Although, you can not look at them directly with a regular text editor, like notepad, and they can be encrypted, there are cookie management editors you can download to read cookies, and there are TCP/IP tools that you can use to watch the traffic go back and forth to a web site including the cookies with their names and values. Cookies can be useful, just be careful how you use them, and what information you store in them.

Cookies – an Introduction

Posted by dale | Browsers, PHP, XHTML | Friday 5 February 2010 2:25 pm

Cookies, cookies, cookies, we’ve heard about cookies now for many years, the perenial red herring, used like the threat of a nuclear bomb, to strike fear in the hearts of all who used a personal computer to surf the Internet, maybe not quite that forceful, but never in a favorable light. Cookies were started by Lou Montulli of Netscape in 1994, and they were first used by Netscape to see if a visitor had previously been to their site. Besides the Netscape browser, they were next supported in release 2 of Internet Explorer. Every browser since then has supported cookies. The general public first became aware of cookies early in 1996, and has been suspicious of them ever since then.

Cookies are bits of text information stored on your computer from a site you have visited on the Internet. They are stored in a different folder on your computer depending on what browser you are using, and if you surf the Internet a lot, you can amass quite a few of them. If cookies have such a bad reputation, one has to ask, why do all browsers support cookies?

Cookies offer web site owners and you several advantages. When your browser stores bits of text information from a web page on your computer, it allows the web site to know what page you’ve visited, and choices you’ve made on that page. For example, cookies can keep track what items you have selected in a shopping cart, and keep the list for you, even if don’t return to the site for a couple of weeks or even years, if the cookie is still on your computer. Another example is saving your login information so you don’t have to login every time you return to the site. If you have ever returned to a site, and gotten a “Welcome back, Frank” type of message, you can thank cookies.

For marketing cookies can be used to see what pages you have visited on a web site, the domain or page URL can be stored as you visit every page. Thus was born the often dreaded “DoubleClick” cookie, which can track your Internet usage from one site to the next site and gather a history of your web usage. Some consider this malware, adware, or spyware, whatever you want to call it, and they use programs to remove all the cookies on their computer to “protect” their PC.

And there lies some of the problems with using cookies to retain data. Although cookies are specifically linked to the user, his computer, and his particular browser, they are still, by many, considered to be malware, because they can pass your personal web usage history to marketing organizations, even though, it may seem anomynous, it’s still your history being passed. Cookies are not secure from others, which reminds me to warn you against putting any sensitive user information in cookies. They can be viewed by others.

Users delete cookies with cleaning and malware programs, or by disabling cookies in their browser, because of this, as a way to save information beyond the current session, cookies are unreliable for storing information, and inconsistent in storing information from one user to the next. Besides for marketing reasons, cookies are mainly used to retain user information on a current session. Instead, most websites require a user to log in, and by doing this, the user’s information is retained on the server, instead of on the user’s computer, a safer and quicker way to retain information from one web page to the next, especially for ecommerce.

Nevertheless, cookies can be useful, in retaining information about the user that is non-personal, like your favorite color, or the language you speak, and they can retain this information for a fairly long period of time, thus, they are still in use some 15 years later. Are purpose is to show how to use cookies to store information, which we’ll address in are very next post.

Ubuntu – The Terminal Window

Posted by dale | Linux, Ubuntu | Sunday 31 January 2010 12:04 pm

One of the things that separates Windows from Linux or Ubuntu, a Linux distribution, is the way the operating system handles the graphical user interface. Microsoft Windows is an integral part of the operating system. It is integrated with the operating system and at this point, Windows 7, you can’t operate the computer with out the Window’s graphical interface. To be fair, you can still get to the old DOS command line by typing cmd in the run window, but it’s more there for a link to nostalgia, than it is to do day to day operations. In a lot of ways, I miss the DOS command line, I was good at it. Alas, even some of the old DOS commands are missing, like fdisk, for example. That’s all done through the windowing system, now.

In contrast, Linux has two windowing systems, KDE, and the one used in Ubuntu, Gnome. These two windowing systems are independent applications, and more important, they run as applications, just like OpenOffice or a game would run.

Linux consists of a kernal, and another layer that runs user applications, and never the twain shall meet. The kernal uses its own memory space, and each application runs in its own memory segment. If an application needs to access a disk drive, it calls the kernal, the kernal accesses the drive, and passes the information over to the calling applications memory space. Because of this the desktop can crash, say from a video game that has a bug, and it will not bring the computer down. It will just shut down that application, which you can restart from the Linux command line.

In contrast, Microsoft integrates windows with the operating system. So if you have a problem with your video driver, the entire system crashes, and you have to reboot the computer. This is one of the reasons Linux is more secure than Windows.

I mentioned you can restart an application from the command line in Ubuntu. How do we get there?  In Windows, you type cmd in the run window, and you get a black window with the command prompt.  Ubuntu is pretty much the same.  From the Gnome desktop, in the upper left corner, go to Applications->Accessories->Terminal. You’ll find a nice black window pop up with a $ prompt. Welcome to the Ubuntu Linux distribution command line.

Bringing Up the Ubuntu Terminal Window

Putting an Icon on Your Desktop

As a digression, I am at the command prompt much more often than in Windows, so I put an icon on my desktop to bring it up quickly.  To put an icon on your desktop, go back to Applications->Accessories->Terminal, but instead of left clicking to bring up the window, right click, and your given a couple of choices. You can add an icon to the laucher panel, this is a tiny icon that appears on the top bar of your screen, like the current Firefox icon, or you can add the icon to your desktop.

There is another choice, of putting it in the menu, as a drawer, the equivalent of a folder in Windows, or a an actual menu item.  Since we’re making an icon for the desktop, we don’t need to put it in the menu, since it’s already there.  By the way,  if you would like to rearrange your menus, change the drawers, or remove some menu items, the menus are completely configurable.  Go to the Applications choice on the top menu bar, for example, right click and select “Edit Menus.”

Back to the terminal window, the terminal window gives you complete access to the Ubuntu distro,  i.e. the Linux operating system command line, and its plentiful commands, but that is the subject of another post.  As a teaser, I’ll give you a couple of commands to get you started.    Everything is in lower case, type “pwd” for print working directory.   It tells you where you are.  Type, “ls” to list the files in that directory, or better “ls -al” to get a long alphabetical listing.  Some things come from DOS.  Type “cd ..” for change directory  to move up one level in the directory structure, and or to go down, type the name of the directory , for example,  “cd home”  goes down to the home directory, that should keep you busy for awhile.  Have fun and enjoy Ubuntu.

And finally, less we get carried away, you can still explore your file system through the GNOME graphical user interface, like Windows Explorer, without using the terminal window or the command line, by going to the “Places” menu in the upper tool bar.

PHP Post – Passing Variables – Fun with Forms

Posted by dale | PHP, XHTML | Saturday 30 January 2010 12:21 am

In my last post, we covered the GET method, get is one of two methods used to get information from the client’s browser to the server, the other method being “POST.” You’ll find that “post,” by a wide margin, is the method used by developers, over the less secure, “get.”

The post method is used when you have a large amount of data in your form, and when you want to be more secure with the data, and not have it so visible, as with the “get” method.

Let’s have a little fun and review forms a bit, we’ll start with a form the developer might put on a page for the user to fill out in his browser window. Here’s the body of the html with the form.

Tell Us about Yourself

My favorite ice cream flavors are (pick all that you like): French Vanilla Chocolate Black Rasberry Vanilla Fudge Strawberry Cookie Dough Coffee What is your favorite pet? Dogs Cats Horses Parrots Snakes I don't like pets What is the make of the current car you drive: Tell us about your favoite hobby and why you like it:

And here is what the form will look like in the browser. I’ve filled in some example data in the form in the browser window for us to use in the next file. In this case the form action will send the form information to “formctrl.php” which we’ll will use to echo out the data.

Here is the php code, minus the php tags, we’ll use to retrieve the data in the “formctrl.php” file, and then, in this case, echo out the data to the screen. Notice that the syntax to retrieve the data is the same as we used for “get,” except we substitute the word, “post,” instead. The data variable in the post portion comes from the “name” tag in the form for each input method.

In the case of asking for ice cream flavors, we selected more than one choice, so we created an array by putting an [] after the name in he checkbox, called, “checkit[]” To retrieve the data from the array, we initialized an array variable in the next file, “$checked,” and then use a foreach loop, and go through the array one choice at a time to retrieve the choices.


$fname   = $_POST['fname'];                  // First Name
$lname   = $_POST['lname'];                  // Last Name
$checked = array();
$checked  = $_POST['checkit'];              // Ice Flavors
$radsel   = $_POST['radioselect'];           // Favorite Pet
$dropcar   = $_POST['dropdowncar'];      // Car
$note   = $_POST['notes'];                    // Comments

echo "And now let's check the data from the form.";
echo "";
echo "";
echo "Hello, Mr. ". $lname . ",";
echo "";
echo "Or can we call you, ". $fname ."," ;
echo "";
echo "What are some of your favorite ice cream flavors?";
echo ""; 

foreach ($checked as $ic ){
   echo "I like ". $ic ."";
   }

echo "";
echo "And what is your favorite kind of pet? ". $radsel .".";
echo "";
echo "";
echo "Thanks ". $fname.",";
echo "";
echo "Can you give me a ride?  ";
echo "What kind of car do you drive?";
echo "";
echo "Yes, a ".$dropcar .".";
echo "";
echo "Any thing more you'd like to say?: " . $note  ;
echo "";
echo "OK, What ever you say, Let's go! ";

And here is what the output of the above file will look like in the browser window.

I think from the above example you can see why “post” is the most popular method used with forms, the user’s data remains hidden until you specifically get the data in the next file.

We’ve covered passing the user’s information from his browser to a file on the server. We’ll next move on to keeping information about an individual user separate from another user, and retrieving it later.

Oracle acquires Sun

Posted by dale | Companies, MySQL | Thursday 28 January 2010 1:58 pm

Wow, this is big. It is no secret that Sun has fallen on some tough times lately. Sun had a total revenue of $11.45 billion last year down from $13.88 billion the year before. In contrast, Oracle’s last year revenues were $23.23 Billion. The combined revenues of both companies should approach $35 billion. Microsoft currently checks in at $56.3 billion. We’re looking at the heavy weights going at it. With Microsoft on the decline, Google at $23.65 billion on the rise, and now Oracle stepping up into the fray, this may become a very interesting war. Oracle acquired Sun for a mere $7.4 billion, a steal.

Oracle’s revenue comes from it’s pervasive Oracle database. Depending on how you look at it revenue, or installs. Oracle is in the top 2 with Microsoft and IBM’s DB2 a close third. Let’s not forget, MySql is the most popular Open Source, i.e free, database in the world. What is surprising is when you look at installs and the number of developers developing with a database, MySql comes in a close 3rd to Oracle and Microsoft, with DB2 fourth, and MySql shows the greatest growth rate of all database development.

Oracle’s acquisition of the MySql product may be a problem for the Open Source community. Sun owned MySQL, which now belongs to Oracle. If you remember, Oracle purchased PeopleSoft in Dec. 2004 for $10.3 billion. In Oct, 2005 they acquired Innobase which is an integral part of MySql for transaction processing and foreign keys. What will Oracle do with MySql has caused a huge concern with the Open Source Community, so much so, that their already has been several forks of MySql, Drizzle, and MariaDB, just in case Oracle starts charging for MySql. For now, Oracle pledges to leave MySql independent, but this is to be expected in the initial stages of an acquisition, things usually change in six months or so.

My thought is they will continue to support an Open Source MySql and build on top of MySql additional tools, extensions, and integrations with other Oracle products with, of course, a clear upgrade path to Oracle’s flagship products for which the enterprise users will pay dearly.

And the same for OpenOffice.org, a legitimate contender, now, of Microsoft Office. Oracle has never had an Office Suite and has wanted one. Oracle is built with Java, as is OpenOffice.org. Again, tools, extensions, and integrations with Oracle products seems like a nice way to get users to start paying for more and more functionality from a previously non-existent Oracle Office Products.

Oracle keeping the Open Source products they have acquired free, and enhancing them, at first, to gain market share seems like good business sense, but as these applications gain more and more market share, I believe Oracle will take a page from Microsoft’s play book, and start charging for their enhancements to the products. What this means for Open Source, is a freezing of the Open Source components to a minimal feature level, and if you want more, pay for it.

I have great faith in Open Source software, the forking of MySql is evidence that independent Open Source Developers will continue to create other applications with the missing functionality, that Oracle will ask customers to purchase. As MySql has emerged as the premier Open Source database, so other products can, and will, emerge to take its place, if Oracle begins to get as “bean counterish” as Microsoft is currently, with it prideful boasting about “Microsoft Genuine Advantage,” and its publicly crowing about the number of companies they have sued, look for any closing down, of previously Open Source Oracle products to be a catalyst to breed a new generation of improved Open Source products.

PHP Get – Passing Variables – Get it!

Posted by dale | PHP, XHTML | Wednesday 27 January 2010 1:46 am

Last post we talked about how we normally get data into a system with a form. The user enters his information into the form and clicks the submit button. The browser then sends the data to the server.

Back at the server, php sets aside some memory, the server stores the information in that memory location, and calls the next page. That page is what the developer specified in the form command.

Here’s the form again:

In this case, the action parameter tells the server what file to go to next, controller.php.

The more interesting questions are how the browser passes the information to the server, and how the controller.php file gets that information out of memory. Those questions are answered by the method parameter in the form tag, in this case, GET. Get is one of the two methods you can use to get data from the browser to your program file.

The GET method tells the browser to package the site and form data as part of the URL sent to the server calling the next page. For example, if we go to the W3C site at http://www.w3.org/ , and in the Google search box on the right side type, “CSS,” click the magnifying glass, and look at the URL at the top of the page.

You’ll see: “http://www.google.com/search?q=site:w3.org&q=css&search-submit=” The browser packaged the site “w3.org”, the variable data, “css,” and the variable, “search,” into the URL after the “?”

Now, to get this information into the controller.php file with use the php $_GET method.

And here’s how you get the data into the controller.php file:


$searchinfo = $_GET['searchit'];

Notice how the name parameter of the input tag, searchit, is the name of the variable we use to GET the information back out of memory.

if we echo the variable we just created, $searchinfo ,


echo "The search word is: ". $searchinfo;

The answer we get is:


The search word is: css

We’ve passed the data from the form input page to the controller.php page.

Now some thoughts. The best place to use get is with queries, as shown above, not when your passing sensitive information, like your social security number. Why? For obvious reasons, all your information is in the URL for anybody to see. GET is not secure, but for a search box, it’s fast and easy.

Another thing, the URL has a maximum size. Surprising it is mostly set by the browser you use, Internet Explorer is 2048 characters, Firefox is 65,536, Safari is 80,000 and Opera in 190,000. Nothing to really worry about, but its best to keep the “Get” method to short queries back to the server. Get gets a bad rap for messing up the URL line, and putting the data out there for everyone to see. It’s not used that much, except for search queries, mostly form data is posted, which we’ll talk about next.

HTML Forms – Passing Variables – Creating Data with Forms

Posted by dale | PHP, XHTML | Friday 22 January 2010 11:12 pm

We can’t pass data to another page until we have some data.  The way we  input data in web pages is with forms.  Forms are created with html, more easily created with html then styled in CSS, but that’s another article.

Forms are created with the <form> tag, and of course, the form ends with a </form> tag.  Form is a block element.  Any submitting elements between these two tags are processed as being part of the form.

Let’s create a form with some input elements as an example of proper html syntax:




Pencil: Notebook: Textbook: Pack:
Cauleflour Brussel Sprouts Black Beans

The above code yields a form that looks like the image below in your browser (click to enlarge image).

You fill in the form on the web page, click the, “Click me when the form is filled out!” button, and the data you entered into the form is sent to the file “../controllers/example_controller.php” which you specified in the action parameter in the opening form tag.

Some notes on the form itself, I included a hidden field not displayed in your browser window.  Now don’t get excited about secret codes, or something evil you could pass in to the site, because this is not secure.  All you have to do is View->PageSource in your browser, and you can see the “hidden field” value. It is not used a lot because of this, but it can be used if you want to pass some data to another page when the form is submitted that would not be normally obvious to a user.

You’ll notice that each type of input has a “name” tag. The “name” tag is important, it’s how you identify the the data that is coming to the next page.  For example, the name of the first input box is “firstname,” when I get to the next page, I’m going to ask for “firsname” when I want the contents of that input, Which brings us to the topic at hand, passing data to another page.

We can pass form data to the, “../controllers/example_controller.php” file in one of two ways either “Get,” or “Post.”  The method we use to send the data is a parameter in the initial form tag, like so, method = “post,” or method=”get”  We’ll cover this in our next article.  For now, in our initial web page we have collected the data, when the user clicks on the submit button, we pass the data to another page or file.  And we’ll talk about what the receiver file has to do to catch the data in our next article.

Passing Variables – An Introduction

Posted by dale | PHP, XHTML | Friday 22 January 2010 12:28 am

This is the start of a new series of articles on passing variables.  A series about coding web pages with PHP.  PHP is an interactive, interpretive, scripting language that works well with HTML to communicate with the database, and create dynamic applications for the Internet. As such this series will combine HTML and PHP to accomplish varies tasks.

The focus will be on passing variables.  Why passing variables?  Because the Internet is stateless.  By stateless, I mean that every request going to the Internet server is independent of any other request.  The Apache server delivers a web page from the server to the browser on your computer, and when you click on another link, probably a new server will deliver another page. The servers could be physically located half a world apart.  How do we move data from one page to the other when each page stands on it own?  The new page that loads, does not know anything about the preceding page, unless of course, you pass some informaton from the one page to the other.

And that’s where the problems start.  If I assign a variable on one page, that variable ceases to exist in the new page.  It’s gone.  Variables only persist while in an individual page.  If I type in my name on an Internet page, how does the new page repeat my name back, like Amazon does when you log in?

Well, that’s a good question and the subject of this series.  By passing variables, I mean passing data, whether its your name, or phone number, or the results you entered in a survey from one web page to another, or from the web page to the database and back to another web page.  We’ll focus on “Passing Variables,” getting data moving around your system.

“Passing Variables” probably causes more problems in coding than any other issue.  You pass the data a user fills out in a form, back to a “controller” file.  This takes in the information, and assigns the indivual data to variables or an array.  The information is validated and if there is an error, an error screen will be called, if the data is ok, We can pass these variables back to a “model” file for saving in a database, again passing variables between pages.

The next page comes up, calls a function to get the informaton out of the database, passes the data back to the new page, the new page shows the same form with the information you filled in the form populated in the form.  The form page you filled in is a different page then the page that had the blank form you initially filled out, with perhaps an error message, saying a field you forgot is required.

We will cover some HTML and more PHP.  Topics I hope to cover are: Forms, Get, Post, Cookies, Sessions, function variables, returns, arrays, and passing objects.  As far as syntax, we will eliminate any extraneous html or php that is not necessary to make our point. You’ll see no div’s, or ul’s. or li’s.  We assume you know what needs to go else where in the page to make it work, and are reading the post, because you just need that snippet of code to make it work.  We definitely want to make the page an easy reference when your stuck to quickly look up the right code sequence and syntax, and you just want to know how to do that…

And with that…we’re off…

Changing the Ubuntu Desktop

Posted by dale | Installing Software, Ubuntu | Tuesday 19 January 2010 10:44 pm

By now you are familiar with the initial installed Ubuntu background.  When you use a computer every day, you know that after awhile you want to change the appearance of your computer, just as a change of pace.  Ubuntu has not forgotten the aesthetics, and gives you just as many choices as Windows.

The Initial Ubuntu Background

For those Windows users, Windows calls their background the desktop, and the way you change the picture on the desktop in Windows is to right click on the desktop, and bring up the properties menus.  In the properties menu you can change the theme and sounds, the desktop picture, what you use for a screensaver, the appearance of menus, and the screen resolution.

Let’s see what we can do with Ubuntu.  Just like in Windows, right click on your desktop, and there you will find a “Change Desktop Background,” menu,  left click, and up comes “Appearance Preferences.”  You’ll find 22 backgrounds you can choose from, or if you click the “Add” button you can use any of your pictures.  You can also down load additional pictures from Gnome Art.  Remember Gnome is name of the Graphic User Interface that Ubuntu uses.  This site has a bunch of additional themes and backgrounds that are easily downloaded and installed by clicking on the “Get more backgrounds online” link.

A New Background

Through the upper tab menus on Appearance Preferences,  you can change the theme, by changing the look of your: controls, colors, window borders, icons, and mouse pointers. Not only that you can change the fonts that are used along with the size of the fonts for menus and documents from the fonts menu. If your eyes need a little bit bigger fonts it’s no problem to adjust them here.

Font Preferences

There’s one other thing you may want to change, and that is your screen saver.  To change your screen saver in Ubuntu, go to the “System” menu in your upper left menu, click on “Preferences” and then “Screensaver.”  This is also where you can configure Ubuntu to go to “sleep” after a period of inactivity or just to shut the display off.  This is under the “Power Management” menu in “Screensaver Preferences.”

Screensaver Preferences

In summary, you can change the entire look of Ubuntu, and make it your own with a few clicks of the mouse.

Printer Drivers for Ubuntu

Posted by dale | Hardware, Installing Software, Software, Ubuntu | Monday 18 January 2010 8:04 pm

Ubuntu comes with drivers for most of your peripherals, except printer drivers, which normally are installed separately.  In a previous blog I have written favorably about the Canon MX850 compared to the equivalent HP ink-jet all-in-one printers.  Having a good feeling about Canon, I went to their web site and made an email inquiry about a printer driver for Ubuntu.  Here is their reply, “While considering the desire to provide the best possible support for Canon’s products, Canon must make decisions on which products to support when new operating systems are introduced.  Currently, Canon has decided to support only the Microsoft Windows and the Macintosh operating systems.”

Pardon me, Canon, but Ubuntu and Linux are not new operating systems.  They’ve been around almost as long as Windows, and the Apple operating system is based on Linux.

Have no fear, though, this happens occasionally and what you’ll find when you go looking for a solution is other solutions.  Searching further, for Canon printer drivers, there is a free solution, the CUPS-BNJP Printer Driver, which mimics the Canon BNJP printer protocol for the Canon Pixma printers and works over the network. This also works with the XSane scanning software provided with Ubuntu to allow scanning of documents.

CUPS-BNJP is based on CUPS, CUPS works with other printers besides Canon.  It was built for the Fedora distribution of Linux.  Since Ubuntu uses the Debian distribution, there may or may not be an issue in using CUPS with Ubuntu.  We can check that easily.  If you go to Applications->Ubuntu Software Center->Get Free Software->System Tools and scan through the list of available software, you’ll come to two choices: Printing, Printers.   If you click on “Printing,”  a CUPS printer driver is available.  “Printers” on the menu system gives you a GUI interface between CUPS and the printer.

CUPS uses your web browser to view print jobs, manage your printers, and for online help.  However, it makes use of the command line for its configuration.  The printer GUI in the Ubuntu Software Center. according to the software description,  seemed like it depended on some other software for configuring remote printers on a LAN,  if you don’t want to install a series of dependent software, or if you prefer not to use the command line interface, you probably want to check out a commercial solution, TurboPrint 2 for Linux.

TurboPrint 2 supports ink-jet printer’s from: HP, Bother, Epson, and Canon for all Linux distributions.  For the modest cost of $29 you can be ensured that you printer will function, and pick up a nice set of additional features with the software.

TurboPrint2 features include: high print resolutions, color management that matches screen document color to printed color, printer status monitoring to track print progress and errors, like a low ink cartridge, printing on both sides of the paper, print preview of what your about to print, and intelligent ink management to save ink and extend cartridge life. The one remaining question that I had is will it work on a printer attached to your network, and it will.  This intelligent printer utility has Windows and individual manufacturers printer drivers beat hands down.

The company provides a trial version to see if it will work on your system. You can download from the web and hook it up and if everything works, then purchase the software.  What’s not to like!

Given I was not sure about the Cups-BNJP distribution with Ubunutu,  the GUI configuration tool appeared to need additional software to pick up my printer on my LAN,  which meant there may be some additional configuration issues beyond just downloading the software, and  a free trial of TurboPrint was available, I decided to go with the TurboPrint option and give it a try.

TurboPrint Control Center and Printer Monitor

I downloaded the correct distribution for Ubuntu from their website. Clicked on the install button, the install wizard came up and installed the software.  The installation was painless.  The only thing that made me pause was the request to add a printer before other functionality was available.  This is done with the “Add” button in the Print Control Center.  My model Canon was recognized immediately on my LAN and that was it.  I printed a test page, checked the level of my ink cartridges, and was suitably impressed.

Considering I didn’t have to read any documentation, install several pieces of software,  or potentially do a command line configuration of the printer.  I was up and running in 5 minutes,  and had some one to turn to for support if any problems cropped up, it certainly is worth the $29 asking price for Turbo Print to me,  so much for printer drivers.

Next Page »