You are on page 1of 25

PHP Header Function

When you request a web page be brought back to your browser, you're not just bringing back the
web page. You're also bringing back something called a HTTP HEADER. This is some extra
information, such as type of programme making the request, date requested, should it be
displayed as a HTML document, how long the document is, and a lot more besides.
One of the things HTTP HEADER also does is to give status information. This could be whether
the page was found (404 errors), and the location of the document. If you want to redirect your
users to another page, here's an example:
<?PHP
header("Location: http://www.homeandlearn.co.uk/");
?>
<html>
<body>
</body>
</html>
Note how the header code goes before any HTML. If you put header code after the HTML, you'll
get an error along the lines of "Cannot modify header information."
Check for blank Textboxes with PHP

If you remember the script that we wanted to create earlier it was this:
1. Get the text that a user entered in a textbox on a form
2. Trim any blank spaces from the left and right of the text
3. Check that what you have left is not a blank string
So we want to check that the textbox doesn't just contain this "". There has to be something in it,
like "Bill Gates". Here's a script that does all three items on our list:
<?PHP
$user_text = trim("Bill Gates");
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == "") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>
Try it out. When you run the script, you should find that Text OK prints. Now change this line:
$user_text = trim("Bill Gates");
to this:
$user_text = trim("");
Run your script again. This time, Blank text box detected should print out. Obviously, we're not
getting the text from a textbox on a form, but just simulating the process. If you want to try out a
version with all the HTML, here it is. This next script checks two textboxes on a form.
A Script to Check for Blank Text Boxes
Try the script out. But the point is, that we're using the same function to check for blank text
boxes. We're not writing the same code over and over. Just call our one function as and when
needed.
In the next part, we'll see how to get values back out of functions.
MySQL databases - read a record with PHP
To read records from a database, the technique is usually to loop round and find the ones you
want. To specify which records you want, you use something called SQL. This stands for
Structured Query Language. This is a natural, non-coding language that uses words like
SELECT and WHERE. At it's simplest level, it's fairly straightforward. But the more complex
the database, the more trickier the SQL is. We'll start with something simple though.
What we want to do, now that we have a connection to our database, is to read all the records,
and print them out to the page. Here's some new code, added to the PHP script you already have.
The new lines are in blue:
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
Before we go through the new code to see what's happening, run your script. You should find
that the address you added in a previous section is printed out. (We only have one record at the
moment.)
1
Test
Name
12 Test Street
The first line in the new code is this:
$SQL = "SELECT * FROM tb_address_book";
The $SQL is just a normal variable. But we're putting into it a long string. This is a SQL
statement. Here's a brief run down on SQL.

Structured Query Language
SQL (pronounced SEEKwel), is a way to query and manipulate databases. The basics are quite
easy to learn. If you want to grab all of the records from a table in a database, you use
the SELECT word. Like this:
SELECT * FROM Table_Name
SQL is not case sensitive, so the above line could be written:
Select * From Table_Name
But your SQL statements are easier to read if you type the keywords in uppercase letters. The
keywords in the lines above are SELECT and FROM. The asterisk (*) means "All
Records".Table_Name is the name of a table in your database. So the whole line reads:
"SELECT all the records FROM the table called Table_Name"
You dont have to select all the records from your database. You can just select the columns that
you need. For example, if we wanted to select just the first name and surname columns from this
table, we can specify that in our SQL String:
"SELECT First_Name, Surname FROM tb_address_book";
When this SQL statement is executed, only the First_Name and Surname columns from the
database will be returned.
There are a lot more SQL commands to get used to, and you'll meet more of them as you go
along. For now, we're just selecting all the records from our table.

Back to the Code
The first line of our code, then, was this:
$SQL = "SELECT * FROM tb_address_book";
SO we have a SQL statement, but we need to pass it to another inbuilt function:
mysql_query( )
The mysql_query( ) function is used to send a SQL query to your database. If you have typed
out your SQL correctly, then the function will return a value. This value will be true, false, or a
file handle. Because we're using the SELECT keyword, the value returned by will be a file
handle. In our code, the line was this:
$result = mysql_query( $SQL );
The file handle returned in our $result variable just points to the results. It doesn't actually bring
anything back. To bring back the data, we had this inside a while loop:
$db_field = mysql_fetch_assoc( $result );
The inbuilt function we're using to bring results back is this:
mysql_fetch_assoc( $result )
The assoc part means Associative. As in "associative array". So we're asking that the results be
brought back in an array format. In between the round brackets of mysql_fetch_assoc we have
typed the name of our file handle the one that was pointing to the results of SQL statement.
Remember: an associative array is one where the keys are text. So it's this format:
Array['One'] =
Array['Two'] =
Array['Three]' =
And not this:
Array[1] =
Array[2] =
Array[3] =
When the mysql_fetch_assoc function returns an array, we're putting it all into a variable
called$db_field. The Key part of the array is all the Column names from our database tables.
This is done automatically for you. So the array format will be this:
$db_field[Column_Name] = Value
The reason why you're doing this is so that you can loop round the array and access the values
from the table. Here's our loop, without anything between the round brackets:
while ( ) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
So we're printing whatever the value is in the array
position $db_field['ID'], $db_field['First_Name'],$db_field['Surname'] and $db_field['Addres
s']. We're also adding a HTML line break at the end, just for printing purposes.
If all that is confusing, just remember the format:
Array_Name[Table_Coulmn_Name] = Value_From_Record
Our whole while loop, then, is this:
while ($db_field = mysql_fetch_assoc($result) ) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
Because that is a bit complex, let's go through the steps we've used to access the records from our
table:
1. Set up a SQL Statement that can be used to get the records from the database table
2. Use mysql_query() to bring back the records we've specified in Step 1
3. Use mysql_fetch_assoc() to set up an array. The array will contain all the records that were
returned in Step 2
4. Loop round all the data in the array using a While loop
Step 1 was this, in the code:
$SQL = "SELECT * FROM tb_address_book";
Step 2 was this:
$result = mysql_query($SQL);
Step 3 was this:
$db_field = mysql_fetch_assoc($result)
And Step 4 was this:
while ($db_field = mysql_fetch_assoc($result) ) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
If you're still confused, study the code and go over this section. In the next section, we'll adapt
the code to add more records to our database table.
PHP Session Variables
This lesson is part of an ongoing User Authentication tutorial. The first part is here: User
Authentication along with all the files you need.
On all pages of your site that you want to secure, you'll need to check if the user was
successfully logged on or not. After all, what's to stop non members from simply typing the
address of the page in their browsers? If you haven't set any checks, then the page will load,
whether they are a member or not. To stop this happening, you can check the session variable
that you set up on the login page.
If you open up the page called page1.php (in your scripts folder), you'll see this complex code
at the top:
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
?>
This checks to see if the session called login is set, and that it's not a blank string. If it is, then the
user is redirected to the login page. In the script, you first start the session:
session_start();
Next comes a complex If statement:
if () {
header ("Location: login.php");
}
In between the round brackets of the If statement, we have the NOT operator. This is followed
by the inbuilt isset() function:
if ( !(isset( ) ) {
}
This says, "If NOT isset". Or, "if the value of the isset function is false ... " If the value in the
round brackets of isset is indeed false, then the code between the curly brackets { } gets
executed. That code, for us, was the redirection line. What we have between the round brackets
of isset is this:
($_SESSION['login'])
That's just our session variable from the login page. Is the user has logged in successfully, a
value of 1 will be set inside of this variable.
But we also need to check the session variable for a blank string. So we have and AND part to
the statement:
&& $_SESSION['login'] != ''
This says, "AND session login DOES NOT EQUAL a blank string". In other words, we check to
see if a session variable has been set, and that it's not a blank string.
If everything is OK then the user will see the HTML code below the PHP at the top. If it's not,
you can send them somewhere else. But you need to put that PHP code at the top of every page
that you want to protect. And it needs to go before any HTML code. You can't put it in the head
section, otherwise you'll get "header" errors.
In the next part, you'll how to let your users log out.


<?php

$username=$_POST['username'];
$password=$_POST['password'];
$companyname=$_POST['companyname'];
$firstname=$_POST['firstname'];
$secondname=$_POST['secondname'];
$email=$_POST['email'];

#Insert data into mysql

$sql="INSERT INTO company(username, password, companyname, firstname, secondname, email)VALUES('$use
rname', '$password','$companyname', '$firstname', '$secondname' , '$email')";

$result=mysql_query($sql);


$query = mysql_query("SELECT * FROM users WHERE username = '". $username ."' OR email = '". $email ."'");

if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use please try another.';
}


if($result){
echo "Successful";
echo "<BR>";
echo "<a href='Company_login.php'>Go To Company Login</a>";
}

else {
echo "ERROR";
}

mysql_close();
?>



Check into database for name and password

<?php

session_start();
require_once('includes.php');


//Connect to server
$link = mysql_connect($host, $user, $pw) or die(mysql_error());
//Select the database
mysql_select_db ($db);

// Get the login credentials from user
$username = $_POST['username'];
$userpassword = $_POST['password'];

// Secure the credentials
$username = mysql_real_escape_string($_POST['username']);
$userpassword = mysql_real_escape_string($_POST['password']);

// Check the users input against the DB.
$query = "SELECT * FROM user WHERE username = '$username' AND password
= '$userpassword'";
$result = mysql_query($query) or die ("Unable to verify user because "
. mysql_error());

$count = mysql_num_rows($result);

if ($count == 1)
{
$_SESSION['loggedIn'] = "true";
header("Location: menu.html");
// I also tried the whole URL here, but same result.

}
else
{
$_SESSION['loggedIn'] = "false";
echo "<p>Login failed, username or password incorrect.</p>";
}



?>




Example:
Try out following example to display all the records from employee table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

To delete record from database
Example:
Try out following example to understand delete operation. You need to provide an employee ID to
delete an employee record from employee table.
<html>
<head>
<title>Delete a Record from MySQL Database</title>
</head>
<body>

<?php
if(isset($_POST['delete']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

$emp_id = $_POST['emp_id'];

$sql = "DELETE employee ".
"WHERE emp_id = $emp_id" ;

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="emp_id" type="text" id="emp_id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>


CREATING A SIMPLE LOGIN-
LOGOUT SESSION USING PHP
Before attempting this, please ensure that you have installed an Apache/MySQL/PHP Stack,
you may use one of these program :
XAMPP (For many platform)
WAMP (For Windows)
MAMP (for Mac user)
Start the server by executing Start Wamp Server (for WAMP user, or similar for the other
software). Then, you can view your page in any browser in your own computer by typing:
http://localhost/
if you can see your page there, Good job !!! :D :D, it means that your server has already running in
your computer.
then lets get into the php & html code.
first we create the simple login form like this : (in this example I create the login form with the
name: niceform.php)
<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header(Location: content.php);
}
?>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN>
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method=post action=login.php>
<! in this example I link it with login.php to check the password & username>
<table>
<tr><td>Username:</td><td><input type=text name=usr></td></tr>
<tr><td>Password:</td><td><input type=password
name=pswd></td></tr>
<tr><td><input type=submit name=login value=Login></td>
<td><input type=reset name=reset value=Reset></td></tr>
</table>
</form>
</center>
</body>
</html>
After finishing the form, lets move to login.php, here well check the variable of username and
password, if its correct, then itll be redirected to content.php , otherwise itll forced back into
the niceform.php
login.php:
<?php
session_start();
if($_REQUEST['usr']==ABC && $_REQUEST['pswd']==123){
$_SESSION['usr'] = ABC;
$_SESSION['pswd'] = 123;
header(Location: content.php);
}
else{
header(Location: niceform.php);
}
?>
then, we move to the content page content.php :
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
header(Location: niceform.php);
}
include logoff.html';
<! in this example my content only containing a html with logout link>
?>
For logout function, I simply use session_destroy (for a simple log out function in this
case) logout.php :
<?php
session_start();
session_destroy();
header(Location: niceform.php);
exit;
?>
finally, create a html file that containing a link for logout : logoff.html :
<html>
<head>
<title></title>
</head>
<body>
<center>
<h2><a href=./logout.php>Logout</a></h2>
<br/>
</center>
</body>
</html>


Step first save it as connection.inc.php
<?php
$dbc = mysql_connect('localhost','root','') or die("Cant connect :" .
mysql_error());

mysql_select_db("test-login",$dbc)

or
die("Cant connect :" . mysql_error());

?>

Step second save it core.inc.php

<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];

if(isset($_SERVER['HTTP_REFERER']))
{
$http_referer = $_SERVER['HTTP_REFERER'];
}
else
{
$http_referer = '';
}


function loggedin()
{
if (isset($_SESSION['user_id'])&&!empty($_SESSION['user_id']))
{
return true;
}
else
{
return false;
}
}

?>

3. Save this page as 'login.inc.php
<?php
if(isset($_POST['username'])&&isset($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$password_hash=md5($password);

//echo $password_hash;

if(!empty($username)&&!empty($password))
{
$query = mysql_query("SELECT * FROM users WHERE username ='".$username."' AND
password ='".$password_hash."'") or die(mysql_error());

$data = mysql_fetch_array($query);

$test=$data['password'];

$query_run=$query;
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==0)
{
echo 'Invadid username/password combination.';
}
else if($query_num_rows==1)
{
echo 'ok';
$user_id= mysql_result($query_run,0,'id');
$user_id=$data['id'];
$_SESSION['user_id'] = $user_id;
header("Location:".$_SERVER['PHP_SELF']. " ");
}
{
}

}
else
{
echo 'You must supply a username and password';
}

}

?>
<div align="center">
<form action="<?php echo $current_file; ?>" method="POST">
Username: <input type="text" name="username"> Password: <input
type="password" name="password">
<input type="submit" value="Log in">
</form>
</div>

Save this page as 'logout.php'
<?php
require 'core.inc.php';
session_destroy();
header('Location: '.$http_referer);


?>

Save this page as 'index.php'
<?php
require 'core.inc.php';
require 'connection.inc.php';
if(loggedin())
{
$rightvar=$_SESSION['user_id'];
$result = mysql_query("SELECT * FROM users WHERE id = $rightvar") or
die(mysql_error());
$data = mysql_fetch_array($result);
$firstname=$data['firstname'];
$surname=$data['surname'];
$userid=$data['id'];

echo 'Welcome! ' . $firstname . ' ' . $surname .'<a
href="logout.php"><input type="button" value="Logout"/></a>';
}
else
{
include 'login.inc.php';
}
?>

















<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

$emp_id = $_POST['emp_id'];
$emp_salary = $_POST['emp_salary'];

$sql = "UPDATE employee ".
"SET emp_salary = $emp_salary ".
"WHERE emp_id = $emp_id" ;

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="emp_id" type="text" id="emp_id"></td>
</tr>
<tr>
<td width="100">Employee Salary</td>
<td><input name="emp_salary" type="text" id="emp_salary"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>












it should need 5 files for this login-logout system, they are
1. login/index page
2. datafetch/usercheck page
3. session/check page
4. welcome/profile page
5. logout page

the above files must me needed for this. we can named it as our wish. let
see what i done here. and the database file is needed, if you have any doubt
about insert coding check here for insert code

database name --> 2mylogin
table name --> login


DB.PHP
<?php
$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('2my4edge',$conn);
?>


INDEX.PHP
<?php
session_start();
?>
<form method="post" name="login" action="login.php">
<label for="name" class="labelname"> Username </label>
<input type="text" name="username" id="userid" required="required" /><br />
<label for="name" class="labelname"> Password </label>
<input type="password" name="password" id="passid" required="required" /><br
/>
<input type="submit" name="submit" id="submit" value="Login" />
</form>
in the index page we have to start the session, as the above mentioned.
action is performed in login.php page.

LOGIN.PHP
<?php
include('db.php');
session_start();
{
$user=mysql_real_escape_string($_POST['username']);
$pass=mysql_real_escape_string($_POST['password']);
$fetch=mysql_query("SELECT id FROM `login` WHERE
username='$user' and password='$pass'");
$count=mysql_num_rows($fetch);
if($count!="")
{
session_register("sessionusername");
$_SESSION['login_username']=$user;
header("Location:profile.php");
}
else
{
header('Location:index.php');
}

}
?>
if the session is registered then go to check the profile.php page
theresession.php file is included so the session is checked.

SESSION.PHP
<?php
include('db.php');
session_start();
$check=$_SESSION['login_username'];
$session=mysql_query("SELECT username FROM `login` WHERE username='$check'
");
$row=mysql_fetch_array($session);
$login_session=$row['username'];
if(!isset($login_session))
{
header("Location:index.php");
}
?>
check the session value is correct or not. if the session is value is not set,
then again redirect to index.php page.
PROFILE.PHP
<?php
include("session.php");
?>

<h3 align="center"> Hellow <?php echo $login_session; ?></h3>
<h2 align="center" >Welcome to login system</h2>

<h4 align="center"> click here to <a href="logout.php">LogOut</a> </h4>

assign the logout.php page in the profile.php page.

LOGOUT.PHP
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
in the logout.php page, we should unset or destroy the session value as the
above you seen. then locate to index.php page.
and we should have to start the session in all the page.



Check for blank Textboxes with PHP

If you remember the script that we wanted to create earlier it was this:
1. Get the text that a user entered in a textbox on a form
2. Trim any blank spaces from the left and right of the text
3. Check that what you have left is not a blank string
So we want to check that the textbox doesn't just contain this "". There has to be something in it,
like "Bill Gates". Here's a script that does all three items on our list:
<?PHP
$user_text = trim("Bill Gates");
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == "") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>
Try it out. When you run the script, you should find that Text OK prints. Now change this line:
$user_text = trim("Bill Gates");
to this:
$user_text = trim("");
Run your script again. This time, Blank text box detected should print out. Obviously, we're not
getting the text from a textbox on a form, but just simulating the process. If you want to try out a
version with all the HTML, here it is. This next script checks two textboxes on a form.
A Script to Check for Blank Text Boxes
Try the script out. But the point is, that we're using the same function to check for blank text
boxes. We're not writing the same code over and over. Just call our one function as and when
needed.
In the next part, we'll see how to get values back out of functions.






PHP Server Variables

PHP stores a list of information about the server. This will include things like, the browser the
visitor is using, the IP address, and which web page the visitor came from. Here's a script to try
with those three Server Variables:
$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
print "Referrer = " . $referrer . "<BR>";
print "Browser = " . $browser . "<BR>";
print "IP Adress = " . $ipAddress;
These are useful if you want to log your stats, or to ban a particular IP address! (If you run the
script on a local machine, you may get an error for the referrer.)
So to get at the values in Server Variables, the syntax is this:
$_SERVER['Server_Variable']
You start with a dollar sign, then an underscore character ( $_ ). Then you add the
word SERVER. In between square brackets, you type the name of the server variable you want
to access. Surround this with either single or double quotes.
Because you are returning a value, you need to put all that on the right hand side of an equals
sign. On the left of the equals sign ( = ), you need a variable to hold the string that is returned.
The server variables are held in an array (associative), so you can use a foreach loop to get a list
of all available ones. Try this script:
<?PHP
foreach($_SERVER as $key_name => $key_value) {
print $key_name . " = " . $key_value . "<br>";
}
?>
What the script does is to loop round all the server variables and print out the keys and values in
the SERVER array.


The strpos function in PHP

A more useful thing you'll want to do is to see if one string is inside of another. For example, you
can get which browser the user has with this:
$agent = $_SERVER["HTTP_USER_AGENT"];
print $agent;
Try it out and see what gets printed out. You should find that quite along string gets printed.
If you're testing which browser the user has, you can use a string function to search for a short
string inside of this very long one. A PHP string function you can use is strpos( ). The syntax for
the strposfunction is:
strpos( string_to_search, string_to_find, start )
You need to supply at least the first two. The third, start, is optional. Here's a simple example.
$full_name = "bill gates";
$letter_position = strpos( $full_name, "b" );
print $letter_position;
When you run the script, a value of 0 is returned. That's because PHP considers the first
character of the string to be at position 0, the second character at position 1, the third at position
2, etc. Since we were searching for the letter "b", and "bill gates" begins with this letter, a value
of 0 is returned.
Try changing strpos( ) from this:
$letter_position = strpos($full_name, "b" );
to this:
$letter_position = strpos($full_name, "B" );
What happens when you run the script? Nothing! At least, you don't get a value back. That's
because ifstrpos can't find your characters, it returns a value of false. A value of false in PHP
can be tested for by using the triple equals operator. Like this:
$full_name = "bill gates";
$letter_position = strpos($full_name, "B");
if ($letter_position === false) {
print "Character not found " ;
}
else {
print "Character found";
}
The triple equals operator ( === ) not only checks for a value but what type of value it is: integer,
string, Boolean, etc. If a string is not found, you need to use this operator, just in case the
character you're searching for is at position 0. PHP is a little bit quirky with zeros. It seems them
as having a false value as well. But it can be a different kind of false! So use ===.
Here's a script that checks which of two browsers a user has:
$agent = $_SERVER['HTTP_USER_AGENT'];
if ( strpos( strtoupper($agent), 'MSIE') ) {
print "Internet Explorer";
}
else if (strpos(strtoupper($agent), 'FIREFOX')) {
print "Firefox";
}
else {
print $agent;
}
The above script uses two of the string functions that you've met: strpos( ) and strtoupper(
). See if you can figure out what's going on!

In the next part, you'll learn how to split a line of text. You'll need to do this when working with,
for example, text files


The PHP getdate Function

Another useful date/time function is getdate. This will return an array (associative) with all the
date and time values. You can use it for things like comparing one date to another. For example,
comparing how many days have passed since a given date. Here's the syntax:
getdate( time_stamp );
The time stamp is optional. If you leave it out, it gets the values for the current local date and
time. The parts of the array are this:
seconds
minutes
hours
mday (day of the month as a number)
wday (day of the week as a number)
mon (month a number)
year
yday (year day as a number)
weekday (day in text format)
month (month in text format)
0 (Seconds since the Unix Epoch)
Because getdate returns an associative array, you can just do this sort of thing:
$today = getdate();
print $today['mday'];
print $today['wday'];
print $today['yday'];
So whichever part of the array you want to access goes between square brackets. You then type
one of the above Keys between quote marks.
As a further example, suppose you want to work out how many days it's been since a forum
member last posted something. And that you have used this to write the date of the last post in a
database:
$post_date = date('z');
If you look at the previous tables, you'll see that "z" means the year day as a number. So a value
of 60 would mean the 60th day of the year.
Now, you've read this value back in, and you want to compare that date against today's date. You
can do it like this:
<?PHP
$post_date = 60;
$today = getdate();
$day_difference = $today['yday'] - $post_date;
Print "Days since last post = " . $day_difference;
?>
So we've set up the array using getdate:
$today = getdate();
We've then used "yday" to calculate how many days have elapsed since the last post:
$day_difference = $today['yday'] - $post_date;

Working with dates and times can be quite tricky, and a good reference is the PHP.net website.
As well as setting out all the date and time functions, there's lots of posts from people with good
date/time scripts:
http://uk.php.net/manual/en/function.date.php
In the next section of the course, we'll explore databases.


The PHP date function

Knowing how to handle date and time values in PHP will be a useful addition to your
programming skills. In this and the following sections, we'll take a look at how to process this
type of data.

The date( ) function
The inbuilt PHP function date( ) is the most widely used method of returning date values.
Unfortunately, there is a very long list of things you can put between the round brackets of the
function! Try this script, to get an idea of how it works:
<?php
$today = date('d-m-y');
print $today;
?>
It should print the day of the week first (d), then the month (m), then the year (y). But this will be
the numerical format. So it will print something like:
04-07-2006
This type of date can be very confusing, however, because it means the 7th of April in the USA.
In the UK, it means the 4th of July.
But to use the function, you first type date followed by the round brackets. In between the round
brackets you can type a whole host of different date combinations. There's a list coming up. But
take note of the case. Change your script to capital letters and watch what happens.
Also, the separator can be anything you like (within reason). So you can have this instead of a
hyphen:
$today = date('d:m:y');
Or this:
$today = date('d m y');
Or even this:
$today = date('d~m~y');
Note the single quote marks surrounding the date text. Miss these out and you'll get errors. You
can use double quotes, but singles are recommended: dates can be a bit quirky.
Click the next part for a fuller list of the date and time characters to use between the round
brackets ofdate

You might also like