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

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…

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.

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.

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.

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.

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.

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.

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.

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.

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.

Multiple Drop Down Choices in a Form

Posted by dale | PHP, XHTML | Tuesday 11 August 2009 12:27 pm

One of the most common things done on a web page is to use a form to gather information.  We have all filled out online forms where your home “State” is asked for.  This is usually presented to you as a drop down list of all our states.

The advantage of doing it this way for the developer is he can make sure he gets the state information in a format that he would like.  That is, he may want the information to come back as MD, or, a number like ‘13′, or the full name, Maryland, for example.  The drop down selection box forces the form submitter to make a choice that the developer can then format anyway he likes with less chance of having bogus information entered.  A win-win for everyone.

The drop down box is put up inside a form block in XHTML with a select tag followed by a listing as a series of option tags corresponding to each option you would like in your list.  Here’s a car type example:

<select name=”car_type” size=”5″>
<option value=”1″>sedan</option>
<option value=”2″>hatchback</option>
<option selected=”selected” value=”3″>coupe</option>
<option value=”4″>suv</option>
<option value=”5″>hybrid</option>
</select>

This puts up a nice neat drop down box with the selections you specified in the options.  Some explanations:

VALUE.  The value within the option tag is the value that will be returned when the form is submitted if that option is chosen.

SELECTED.  If you would like to display a choice in window of the drop down box, use selected with the option you want to display in the form.   In the example, coupe will show up in the drop down box window.  If you don’t use selected, the default is the first option displayed in the drop down box.  If you want nothing in the window, then include a blank option tag at the top of the list of options.

There are several choices you can specify with the select tag: name, size, disabled, multiple.

NAME. Name is the name of the select box. This is used to identify that particular drop down box when your retrieving the information from the form in another file.

SIZE. Size is the number of options you would like to make visible at one time when you press the drop down arrow.  Do you want to display all 52 states, or display 6 and make the user scroll to get other state names?

DISABLED.  Disabled is used when you want to show your choice, but not allow your user to select a new choice. It displays the previous choice, but disables and “grey’s out” the control so it can’t be used.

<select disabled=”disabled” name=”state” size=”6″>

MULTIPLE.  We use this if we want to be able to select more than one choice in the drop down list.  For example, you have a list of names and want to include a small group to form a sub-group of names.

<select name=”state” size=”6″ multiple=”multiple”>

The drop down box is used a lot, because it takes up less space in the form than if we put up a series of checkboxes, where all your choices would need to be displayed in the form.

What happens behind the scenes?

When the user clicks submit after, hopefully, filling in the form drop down box, the program “posts” the forms information in the page specified in the form “action.”   In this case, “http://www.mypage.com”  You retrieve the form information on that page with a statement like this in php:

$car_type = $_POST['car_type'];

If the information is a multiple select drop down, you tell the select tag in the form that this is multiple select in two ways, with the tag multiple=”multiple”,  and also in the name with a [], to signify this is an array of the user’s choices,  like so:

An array of data
<select name=”car_type[]“  multiple=”multiple”>

This becomes an array in the form returned to php with all the drop down choices in the array, like this:  $cars = $_POST['car_type'];   In this example, the variable $cars is an array containing all your choices in the multiple drop down box.

PHP 5.3 new release

Posted by dale | PHP | Sunday 2 August 2009 12:19 pm

The new PHP textbooks being published are all trying to get a jump on the competition by talking about what we can expect in PHP 6.  PHP is the quietly taking the Internet by storm as the free open source, object-oriented, language of web development.

With that backdrop, the PHP development team quietly announced the release of PHP 5.3 on June 30, 2009 with no specific date for PHP6.  What are some of the new features in PHP5.3?

Although touted for PHP6, PHP now supports namespaces.  Namespaces allow you to group classes and variables in their own named area.  This helps with problems of duplicate naming causing bugs in large projects with multiple developers.

Of significant note, a MySQL native driver arrives to replace the MySQL Client Library.  This does not mean yet another MySQL API to learn, as it still uses PDO MySQL and MySQLi, but it has now become a part of PHP, instead of part of MySQL.  MySQL calls are now directly compiled with the MySQL Native driver instead of the MySQL Client Library.   This is more efficient by using the PHP Memory Management.  Before, each row retrieved from the database had to be stored twice in memory, once by the MySQL Client Library and once by PHP memory manaagement.  Now with the native driver, it only needs to be stored once. It also means that you can use PHP database calls without actually having MySQL installed.  This allows connections to become more persistent.  Added functions include a new mysqli_fetch_all() function which returns all rows of a query at once, as well as new statistical functions.

Some other features include: improved Windows support, late static bindings, garbage collection for circular references, and better MIME support.  There are over 140 bug fixes and overall improvements.  Compatiblity with the older PHP4 has now been dropped.

So what’s still on the plate for PHP6, when it comes?  Full internationalization unicode UTF8 support.  Along with that, removal of the ereg regular expression extensions.  This further supports internationalization with regular expressions, and as an aside, it will help to cut down on some of the regular expression confusion, as to which extension to use.  Along with this we will see the disapperance of register_globals, magic_quotes and safe mode; and improved caching.