PHP Lab Manual
PHP Lab Manual
1. <html>
<head>
<title>Hello World!</title>
</head>
<body>
<?php
// single-line comments can be like this
# or even like this
/* multi-line comments can
be like this */ ?>
<h1>Examples</h1>
<?php echo "Hello World!"; ?><br />
<?php
// The semicolon at the end of the statement is important!
?>
<?php
// print works like echo
print "Hello World!";
?><br />
<?php
// concatenation
echo "Hello" . " World!<br />";
// simple math
echo 2 + 3;
?><br />
</body>
</html>
1. <?php
/* WARNING: NEVER include this file on your production machine
It's very useful for development but it also gives away WAY too much
information about your system if anyone got access to it.
*/
phpinfo();
?>
2. <html>
<head>
<title>Variables</title>
</head>
<?php
$var1 = 10;
echo $var1;
<?php
// variables values are variable; $var1 can be assigned a new value
$var1 = 100;
echo $var1;
?>
</body>
</html>
3. <html>
<head>
<title>Strings</title>
</head>
<body>
<?php
// Simple string, surrounded by single quotes.
// (included HTML still works just like HTML when output)
echo 'Hello World<br />';
<?php
$firstString = "The quick brown fox";
$secondString = " jumped over the lazy dog.";
?>
<?php
// Concatentation
$thirdString = $firstString;
$thirdString .= $secondString;
echo $thirdString;
?>
<br />
Lowercase: <?php echo strtolower($thirdString); ?><br />
Uppercase: <?php echo strtoupper($thirdString); ?><br />
Uppercase first-letter: <?php echo ucfirst($thirdString); ?><br />
Uppercase words: <?php echo ucwords($thirdString); ?><br />
<br />
Length: <?php echo strlen($thirdString); ?><br />
Trim: <?php echo $fourthString = $firstString . trim($secondString);
?><br />
Find: <?php echo strstr($thirdString, "brown"); ?><br />
Replace by string: <?php echo str_replace("quick", "super-fast",
$thirdString); ?><br />
</body>
</html>
6. <html>
<head>
<title>Numbers: Floating Point Numbers</title>
</head>
<body>
<?php
// Floating Point Numbers (floats) are "numbers with a decimal"
$var1 = 3.14
?>
<?php
// Floats can occur when two numbers don't divide evenly
echo 4/3;
?>
<?php
// defining a simple array
$array1 = array(4,8,15,16,23,42);
<br />
A good way to see the values inside an array during development:<br />
<pre><?php print_r($array2); ?></pre>
</body>
</html>
8. <html>
<head>
<title>Array Functions</title>
</head>
<body>
<?php $array1 = array(4,8,15,16,23,42); ?>
</body>
</html>
9. <html>
<head>
<title>Loops: foreach</title>
</head>
<body>
<?php /* foreach loops
<?php
$ages = array(4, 8, 15, 16, 23, 42);
?>
<?php
// using each value
foreach($ages as $age) {
echo $age . ", ";
}
?>
<br />
<?php
// using each key => value pair
foreach($ages as $position => $age) {
echo $position . ": " . $age . "<br />";
}
?>
<br />
<?php
// Just for fun...
$prices = array("Brand New Computer"=>2000,
"1 month in Lynda.com Training Library"=>25,
"Learning PHP" => "priceless");
foreach($prices as $key => $value) {
if (is_int($value)) {
echo $key . ": $" . $value . "<br />";
} else {
echo $key . ": " . $value . "<br />";
}
}
?>
</body>
</html>
10. <html>
<head>
<title>Booleans and NULL</title>
</body>
</html>
// Assignment to a variable
$max_width = 980;
// Assignment to a constant
define("MAX_WIDTH", 980);
/*
Note that once a page is returned, a constant CAN be redefined by another PHP page.
For example:
Browser Request 1 -> page1.php -> SIZE defined as 10 -> PHP page finishes -> Page 1
Returned
Browser Request 2 -> page2.php -> SIZE defined as 20 -> PHP page finishes -> Page 2
Returned
<?php
$a = 4;
$b = 4;
if ($a > $b) {
echo "a is larger than b";
}
?>
</body>
</html>
14. <html>
<head>
<title>Logical Expressions: Switch</title>
</head>
<body>
<?php
/* switch
Useful when there are many possible actions based on the value of
single variable
*/
$a = 2;
switch ($a) {
case 0:
echo "a equals 0";
break;
case 1:
echo "a equals 1";
break;
case 2:
echo "a equals 2";
break;
default:
echo "a is not 0, 1, or 2";
while(expression)
statement;
</body>
</html>
16. <html>
<head>
<?php
// Outputs 1-10
for ($count=0; $count <= 10; $count++) {
echo $count . ", ";
}
?>
</body>
</html>
17. <html>
<head>
<title>Loops: break</title>
</head>
<body>
<?php /* break
*/
You can also have an explicit "continue" which will loop back to the top
immediately
i.e. skip the remaining statements and start the next cycle of the
loop
Useful if you can quickly determine that the rest of the loop contents won't
apply
If you can, it could speed up your loop!
*/ ?>
<?php
// skips the number 5
for ($count=0; $count <= 10; $count++) {
if ($count == 5) {
continue;
}
echo $count . ", ";
}
?>
</body>
</html>
19. <html>
<head>
<title>Loops: pointers</title>
</head>
<body>
<?php // Pointers and while loops revisited
<?php
// a simple function
function say_hello() {
echo "Hello World!<br />";
}
say_hello();
// Functions can be called more than once (that's the point!) with different
arguments
say_hello2("Everyone");
?>
</body>
</html>
21. <html>
<head>
<title>Functions: globals</title>
</head>
<body>
<?php /* global variables in functions
?>
<br />
<?php
// Example using a local variable, arguments and return values
$bar = "outside";
function foo2($var) {
$var = "inside";
return $var;
}
$bar = foo2($bar);
echo $bar . "<br />";
// use sparingly for variables which truly are global & need to be accessed many
times from many places
// don't declare globals out of laziness--pass in arguments and return values
instead
?>
</body>
</html>
22. <html>
<head>
<title>Second Page</title>
</head>
<body>
<?php
// view values in $_GET array
print_r($_GET);
</body>
</html>
25. <html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<?php // Reading the value of a cookie
</body>
</html>
26. <html>
<head>
<title>Form Processing</title>
</head>
<body>
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser
// Always use exit to keep anything else from the page from executing
</body>
</html>
30. <html>
<head>
<title>Include</title>
</head>
<body>
<?php
// inserts the contents of the file "included_func.php" as if
// those same lines had been typed here.
include("included_func.php");
<?php
/* In addition to include(), you can also use:
include_once();
require();
require_once();
function hello($name) {
echo "Hello {$name}!";
}
/* Note: Even though the request to include this file was inside php-tags,
the file needs to have php-tags around any PHP.
PHP always assumes HTML unless told differently by those tags.
*/
?>
32. <?php //The calendar form
define("ADAY", (60*60*24));
if ((!isset($_POST["month"])) || (!isset($_POST["year"]))) {
$nowArray = getdate();
$month = $nowArray["mon"];
$year = $nowArray["year"];
} else {
$month = $_POST["month"];
$year = $_POST["year"];
}
$start = mktime (12, 0, 0, $month, 1, $year);
$firstDayArray = getdate($start);
?>
<html>
<head>
<title><?php echo "Calendar: ".$firstDayArray["month"]."
".$firstDayArray["year"]; ?></title>
?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php
// 3. Perform database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
?>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>
34. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (isset($_GET['subj'])) {
$sel_subj = $_GET['subj'];
$sel_page = "";
} elseif (isset($_GET['page'])) {
$sel_subj = "";
$sel_page = $_GET['page'];
} else {
$sel_subj = "";
$sel_page = "";
}
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = get_all_subjects();
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li";
if ($subject["id"] == $sel_subj) { echo " class=\"selected\""; }
echo "><a href=\"content.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = get_pages_for_subject($subject["id"]);
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page) { echo " class=\"selected\"";
}
echo "><a href=\"content.php?page=" .
urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
?>
</ul>
</td>
<td id="page">
<h2>Content Area</h2>
<?php echo $sel_subj; ?><br />
<?php echo $sel_page; ?><br />
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
35. <?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
</td>
<td id="page">
<h2>Staff Menu</h2>
<p>Welcome to the staff area.</p>
<ul>
<li><a href="content.php">Manage Website
Content</a></li>
<li><a href="new_user.php">Add Staff User</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
36. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
find_selected_page();
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<?php
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
?>
<?php
$query = "INSERT INTO subjects (
menu_name, position, visible
) VALUES (
'{$menu_name}', {$position}, {$visible}
)";
$result = mysql_query($query, $connection);
if ($result) {
// Success!
header("Location: content.php");
exit;
} else {
// Display error message.
echo "<p>Subject creation failed.</p>";
echo "<p>" . mysql_error() . "</p>";
}
?>
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
}
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>
<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name"
value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject
if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
} else {
// Errors occurred
}
} // end: if (isset($_POST['submit']))
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
} else {
// Errors occurred
$message = "There were " . count($errors) . " errors in the
form.";
}
} // end: if (isset($_POST['submit']))
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>
<?php if (!empty($message)) {
echo "<p class=\"message\">" . $message . "</p>";
} ?>
<?php
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name"
value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
} else {
// Errors occurred
$message = "There were " . count($errors) . " errors in the
form.";
}
$id = mysql_prep($_GET['subj']);
if ($subject = get_subject_by_id($id)) {
$id = mysql_prep($_GET['page']);
// make sure the page exists (not strictly necessary)
// it gives some extra security and allows use of
// the page's subject_id for the redirect
if ($page = get_page_by_id($id)) {
// LIMIT 1 isn't necessary but is a good fail safe
$query = "DELETE FROM pages WHERE id = {$page['id']} LIMIT 1";
$result = mysql_query ($query);
if (mysql_affected_rows() == 1) {
// Successfully deleted
redirect_to("edit_subject.php?subj={$page['subject_id']}");
} else {
// Deletion failed
echo "<p>Page deletion failed.</p>";
echo "<p>" . mysql_error() . "</p>";
echo "<a href=\"content.php\">Return to Main Site</a>";
}
} else {
// page didn't exist, deletion was not attempted
redirect_to('content.php');
}
?>
<?php
// because this file didn't include footer.php we need to add this manually
mysql_close($db);
include_once("includes/form_functions.php");
include_once("includes/form_functions.php");
if (logged_in()) {
redirect_to("staff.php");
}
include_once("includes/form_functions.php");
$username = trim(mysql_prep($_POST['username']));
$password = trim(mysql_prep($_POST['password']));
$hashed_password = sha1($password);
if ( empty($errors) ) {
// Check database to see if username and the hashed password exist
there.
$query = "SELECT id, username ";
redirect_to("staff.php");
} else {
// username/password combo was not found in the database
$message = "Username/password combination
incorrect.<br />
Please make sure your caps lock key is off and try
again.";
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the
form.";
}
}
redirect_to("login.php?logout=1");
$username = trim(mysql_prep($_POST['username']));
$password = trim(mysql_prep($_POST['password']));
$hashed_password = sha1($password);
if ( empty($errors) ) {
$query = "INSERT INTO users (
username, hashed_password
) VALUES (
'{$username}',
'{$hashed_password}'
)";
$result = mysql_query($query, $connection);
if ($result) {
$message = "The user was successfully created.";
} else {
$message = "The user could not be created.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the
form.";
}
}
} else { // Form has not been submitted.
$username = "";