Mcloide's resources library

All about PHP, Javascript, concepts and development

Posts Tagged ‘PHP’

Face detection with PHP

Posted by mcloide on November 10, 2009

digital face @copy bitsys.gr

Today checking my daily Tweets for development I have found a very good tutorial about face detection using the GD library from PHP.

Karthik Tharavaad have developed a class that will allow you, with very little commands, to detect a face in a photo. As shown on the end of the post, it works well.

More at the post: @Karthik Tharavaad – Face detection with PHP

Post source got from Twitter: @planetphp

Posted in PHP, development, resources | Tagged: , , , , , , , | Leave a Comment »

PHP Basic Series – Session Handling

Posted by mcloide on October 8, 2009

A session, a lasting connection between a user agent (user browser) and a server application (web application, site, etc) have a very short time life just like a cookie therefore it caries all the information necessary to the application to communicate between all of its parts.

The lasting connection, a true characteristic of a session, is also the reason why is important to take a very careful look at how the session works and how to increase its security.

In order to facilitate things and understanding of session, consider the session as a cookie holds an array and it is stored at the server while the application is being executed (or until your browser closes).

In PHP a session can be either stored in the filesystem or in the database. Either choice of storage has its pros and cons regarding security but in the overall both work in the same way. Consider the previous example: The login form. Once the user connects correctly logs into the application is necessary to keep the username / password or username / logged state so all parts of the application understands that the current user has correctly logged at some point and will keep like that until he decides to logoff.

To correctly construct that scenario the first thing to be done is to set the session. With PHP, unless you specify it, a session will not be started. There are 2 ways to start a session:

  1. You open the session on every single script of your application using <?php session_start(); ?>
  2. You open it only once, at the application bootstrap, and includes the bootstrap in every step of the application

It might seem that both are the same, therefore the second option is by far more clean and secure.

bootstrap.php

<?php
session_start(); // the session start must be the first thing of every script. If any header or even an echo is done before the session start, it will break
// Adding some security to avoid session fixation attacks
if (!isset($_SESSION['sinit'])) {
session_regenerate_id(); // this will give the session a new identifier and keep the current session information
$_SESSION['sinit'] = true;
}
// the bootstrap file is also a good place to start libraries such as ob_start and to define your constants that will be shared all over the application
// since it’s a full php file, with no HTML coding (or any other coding), there is no need to close the PHP open tag

At the bootstrap the application now have the session instantiated and also have a small security that checks if the sinit (session initiated) session variable has already being set and otherwise it will regenerate the session identifier keeping the previous data. This will help your application to prevent from the most usual Session Fixation attacks.

The bootstrap is prepared and the next step is to include the bootstrap on the login script. The bootstrap will add the initiated session on the login script and the application will be able to use the session to hold the login information from the user, so it can be used in other parts of the application.

login.php

<?php
include_once(‘bootstrap.php’); // getting the instantiated session and variables

if (isset($_POST['doIt'])) {

// initiating the session variables that will hold the logged user information
$_SESSION['username'] = null;
$_SESSION['logged'] = false;

$username = $_POST['username'];
$password = (int) $_POST['password']; // casting the password so it can be converted to a integer since everything on a post variable is, at first, a string

if ( (!empty($username) && is_string($username) && $username === ‘myUsername’)
(!empty($password) && is_numeric($password) && $password === 123456789)) {
// for now let’s use a hardcoded username and a hardcoded password just to exemplify the process
// the username and password is correct and the user is correctly logged on. Now is necessary to tell the remaining parts of the application.

$_SESSION['username'] = $username;
$_SESSION['logged'] = true;

header(‘location: userProfile.php’);
}
?>
<html> ….

With the code snipped above the application now holds the information that the user myUsername is now logged and there is no more need to requested for the user to login or force his logout.

This code would not make much sense if we don’t use it in other parts of the system. Let’s add on this little application 2 more sections, the user profile and a logout page to clean the session.

userProfile.php

<?php
include_once(‘bootstrap.php’);

if (!isset($_SESSION['username']) || !isset($_SESSION['logged']) || !$_SESSION['logged']) {
// checking if the user is logged, otherwise, redirect to logout
header(‘location:logout.php’);
}
?>
<html>
<head>
<title> User Profile </title>
</head>
<body>
<h3>Welcome to your profile page, <?php echo $_SESSION['username']; ?></h3>
<fieldset>
<legend>Action Menu </legend>
<dl>
<dt> Edit your profile </dt>
<dt> <a href=”logout.php”>Logout</a> </dt>
</dl>
</fieldset>
</body>
</html>

At the user profile the application checks the session to see if the user is correctly logged and otherwise redirects the user-to-be to the logout page that will clean the session and redirects him to the login page. At the user profile page the application makes use of the information in hands and uses to interact with the user (in blue). When the page is displayed it will show:

Welcome to your profile page, myUsername

Bellow the message it will show the user some action options for editing his profile information and loggout of the application.

To finish up, let’s clean the session once the user is ready to logout.

logout.php

<?php
include_once(‘bootstrap.php’);
// cleaning the session variables
$_SESSION = array();

if (isset($_COOKIE[session_name()])) {
// to guarantee that the previous session will not be hijacked, destroy the cookie that held the session name
setcookie(session_name(), ”, time() – 42000, ‘/’);
}

// finally destroy the session
session_destroy();

header(‘location: index.php’);

This will fully clean up the session and redirect the user to the first page of the application. It seems a simple set of scripts all over but this will fully exemplify how the session should be handled through the application.

The basics still being, for every session instantiated it must have a session destroy and clean up part. Managing variables, creating, destroying, adding values and updating, works in the same way as an array, but in this case the array is handled by the system and it has its own name $_SESSION.

The series is getting close to the end and soon enough everything will be set together. Keep learning and playing with the session and check this 2 articles from Chris Shiflett blog. It shows very well how session and security should be walking side by side.

  1. Session Fixation
  2. Session Hijacking

Have fun.

Posted in PHP, Security, development, resources | Tagged: , , , , , , , , | Leave a Comment »

Apache Solr extension for PHP

Posted by mcloide on October 7, 2009

One of the most dedicated PHP developers that I ever have met, Israel Ekpo, has released an Apache Solr PHP extension. Solr, Apache enterprise search server has now a good and easy interface for any PHP developer to easily use the server search features.

As himself mentioned:

The Apache Solr extension is an extremely fast, light-weight, feature-rich library that allows PHP developers to communicate easily and efficiently with Apache Solr server instances using an object-oriented API.

More at:

Posted in News, PHP, development | Tagged: , , , , | 1 Comment »

PHPArch Free Webcast – new recordings released

Posted by mcloide on September 21, 2009

PHPArch has released more webcasts recordings on their website and they are also offering a free edition of the PHP Architech magazine.

More @ PHPArch.com

Here is the list of the webcasts:

Date Speaker Title Signup
Jun 26 Matthew Turland New SPL Features in PHP 5.3 Recording
Jul 10 Sumit Chawla Connecting PHP to Microsoft Technologies Recording
Jul 24 M. Weier O’Phinney Play-doh: Towards Better Object Modeling Recording
Jul 31 Stefan Priebsch Migrating to PHP 5.3 Recording
Aug 14 Scott MacVicar The Future of PDO
Aug 21 Hank Janssen

Zach Owens

Running PHP on Windows
Aug 28 Derick Rethans PHP Date and Time Programming Recording
Sep 4 Cal Evans Zend Framework Piece by Piece Recording
Sep 11 Andrei Zmievski What’s New in PHP 6.0
Sep 18 Vijay Rajagopalan Running PHP on Azure Register

Posted in News, PHP, resources | Tagged: , , , , , , , | Leave a Comment »

PHP Basic Series – POST, GET & REQUEST

Posted by mcloide on August 25, 2009

One of the major goals of PHP is to allow a common website to be fully dynamic. For that can be used database requests, form posting, changing information when parameters change, etc.

No matter when working with AJAX/PHP/MYSQL or PHP/MYSQL or simply PHP/MAIL you will probably be using the pre-defined variable arrays of $_POST, $_GET, $_FILES or $_REQUEST. Among these there is one more variable that you should have knowledge about, the $_SERVER variable that holds all the server environment information and is also an array.

[Note]: All these arrays are associative

$_POST

The $_POST array will hold all information that have been passed by a HTTP POST method, or in a simple way, all information that have been passed by a post form and all this information will become a associative index on the array. Per example, if you have a input text box that is named “name” to access it via post you would use $_POST['name'];

It’s always easier to understand the flow of information when you have more than one page, so let’s consider a 3 page application in wich:

  1. Page 1 will hold the post form
  2. Page 2 will process the post
  3. Page 3 will show a thank you message

Page 1: form.html (note that since we are gonna be using php script on the page, there is no need for the php extension even knowing that you can use it).

<html>
<body>
<form method=”post” action=”processForm.php”>
<input type=”text” name=”username” value=”" /><br />
<input type=”submit” value=”submit form” />
</form>
</body>
</html>

It’s a very simple page with a form and a textbox that will submit the information, once posted, to the processForm.php file, that, will process the post request. Note that on the form method the post is defined, but you could use as well the get method. The only thing about using the get method is that it will submit all the values on the browser url as part of a querystring and it would be necessary to use the $_GET variable to request the values.

Page 2: processForm.php - The process posted form page

<?php
if (!empty($_POST)) // checking if a post has been completed
{

if (strlen($_POST['username']) > 0)
{
// has something, let’s force to go to the thanks page
header(‘location: thanksPage.php‘);
}

}
?>

[Note]: Since is a full PHP page you don’t need the closing tag (in red).

Page 3: thanksPage.php – The thank you for posting page

At the last page of the example we will show a thank you page to the user for posting he’s username information.

<html>
<body>
<p> Thanks for posting the form </p>
</body>
</html>

The last page is quite simple and it’s a simple thanks message as part of the last process to be done to complete the post method.

Looking into a simple work flow we would have:

[page 1: form] [enter information] [submit]
{ form is posted to the processPost.php page } :: [page 2: processing] [check if the form has been submited] [check if the username was given]
{ page is redirected to the thanksPage.php } :: [page 3: user message] [show message] [end]

As you have probably noticed by now if the username is not given it will only show a blank page, we would not have a error message being show or even a return to the previous page. Another thing is that even that the username is given, there is no validation what so ever over the submited post.

This is where the $_GET comes to be extremely useful. Get should be used to communicate parameters between pages, but only communicating those parameters that does not contain sensitive information such as passwords or credit card numbers. As example, think in a AJAX call to a php script where the goal is to filter the search based on a given parameter. This is actually done by using $_GET on the php side and passing the filters by a querystring.

Since we don’t really need a form posting to use the get, let’s first demonstrate how to send parameters between pages using the $_GET array. To better understand the process let’s create a 2 page set where the first a user will click a link that will set a parameter on the second page.

Page 1: Links with parameters

<html>
<body>
<a href=”processGet.php?showmsg=1&msg=it%20worked “>click me to set parameters</a>
</body>
</html>

Note 3 elements on that link:

  1. The elements in bold: The ? starts the querystring and whatever comes after it is a parameter that will be passed to the $_GET array. The second element in bold, &, is used to identify any other parameter that will be used on the querystring. After the question mark, all other parameters must use the & to be identified.
  2. The elements in green are the parameters name. The same name that will be used as index on the $_GET array.
  3. The elemenst in blue are the parameters value.

To get those parameters and it’s values, you need a PHP page to parse the $_GET array, so let’s check the page 2.

Page 2: processGet.php – parsing the $_GET array to retrieve the querystring parameters.

<?php
$showMsg = $_GET['showmsg'];
$msg        = $_GET['msg'];
?>
<html>
<body>
<p>
<?php
if ($showMsg) { echo $msg; }
// the equivalent to this is echo ($showMsg) ? $msg : ”;
?>
</p>
</body>
</html>

The second page will check if the first parameter, showmsg, is set to 1 (or true) and if so it will display the msg “it works” on the page for the user.

[Note]: Since this is a php page with html tags in it, you need to close all open php tags (in red).

$_POST and $_GET become really helpful when working together. You would use the post to safely communicate data and the get to inform when something went wrong or simply to exchange information between pages.

Let’s get the example given to $_POST and add some $_GET parameters to communicate the information between page 1 and 2.

Page 1: form.php (note that the extension has changed)

<?php
$hasError = $_GET['error'];
$errorType = $_GET['type'];
?>
<html>
<body>
<?php if (!empty($hasError)) { ?>
<p><? if (!empty($errorType) && $errorType == 1) { echo ‘Please enter your username.’; } ?><br /></p>
// if you had more than one type you could parse all errors here
<?php } ?>
<form method=”post” action=”processForm.php”>
<input type=”text” name=”username” value=”" /><br />
<input type=”submit” name=”submit” value=”submit” />
</form>
</body>
</html>

Page 1 (form.php) contains the form that will submit the username information to the processing php page (processForm.php) and also contains a validation using parameters got from the $_GET array. These parameters will be sent by the second page, proccessForm.php, when an error on the submission is detected.

Page 2: processForm.php

<?php
if ($_POST) {
$username = $_POST['username'];
if (empty($username)) {
header (‘location: form.php?error=1&errortype=1′); // this will display an error message asking the user to enter his username information on the 1st page.
}
else {
header (‘location: thanksPage.php’); // the information was correctly given, so redirect to the thanks page.
}
}
else {
header(‘location: form.php?error=1&errortype=2′); // this could show a message warning the user that a post submission is needed to process
}
?>

With the help of the $_GET array and querystring now we have much more control over the form submission with a very basic validation and at the same time making the form much more dynamic.

I have mentioned above about the $_SERVER, $_REQUEST and $_FILES and where does they come in all of this? Well the $_REQUEST is the same as the $_POST, $_GET and $_COOKIES altogether in one array. In a coding point of view is good to be using all separate since you know what is being sent and where it came from, but using the $_REQUEST is up to each developer.

The $_FILES array is used when you are posting a file through a form (file upload – remember to set the correct enctype on the form). The file will not be available on the $_POST array making the only way to access it through the $_FILES array. Within this array you can find information where it’s currently stored (the tmp file on the server), it’s real name, type, etc.

To wrap up let’s take a look on the $_SERVER array. The server array contains all the information related to the server environment, from the PHP_SELF – the script executing the php coding, to the SERVER_NAME. Check it out on the php manual page for more info or simply do a var_dump($_SERVER) to learn everything about your development server.

On the next post we will gather everything that we have learned here and place it in a small one page application (yeah multi-page is not really necessary, but make it simpler to explain) where we are going to request a username / password from a user to login.

Have fun.

Posted in PHP, Zend, development | Tagged: , , , , , , , , , , | Leave a Comment »

New resources

Posted by mcloide on August 21, 2009

Happy Friday everybody ….

2 New resources for you to check out:

  1. Javascript Bookmarklets
  2. Zend Framework and Firebug – Log PHP warning, errors and exceptions

Don’t forget also of the PHPArch Free Webcast today about Running PHP on Windows with Hank Jansen and Zack Owens.

Have fun .. .

Posted in Javascript, PHP, Zend, development, resources | Tagged: , , , , , , , | Leave a Comment »

Don’t use strtoupper with Japanese characters

Posted by mcloide on August 13, 2009

It’s not like you can’t uppercase characters from Japanese, Chinese, Korean, etc languages, but certainly using strtoupper is not the proper method.

I have passed the last 48 hours trying to find an error that was dying one of my view scripts. No exception has been set or displayed and no error or warning what-so-ever was being displayed. Chasing a bug like this is one of the hardest things you can do.

After a lot of slashhamer debugging (echo mktime(); die;) and help from co-workers and friends I finally could find where the bug was.

The problem was that I was trying to display a Japanese encoded page and simply trying to strtoupper the title was failing and dying the whole script.

After this was found out, then the logical exit was using mb_strtoupper to uppercase it, but it also failed. This time it was fully my fault. Mb_strtoupper uses mb_internal_encoding to get (and set) the internal encoding to be used with that function. If you don’t specify the encoding it will simply get the default therefore failing on the function call creating the origin of my whole ghost bug.

The simple and complete solution for this was setting the encoding to UTF-8 while calling the mb_strtoupper function.

Point is, if you are using a multi-language system and is most likely to be under LATIM1, then whenever using the mb_* functions you must set them to UTF-8, otherwise you will be chasing a ghost bug (and it’s not fun).

Setting the mb_* functions is easy, one of the parameters is always the enconding, so, for example, for the mb_strtoupper function, the function call would be:

echo mb_strtoupper(‘大文字mcloide wordpressのドットドットコム’, ‘utf-8′);

Have fun …

Posted in PHP, Zend, development, resources | Tagged: , , , , , , , , | 6 Comments »

New Page – Zend Certification Series

Posted by mcloide on August 13, 2009

Searching a blog somethings is a bit annoying, so to make everyone life easier I have created a new page with the links for all posts about the Zend Certification Exam (currently PHP5 and in the future ZF).

Since is a page you can easily access it by the top menu or on the right menu

For now, a fast link: Zend Certification Series

Posted in PHP, Zend, development, resources | Tagged: , , , , , | Leave a Comment »

Client Side x Server Side Scripting

Posted by mcloide on August 7, 2009

When considering developing applications for the web two concepts, Client Side and Server Side Scripting,  will emerge and some times, for many beginners mixing this concept gets pretty messy.

Client Side Scripting

Client side scripting is when the application created is translated on the user web browser. The best programmable language that anyone can use to exemplify it is still Javascript.

Whenever working with Javascript all programmed methods, functions, actions and interactions are downloaded to the user web browser and then translated and executed.

Creating a little schematics to understand the process, the sequence would be:

  1. user browser requests a page / application part (index.html)
  2. the page / application part is fully downloaded to the browser
  3. the browser (in this case with Javascript enabled) translate the javascript code and output (print) the result

To better demonstrate this let’s do a small example:

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<script type=”text/javascript”>
// don’t mind the code, is just for example
document.write(“<p>Browser: “);
document.write(navigator.appName + “</p>”);

document.write(“<p>Browserversion: “);
document.write(navigator.appVersion + “</p>”);

document.write(“<p>Code: “);
document.write(navigator.appCodeName + “</p>”);

document.write(“<p>Platform: “);
document.write(navigator.platform + “</p>”);

document.write(“<p>Cookies enabled: “);
document.write(navigator.cookieEnabled + “</p>”);

document.write(“<p>Browser’s user agent header: “);
document.write(navigator.userAgent + “</p>”);
</script>
</head>
<body>
<h1> Your browser information </h1>
</body>
</html>

In this small example, taken from W3C Schools, the javascript code will be downloaded to the user browser and executed displaying the result immediately to the user.

Server Side Scripting

Server Side Scripting is when the translation and execution of the code is done on the server side and only after that being downloaded to the user browser. There are many languages that are fit for the Server Side Scripting. Some great examples are PHP (off course), C# and ROR.

Whenever working with PHP, for example, all PHP code will be translated and executed on the server and substituted for the result that will be downloaded, all together with the page, to the user browser.

Let’s try to do a small schematics here to follow the process for that:

  1. User browser request a page / part of the application (index.php)
  2. The server understands that the page requested has PHP coding and send a request to the PHP engine to translate and execute the code returning the results
  3. After all is processed, the request is complete and the result page is returned to the user browser

To better exemplify this, I will place some body and code for the index.php application.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<title> A Server Side Application </title>
</head>
<body>
<ul>
<?php
// don’t worry about the code for now, just example
$menu = array(‘item1′, ‘item2′, ‘item3′);
foreach($menu as $index => $item)
{ ?>
<li><?php echo $item; ?></li><?php
}
?>
</ul>
</body>
</html>

The PHP engine will translate the PHP coding to output (print) item1, item2, item3 inside a list item for each one of them. The result from this small code will be:

  • item1
  • item2
  • item3

In the real world development, programmers uses both sides of scripting to create complex and interactive applications / pages to the users. Most of the time the client side scripting will take care of the interactions, usability, action requests, etc, and the server side will handle the security of data, output of massive data, body construction, logistics, etc.

To wrap up, take a look at the Google Maps application. While Javascript handles the marker positioning, displaying images, constructing the map, a server side language (PHP I believe) will retrieve the user position by it’s ip positioning the marker, calculate routes, gather the images from the map (in Google Maps specifically is done through an API).

Now let’s start learning some PHP scripting [next].

Posted in PHP, development, resources | Tagged: , , , , , | 1 Comment »