Web technologies -- Laboratory 17 -- 2009-2010 -- info.uvt.ro

From Wikiversity

PHP (part 1)[edit]

PHP is a server side scripting language. It is intended for creating dynamic web pages.

Following an HTTP Request PHP code is interpreted into HTML code (and even plain text) that is returned in the HTTP Response.

PHP pages have the .php extension and can be edited with any text editor.

An example of a very simple PHP script is the following:

	<?php
		echo "Welcome to your first PHP script";
	?>

NOTE: language syntax is similar with the one used in C. Furthermore many of the function names are similar with the ones used in C.

Forms[edit]

Although not restricted to them, PHP works great together with HTML forms. To this end data from the forms can be extracted by using the $_POST (for method="post" forms), $_GET (for method="get" forms) or $_REQUEST' (for any kind of form action) variables.

The next example shows how HTML code and PHP code can be mixed in the same source file. The form submits the information to itself ($_SERVER['PHP_SELF']) and shows a welcome message in case the user name has been set.

	<html>
		<head></head>
		<body>
			<?php
				if (isset($_REQUEST['usename'])) {
					echo "<h1>Welcome" . $_REQUEST['usename'] . "</h1>";
				}
			?>
			<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
				<input type="text" name="username"/>
				<input type="submit" value="Click me"/>
			</form>
		</body>
	</html>

NOTE: the use of htmlentities prevents hackers from inject Javascript code in your HTML. It does this by encoding the HTML special characters such as < or > into < and >. In this way any injected Javascript code will be ignored by your browser.

Cookies and Sessions[edit]

Cookies and sessions are great methods for remembering user data. Because of this they can also be used for sending data from one page to another.

In PHP they are handled by the variables $_COOKIE and $_SESSION.

The start of a session must be marked by a call to session_start() at the beginning of the page. Similarly the end of a session (e.g., when a user clicks a logout button) is marked by a call to the session_destroy() function.

The next example shows how a session variable can be used when deciding whether or not to display a form for querying a new user for his/hers name.

	<?php
		session_start();
	?>
	<html>
		<head></head>
		<body>
			<?php
				if (isset($_REQUEST['username']) && !isset($_SESSION['username'])) {
					$_SESSION['username'] = $_REQUEST['usename'];
				}
				if (isset($_SESSION['username']))
					echo "<h1>Welcome" . $_SESSION['usename'] . "</h1>";				
			?>

			<?php 
				if (!isset($_SESSION['username'])) {
			?>
					<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
						<input type="text" name="username"/>
						<input type="submit" value="Click me"/>
					</form>
			<?php } ?>	
		</body>
	</html>

NOTE: session variables can also be destroyed individually by using unset() function (e.g., unset($_SESSION['username'])).

Cookies (if supported by the browser) can be created by using the setcookie function.

The next code is similar with the one used for sessions but uses cookies instead:

	<html>
		<head></head>
		<body>
			<?php
				if (isset($_REQUEST['username']) && !isset($_COOKIE['username'])) {
					setcookie('username', $_REQUEST['usename'], time()+60*60*24 /*expire in one day from now*/);
				}
				if (isset($_COOKIE['username']))
					echo "<h1>Welcome" . $_COOKIE['usename'] . "</h1>";				
			?>

			<?php 
				if (!isset($_COOKIE['username'])) {
			?>
					<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
						<input type="text" name="username"/>
						<input type="submit" value="Click me"/>
					</form>
			<?php } ?>	
		</body>
	</html>

Cookies can be deleted by setting their expiration date in the past: setcookie("username", "", time()-3600);.

Functions and classes in PHP[edit]

Like any programming language PHP allows us to define functions and classes.

Functions are declared by the function keyword:

	<?php
		function checkExistsInSession($name, $value) {
			if (isset($_SESSION[$name]) && $_SESSION[$name] == $value)
				return true;
			return false;
		}

		// Call function
		$checkExistsInSession("username","John");
	?>

Anonymous functions can also be created since PHP version 5.3:

	<?php
		$checkExistsInSession = function($name, $value) {
			if (isset($_SESSION[$name]) && $_SESSION[$name] == $value)
				return true;
			return false;
		}
		
		// Call anonymous function
		$checkExistsInSession("username","John");
	?>

or by using closures:

	<?php
		function checkExistsInSession($value) {
			// name is predefined here
			$name = "username";

			//notice the use keyword which informs that we want to use the $name variable in the anonymous function
			return function($value) use $name {
				if (isset($_SESSION[$name]) && $_SESSION[$name] == $value)
					return true;
				return false;
			}
		}	
		// Call function
		$checkExistsInSession("John");
	?>

PHP also permits the use of classes since version 3 (and improved in 4). The next example (placed in a file called user.php) shows an example of a class defined in PHP:

class User {
	public $username;
	public $password;
 
	public function __construct($username, $password) {
		if ($this->check($username, $password)) {
			$this->username = $username;
			$this->pasword = $password;
			echo "Credentials OK.";
		}
		else {
			echo "Invalid credentials.";
		}
	}
 
	public function showCredentials() {
		return "Username: " . $this->username . " Password: " . $this->password . ".";
	}
 
	private function check($username, $password) {
		$ok = false;

		//check credentials;
		// ...

		return $ok;
	}
}

The previous class can be used in another file by using include or require:

	<?php
		start_session();
		// assume user.php is in the same directory as the script that needs it.
		require("user.php");

		//check whether the user info is already set or not
		if (isset($_SESSION['user'])) {
			$user = unserialize($_SESSION['user']);
		}
		else {
			$user = & new User($_REQUEST['username'], $_REQUEST['password']);
			//store $user in a session
			$_SESSION['user'] = serialize($user);
		}

		echo $user->showCredentials();
	?>

NOTE: notice the use of unserialize and serialize to marshal the object in a session variable.

Exercise[edit]

  • Store in a session all the information coming from the client (HTTP request header including its IP address) in case the browser is Firefox;
  • Create a webpage with the following requirements:
    • create the following forms:
      • one login page (having a form containing two text fields for username and password and one submit button);
      • one new user page (having a form containing three text fields: username, password field and password check; as well as a submit button). The password value should be the same as the password check value. Validate on both client (Javascript) and server (PHP) side;
    • the application should behave as follows:
      • each new user should be stored in a session variable. You could use an array to hold all new users. The array could then be stored in the session variable;
      • each time a user tries to log in he/she is searched for in the session array. A message containing the status of the search (found/not found) should be displayed)
      • if a user exists he/she should have the option to remove himself/herself from the user list by clicking on a button. The button should appear only if after a login attempt the user is found.

HINT:

  • browser information can be found by accessing the $_SERVER variable;
  • arrays are defined as follows: $numbers = array("one", "two", "three");
  • the size of the array is found by using: sizeof($numbers);
  • when stored in a session an array can be looped by using: foreach($_SESSION["numbers"] as $key=>$value)

, where $key represents the index of the element.