Browsing articles from "October, 2008"
Oct 31, 2008

starting and stopping a session

when developing web apps, many times the application at hand involves needing the user to log in to use the app. this works especially well when, let’s say, the app needs to load information based on who the user is. one way this can be done is to check who the user is on every page and load the information when the page is served. this might work on smaller apps but what if the application is a social networking tool with a coupe hundred thousand members. if too many people are logged in and clicking around at once, the app will be generating far to many database connections, or bloating the server severely. instead, i prefer to load the information that i will require for the duration of the user’s experience into session variables that will remain in tact as long as the user is logged in.

to do this there are 3 basic steps: 1) begin the session; 2) load the data you will need into variables that will remain in place; 3) destroy the session when the user is done so the next person does accidentally, or maliciously, use the previous user’s info.

starting a session in php is rather easy. it can be executed with one simple command:

session_start();

that’s it! typically i start the session as the very first line in my code. once the session has started you can then assign the session variables. the $_SESSION variable is a global array that contains virtually as many pieces of data as you might want. simply attaching a key to the session variable and assigning it a value will set it. lets say i want to store the time the session started:

$_SESSION['start_time'] = time();

just place that code on the very next line after the session is started and the value returned from time(); will be stored in $_SESSION['start_']. pretty simple right?

now lets get a little more serious. lets create something useful. lets say a user is logging in and you want to load that user’s info and maintain it throughout the session. lets assume the user fulled out a form where the fields were named username and password and that user information is stored in a mysql table named user_profiles. the code might look something like this:

session_start();
if ($_POST['username']) {

	$username = $_POST['username'];
	$password = $_POST['password'];
	$sql = "SELECT * FROM user_profiles WHERE username = '$username'";
	$result = mysql_query($sql);

	if (!$result) exit('no such user');
	$row = mysql_fetch_assoc($result);

	if ($row['password'] == $password) {
		$_SESSION['user_id'] = $row['user_id'];
		$_SESSION['username'] = $row['username'];
		$_SESSION['first_name'] = $row['first_name'];
		$_SESSION['last_name'] = $row['last_name'];
	} else {
		exit('incorrect password');
	}

}

here we have checked the user’s username, if the user exists we then check if the password matched the one on file. when that checks out, we set a few session variables that will remain in place for the duration of the session. any time we want to reference the user’s first name we simply reference $_SESSION['first_name'] rather than looking it up again.

to end the session you will use a few php commands: 1) identify the session you want to end; 2) unload all the session variables; 3) end the session. let’s say our user just clicked on a ‘log out’ button, the code might look something like this:

session_start();
if ($_POST['logout']) {

	$_SESSION = array();
	session_destroy();

}

notice i used session_start() again. whenever it is used it will either start a new session or refer to the current session. if we had multiple sessions open at once we would want to refer to the session’s name inside the parentheses: session_start('my_session')

that’s pretty much it. you can see how using sessions can come in handy and how using them in conjunction with database driven applications is almost a must to reduce server bloat.

Oct 29, 2008

using the XMLHttpRequest

with all the emerging web applications out there, ajax has come overwhelmingly popular as a means to have active content on a page update without the need to re-load. one of the easiest way to achieve this is to use the XMLHttpRequest.

i have stated before that i am not an advocate of writing browser detection scripts since it makes more sense to check for the appropriate method when carrying out a task. in order to achieve this with the XMLHttpRequest is quite simple: write a function that attempts to create an XMLHttpRequest a number of ways and returns the results on success or an error on failure.

the function:

function new_request() {

	if (typeof XMLHttpRequest != "undefined") {
		return new XMLHttpRequest();
	} else if (typeof ActiveXObject != "undefined") {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		throw new Error("XMLHttpRequest not supported");
	}

}

simple enough right? now whenever you need to make an XMLHttpRequest a few lines of code will get the information you need

using the function:

var url = "/my_file"; // the path to the file you want to use
var request = new_request();
request.open("GET", url, true);
request.onreadystatechange = function() {
	if (request.readyState == 4) {
		// the code you want to run when the file/data is loaded
	}
}

XMLHttpRequest can return two forms of data: xml dom object and text. this means, depending on what you ask it to do withing the request.readyState == 4 statement, you will be given a certain type of data. if you are simply making a call to a text file that contains a paragraph and you want to display that paragraph you would use the following code:

var txt = request.responseText

while this can be usefull if you have many small txt files that make up the content of a page, i feel it is infinitely more powerful to store the same data in an xml file and just traverse the file to get the data you need from it. to do this you would use the following line instead:

var xmlDoc = request.responseXML

this would allow you to work with the xml dom to pull values out of the file as you need them. so the full code to bring the data in would be the following:

var url = "/my_file.xml"; // the path to the file you want to use
var request = new_request();
request.open("GET", url, true);
request.onreadystatechange = function() {
	if (request.readyState == 4) {
		// the file will be read in as an xml dom object
		var xmlDoc = request.responseXML;
	}
}

you can now traverse the xml dom object to get whatever data you need out of the file. i will be writing instructions on how to traverse the xml dom in another post so this is where i will end.

Oct 29, 2008

adding data to a sql column value

i came across an interesting challenge the other day that i found a rather simple solution to.

i was trying to update a SQL table to add information to the end of a column value. i simply wanted to add some text to the end of what was already stored there. i will be honest, i dont consider myself to be a mysql expert by any means and my first approach was to bring the data into php, add the extra text and then update the table.

wrong way:

$new_data = "some value";
$sql = "SELECT * FROM table WHERE id = 1";
$result = mysql_result($sql);
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
$new_col = $row['column'] . $new_data;
$sql = "UPDATE table SET column = $new_col WHERE id = 1";
$result = mysql_query($sql)

with the use of mysql’s CONCAT function this can be simplified into much more efficient coding.

right way:

$new_data = "some value";
$sql = "UPDATE table SET column = CONCAT(column, $new_data) WHERE id = 1";
$result = mysql_query($sql);

thats it! 8 lines of code reduced to 2 lines. gotta love taking advantage of built in functionality!

Oct 22, 2008

cross browser getElement function

in the ever changing world of browser warfare it seems as if the may never be a completely universal way of developing web applications. i’m constantly having to find ways to carry out a particular task that will yield the same results on all browsers. one such task is getElementById. until we can safely say that every web browser out there will perform the same task, or even recognize is, we need to determine what action we really need to take.

i am not an advocate of writing blatant browser detection scripts and then writing subsequent code based on what browser is detected. its poor coding, and it can get extremely too messy very quickly. instead i prefer to write specific functions that attempt to perform the task at hand a few different ways until the right way is determined. it makes the flow of the overall program much more logical.

the function

function getElement(target) {

	if( document.getElementById ) {
		object = document.getElementById(target);
	} else if( document.all ) {
		object = document.all[target];
	} else if( document.layers ) {
		object = document.layers[target];
	}
	return object;

}

how to call

var object = getElement("myId");

the function simply checks which method works, and returns the object. simple. so no matter what browser is being used, a simple call to getElement will return the correct getElementById results.

Oct 22, 2008

cross browser event handler

on my most recent project i needed to create event handlers to control actions taken when certain things were clicked on. in my case it was a multi-tiered navigation menu, but this has so many amazing applications like context (right-click) menu’s etc.

catch the event
first i placed javascript in the of document to capture the onmousedown event (onclick is not as cross browser friendly) and set it to perform a function i called eHandler rather than take the usual action.

<script>
<!--
if (window.addEventListener)
document.addEventListener('click',eHandler,false);
else if (window.attachEvent)
document.attachEvent('onclick',eHandler);
-->
</script>

the eHandler function
next i wrote the eHandler function to perform various tasks depending on what was clicked. this comes in handy if you want to have different task performed depending on what is clicked.

function eHandler() {

	// get the event
	if (!e) var e = window.event;

	// cross browser method to get the element that was clicked on
	if (e.target) elem = e.target;
	else if (e.srcElement) elem = e.srcElement;

	// get the element's id
	var elem_id = elem.getAttribute("id");

	// catch right clicks, rightclick is a boolean
	if (e.which) rightclick = (e.which == 3); // old netscape way
	else if (e.button) rightclick = (e.button == 2); // modern way

what we have so far
at this point the function now knows what element was clicked on, that element’s id, and whether the user right clicked or not. from here we can add various check and carry out various task with the given information. for example, lets say if the user clicks on the element with the id “myMenuButton”. we can either: display the menu for a normal click OR display that element’s context menu for a right click.

	if (elem_id == "myMenuButton") {
		if (rightclick) {
			var c_menu = document.getElementById("cMenu")
			c_menu.style.display = "block";
		} else {
			var my_menu = document.getElementById("myMenu")
			my_menu.style.display = "block";
		}
	}

return false
finally we want the function to return a value of false to suppress whatever action the browser wants to take from the click action. this is a good way to disable the browsers built in context menu

	return false;
}

the whole function

function eHandler() {

	// get the event
	if (!e) var e = window.event;

	// cross browser method to get the element that was clicked on
	if (e.target) elem = e.target;
	else if (e.srcElement) elem = e.srcElement;

	// get the element's id
	var elem_id = elem.getAttribute("id");

	// catch right clicks, rightclick is a boolean
	if (e.which) rightclick = (e.which == 3); // old netscape way
	else if (e.button) rightclick = (e.button == 2); // modern way

	if (elem_id == "myMenuButton") {
			var c_menu = document.getElementById("cMenu")
			c_menu.style.display = "block";
		} else {
			var my_menu = document.getElementById("myMenu")
			my_menu.style.display = "block";
		}
	}
	return false;

}

summation
its easy to see just how many possibilities event handlers really have when applied properly. combine this with some crafty AJAX and you’ve gone some serous web app potential at your fingertips.

Oct 10, 2008

document word replacement

while working on a contract recently i came across an issue that involved word replacement on pages throughout the site. the client wanted the ability to use a global variable that would represent the total number of subscribers to the site. that variable would then automatically be replaced be the actual number. however, the CMS that i constructed for the client involved a WYSIWYG editor (tinyMCE) and would not allow PHP to be inserted into the text. my solution was to combine php, mysql and javascript in a way that would replace a specific tag withing any page.

for the purpose of this example, let’s say all page content loads in a container div with the id=’container’ and that all text elements within that div are contained in ‘p’ tags. start out by writing a javascript function to replace all instances of the tag within the container p’s:

function globals(txt) {

	var page = document.getElementById("container");
	var p = page.getElementsByTagName("p");

	for(var i = 0; i < p.length; i++( {
		var x = p[i].innerHTML;
		if (x.indexOf('[subscribers]' >= 0) {
			x = p[i].innerHTML.replace("[subscribers]",txt);
			p[i].innerHTML = x;
		}
	}

}

then bring in the data from a table containing the global vars:

<?php
$sql = "SELECT * FROM globals_table WHERE ref_name='subscribers'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
?>

finally add a call to the function at the bottom of the page:
(here i combine javascript with shorthand php)

<script type="text/javascript">
<!--
globals('<?=number_format($globals['subscribers'])?>');
// -->
</script>

thats it! now whenever a pages loads, the global ‘subscribers’ value is brought in from the database. and send to a javascript function (via php) that will loop through all <p> tags inside the container div and replace any instance of “[subscribers]” with the actual number