First Draft

First Draft of the Example Files
This commit is contained in:
RobinNixon
2020-12-10 13:21:38 +00:00
parent 77a7b57c4f
commit 0335342e00
1127 changed files with 46959 additions and 56 deletions
+3
View File
@@ -0,0 +1,3 @@
function O(i) { return typeof i == 'object' ? i : document.getElementById(i) }
function S(i) { return O(i).style }
function C(i) { return document.getElementsByClassName(i) }
+203
View File
@@ -0,0 +1,203 @@
<?php // adduser.php
// Start with the PHP code
$forename = $surname = $username = $password = $age = $email = "";
if (isset($_POST['forename']))
$forename = fix_string($_POST['forename']);
if (isset($_POST['surname']))
$surname = fix_string($_POST['surname']);
if (isset($_POST['username']))
$username = fix_string($_POST['username']);
if (isset($_POST['password']))
$password = fix_string($_POST['password']);
if (isset($_POST['age']))
$age = fix_string($_POST['age']);
if (isset($_POST['email']))
$email = fix_string($_POST['email']);
$fail = validate_forename($forename);
$fail .= validate_surname($surname);
$fail .= validate_username($username);
$fail .= validate_password($password);
$fail .= validate_age($age);
$fail .= validate_email($email);
echo "<!DOCTYPE html>\n<html><head><title>An Example Form</title>";
if ($fail == "")
{
echo "</head><body>Form data successfully validated:
$forename, $surname, $username, $password, $age, $email.</body></html>";
// This is where you would enter the posted fields into a database,
// preferably using hash encryption for the password.
exit;
}
echo <<<_END
<!-- The HTML/JavaScript section -->
<style>
.signup {
border: 1px solid #999999;
font: normal 14px helvetica; color:#444444;
}
</style>
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else { alert(fail); return false }
}
function validateForename(field)
{
return (field == "") ? "No Forename was entered.\n" : ""
}
function validateSurname(field)
{
return (field == "") ? "No Surname was entered.\n" : ""
}
function validateUsername(field)
{
if (field == "") return "No Username was entered.\n"
else if (field.length < 5)
return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field))
return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field)
{
if (field == "") return "No Password was entered.\n"
else if (field.length < 6)
return "Passwords must be at least 6 characters.\n"
else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) ||
!/[0-9]/.test(field))
return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field)
{
if (isNaN(field)) return "No Age was entered.\n"
else if (field < 18 || field > 110)
return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field)
{
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) &&
(field.indexOf("@") > 0)) ||
/[^a-zA-Z0-9.@_-]/.test(field))
return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<tr><td colspan="2">Sorry, the following errors were found<br>
in your form: <p><font color=red size=1><i>$fail</i></font></p>
</td></tr>
<form method="post" action="adduser.php" onSubmit="return validate(this)">
<tr><td>Forename</td>
<td><input type="text" maxlength="32" name="forename" value="$forename">
</td></tr><tr><td>Surname</td>
<td><input type="text" maxlength="32" name="surname" value="$surname">
</td></tr><tr><td>Username</td>
<td><input type="text" maxlength="16" name="username" value="$username">
</td></tr><tr><td>Password</td>
<td><input type="text" maxlength="12" name="password" value="$password">
</td></tr><tr><td>Age</td>
<td><input type="text" maxlength="3" name="age" value="$age">
</td></tr><tr><td>Email</td>
<td><input type="text" maxlength="64" name="email" value="$email">
</td></tr><tr><td colspan="2" align="center"><input type="submit"
value="Signup"></td></tr>
</form>
</table>
</body>
</html>
_END;
// The PHP functions
function validate_forename($field)
{
return ($field == "") ? "No Forename was entered<br>": "";
}
function validate_surname($field)
{
return($field == "") ? "No Surname was entered<br>" : "";
}
function validate_username($field)
{
if ($field == "") return "No Username was entered<br>";
else if (strlen($field) < 5)
return "Usernames must be at least 5 characters<br>";
else if (preg_match("/[^a-zA-Z0-9_-]/", $field))
return "Only letters, numbers, - and _ in usernames<br>";
return "";
}
function validate_password($field)
{
if ($field == "") return "No Password was entered<br>";
else if (strlen($field) < 6)
return "Passwords must be at least 6 characters<br>";
else if (!preg_match("/[a-z]/", $field) ||
!preg_match("/[A-Z]/", $field) ||
!preg_match("/[0-9]/", $field))
return "Passwords require 1 each of a-z, A-Z and 0-9<br>";
return "";
}
function validate_age($field)
{
if ($field == "") return "No Age was entered<br>";
else if ($field < 18 || $field > 110)
return "Age must be between 18 and 110<br>";
return "";
}
function validate_email($field)
{
if ($field == "") return "No Email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "@") > 0)) ||
preg_match("/[^a-zA-Z0-9.@_-]/", $field))
return "The Email address is invalid<br>";
return "";
}
function fix_string($string)
{
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return htmlentities ($string);
}
?>
+46
View File
@@ -0,0 +1,46 @@
<?php // authenticate.php
require_once 'login.php';
try
{
$pdo = new PDO($attr, $user, $pass, $opts);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW']))
{
$un_temp = sanitise($pdo, $_SERVER['PHP_AUTH_USER']);
$pw_temp = sanitise($pdo, $_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username=$un_temp";
$result = $pdo->query($query);
if (!$result->rowCount()) die("User not found");
$row = $result->fetch();
$fn = $row['forename'];
$sn = $row['surname'];
$un = $row['username'];
$pw = $row['password'];
if (password_verify(str_replace("'", "", $pw_temp), $pw))
echo htmlspecialchars("$fn $sn : Hi $fn,
you are now logged in as '$un'");
else die("Invalid username/password combination");
}
else
{
header('WWW-Authenticate: Basic realm="Restricted Area"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function sanitise($pdo, $str)
{
$str = htmlentities($str);
return $pdo->quote($str);
}
?>
+54
View File
@@ -0,0 +1,54 @@
<?php // authenticate2.php
require_once 'login.php';
try
{
$pdo = new PDO($attr, $user, $pass, $opts);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW']))
{
$un_temp = sanitise($pdo, $_SERVER['PHP_AUTH_USER']);
$pw_temp = sanitise($pdo, $_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username=$un_temp";
$result = $pdo->query($query);
if (!$result->rowCount()) die("User not found");
$row = $result->fetch();
$fn = $row['forename'];
$sn = $row['surname'];
$un = $row['username'];
$pw = $row['password'];
if (password_verify(str_replace("'", "", $pw_temp), $pw))
{
session_start();
$_SESSION['forename'] = $fn;
$_SESSION['surname'] = $sn;
echo htmlspecialchars("$fn $sn : Hi $fn,
you are now logged in as '$un'");
die ("<p><a href='continue.php'>Click here to continue</a></p>");
}
else die("Invalid username/password combination");
}
else
{
header('WWW-Authenticate: Basic realm="Restricted Area"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function sanitise($pdo, $str)
{
$str = htmlentities($str);
return $pdo->quote($str);
}
?>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

+35
View File
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html> <!-- backgroundimages.html -->
<head>
<title>CSS3 Multiple Backgrounds Example</title>
<style>
.border {
font-family:'Times New Roman';
font-style :italic;
font-size :170%;
text-align :center;
padding :60px;
width :350px;
height :500px;
background :url('b1.gif') top left no-repeat,
url('b2.gif') top right no-repeat,
url('b3.gif') bottom left no-repeat,
url('b4.gif') bottom right no-repeat,
url('ba.gif') top repeat-x,
url('bb.gif') left repeat-y,
url('bc.gif') right repeat-y,
url('bd.gif') bottom repeat-x
}
</style>
</head>
<body>
<div class='border'>
<h1>Employee of the month</h1>
<h2>Awarded To:</h2>
<h3>__________________</h3>
<h2>Date:</h2>
<h3>___/___/_____</h3>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

+79
View File
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html> <!-- borderradius.html -->
<head>
<title>CSS3 Border Radius Examples</title>
<style>
.box {
margin-bottom:10px;
font-family :'Courier New', monospace;
font-size :12pt;
text-align :center;
padding :10px;
width :380px;
height :75px;
border :10px solid #006;
}
.b1 {
-moz-border-radius :40px;
-webkit-border-radius:40px;
border-radius :40px;
}
.b2 {
-moz-border-radius :40px 40px 20px 20px;
-webkit-border-radius:40px 40px 20px 20px;
border-radius :40px 40px 20px 20px;
}
.b3 {
-moz-border-radius-topleft :20px;
-moz-border-radius-topright :40px;
-moz-border-radius-bottomleft :60px;
-moz-border-radius-bottomright :80px;
-webkit-border-top-left-radius :20px;
-webkit-border-top-right-radius :40px;
-webkit-border-bottom-left-radius :60px;
-webkit-border-bottom-right-radius:80px;
border-top-left-radius :20px;
border-top-right-radius :40px;
border-bottom-left-radius :60px;
border-bottom-right-radius :80px;
}
.b4 {
-moz-border-radius-topleft :40px 20px;
-moz-border-radius-topright :40px 20px;
-moz-border-radius-bottomleft :20px 40px;
-moz-border-radius-bottomright :20px 40px;
-webkit-border-top-left-radius :40px 20px;
-webkit-border-top-right-radius :40px 20px;
-webkit-border-bottom-left-radius :20px 40px;
-webkit-border-bottom-right-radius:20px 40px;
border-top-left-radius :40px 20px;
border-top-right-radius :40px 20px;
border-bottom-left-radius :20px 40px;
border-bottom-right-radius :20px 40px;
}
</style>
</head>
<body>
<div class='box b1'>
border-radius:40px;
</div>
<div class='box b2'>
border-radius:40px 40px 20px 20px;
</div>
<div class='box b3'>
border-top-left-radius &nbsp;&nbsp;&nbsp;:20px;<br>
border-top-right-radius &nbsp;&nbsp;:40px;<br>
border-bottom-left-radius :60px;<br>
border-bottom-right-radius:80px;
</div>
<div class='box b4'>
border-top-left-radius &nbsp;&nbsp;&nbsp;:40px 20px;<br>
border-top-right-radius &nbsp;&nbsp;:40px 20px;<br>
border-bottom-left-radius :20px 40px;<br>
border-bottom-right-radius:20px 40px;
</div>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
<?php // continue.php
session_start();
if (isset($_SESSION['forename']))
{
$forename = htmlspecialchars($_SESSION['forename']);
$surname = htmlspecialchars($_SESSION['surname']);
echo "Welcome back $forename.<br>
Your full name is $forename $surname.<br>";
}
else echo "Please <a href='authenticate2.php'>Click Here</a> to log in.";
?>
+23
View File
@@ -0,0 +1,23 @@
<?php // continue.php = version 2
session_start();
if (isset($_SESSION['forename']))
{
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
destroy_session_and_data();
echo htmlspecialchars("Welcome back $forename");
echo "<br>";
echo htmlspecialchars("Your full name is $forename $surname.");
}
else echo "Please <a href='authenticate.php'>click here</a> to log in.";
function destroy_session_and_data()
{
$_SESSION = array();
setcookie(session_name(), '', time() - 2592000, '/');
session_destroy();
}
?>
+47
View File
@@ -0,0 +1,47 @@
<?php // convert.php
$f = $c = '';
if (isset($_POST['f'])) $f = sanitizeString($_POST['f']);
if (isset($_POST['c'])) $c = sanitizeString($_POST['c']);
if (is_numeric($f))
{
$c = intval((5 / 9) * ($f - 32));
$out = "$f &deg;f equals $c &deg;c";
}
elseif(is_numeric($c))
{
$f = intval((9 / 5) * $c + 32);
$out = "$c &deg;c equals $f &deg;f";
}
else $out = "";
echo <<<_END
<html>
<head>
<title>Temperature Converter</title>
</head>
<body>
<pre>
Enter either Fahrenheit or Celsius and click on Convert
<b>$out</b>
<form method="post" action="convert.php">
Fahrenheit <input type="text" name="f" size="7">
Celsius <input type="text" name="c" size="7">
<input type="submit" value="Convert">
</form>
</pre>
</body>
</html>
_END;
function sanitizeString($var)
{
if (get_magic_quotes_gpc())
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
+4
View File
@@ -0,0 +1,4 @@
<?php // copyfile.php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
echo "File successfully copied to 'testfile2.txt'";
?>
+5
View File
@@ -0,0 +1,5 @@
<?php // copyfile2.php
if (!copy('testfile.txt', 'testfile2.txt'))
echo "Could not copy file";
else echo "File successfully copied to 'testfile2.txt'";
?>
+4
View File
@@ -0,0 +1,4 @@
<?php // deletefile.php
if (!unlink('testfile2.new')) echo "Could not delete file";
else echo "File 'testfile2.new' successfully deleted";
?>
+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE HTML>
<html> <!-- draganddrop.html -->
<head>
<title>Drag and Drop</title>
<script src='OSC.js'></script>
<style>
#dest {
background:lightblue;
border :1px solid #444;
width :320px;
height :100px;
padding :10px;
}
</style>
</head>
<body>
<div id='dest' ondrop='drop(event)' ondragover='allow(event)'></div><br>
Drag the images below into the above element<br><br>
<img id='source1' src='image1.png' draggable='true' ondragstart='drag(event)'>
<img id='source2' src='image2.png' draggable='true' ondragstart='drag(event)'>
<img id='source3' src='image3.png' draggable='true' ondragstart='drag(event)'>
<script>
function allow(event)
{
event.preventDefault()
}
function drag(event)
{
event.dataTransfer.setData('image/png', event.target.id)
}
function drop(event)
{
event.preventDefault()
var data=event.dataTransfer.getData('image/png')
event.target.appendChild(O(data))
}
</script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
<?php // exec.php
$cmd = "dir"; // Windows
// $cmd = "ls"; // Linux, Unix & Mac
exec(escapeshellcmd($cmd), $output, $status);
if ($status) echo "Exec command failed";
else
{
echo "<pre>";
foreach($output as $line) echo htmlspecialchars("$line\n");
echo "</pre>";
}
?>
+24
View File
@@ -0,0 +1,24 @@
<?php //fetchrow.php
require_once 'login.php';
try
{
$pdo = new PDO($attr, $user, $pass, $opts);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$query = "SELECT * FROM classics";
$result = $pdo->query($query);
while ($row = $result->fetch(PDO::FETCH_BOTH)) // Style of fetch
{
echo 'Author: ' . htmlspecialchars($row['author']) . "<br>";
echo 'Title: ' . htmlspecialchars($row['title']) . "<br>";
echo 'Category: ' . htmlspecialchars($row['category']) . "<br>";
echo 'Year: ' . htmlspecialchars($row['year']) . "<br>";
echo 'ISBN: ' . htmlspecialchars($row['isbn']) . "<br><br>";
}
?>
+16
View File
@@ -0,0 +1,16 @@
<?php // formtest.php
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
<form method="post" action="formtest.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
+20
View File
@@ -0,0 +1,20 @@
<?php // formtest2.php
if (isset($_POST['name'])) $name = $_POST['name'];
else $name = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your name is: $name<br>
<form method="post" action="formtest2.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
+42
View File
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html> <!-- geolocation.html -->
<head>
<title>Geolocation Example</title>
</head>
<body>
<script>
if (typeof navigator.geolocation == 'undefined')
alert("Geolocation not supported.")
else
navigator.geolocation.getCurrentPosition(granted, denied)
function granted(position)
{
var lat = position.coords.latitude
var lon = position.coords.longitude
alert("Permission Granted. You are at location:\n\n"
+ lat + ", " + lon +
"\n\nClick 'OK' to load Google Maps with your location")
window.location.replace("https://www.google.com/maps/@"
+ lat + "," + lon + ",14z")
}
function denied(error)
{
var message
switch(error.code)
{
case 1: message = 'Permission Denied'; break;
case 2: message = 'Position Unavailable'; break;
case 3: message = 'Operation Timed Out'; break;
case 4: message = 'Unknown Error'; break;
}
alert("Geolocation Error: " + message)
}
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

+51
View File
@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html>
<head>
<title>Using JavaScript Cookies</title>
<script>
function SaveCookie(name, value, seconds, path, domain, secure)
{
var date = new Date()
date.setTime(parseInt(date.getTime() + seconds * 1000))
var expires = seconds ? '; expires=' + date.toGMTString() : ''
path = path ? '; path=' + path : ''
domain = domain ? '; domain=' + domain : ''
secure = secure ? '; secure=' + secure : ''
document.cookie = name + '=' + escape(value) + expires + path
}
function ReadCookie(name, value, seconds, path, domain, secure)
{
if (!document.cookie.length) return false
else
{
var start = document.cookie.indexOf(name + '=')
if (start == -1) return false
else
{
start += name.length + 1
var end = document.cookie.indexOf(';', start)
end = (end == -1) ? document.cookie.length : end
return unescape(document.cookie.substring(start, end))
}
}
}
function DeleteCookie(name, value, seconds, path, domain, secure)
{
SaveCookie(name, '', -60)
}
</script>
</head>
<body>
<p>The first time this page loads no cookie should have been set and the alert window should show that the cookie with the name <b>test</b> has the value <i>false</i> (meaning it is not set).</p>
<p>After you click OK a value is assigned to the cookie <b>test</b>. To see this new cookie's value click Reload.</p>
<script>
alert("The value of the cookie 'test' is: " + ReadCookie('test'))
SaveCookie('test', 'I love cookies')
</script>
</body>
</html>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+18
View File
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html> <!-- jqueryasyncget.htm -->
<head>
<title>jQuery Asynchronous Get</title>
<script src='jquery-3.5.1.min.js'></script>
</head>
<body style='text-align:center'>
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
$.get('urlget.php?url=amazon.com/gp/aw', function(data)
{
$('#info').html(data)
} )
</script>
</body>
</html>
+18
View File
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html> <!-- jqueryasyncpost.htm -->
<head>
<title>jQuery Asynchronous Post</title>
<script src='jquery-3.5.1.min.js'></script>
</head>
<body style='text-align:center'>
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
$.post('urlpost.php', { url : 'amazon.com/gp/aw' }, function(data)
{
$('#info').html(data)
} )
</script>
</body>
</html>
+12
View File
@@ -0,0 +1,12 @@
<html>
<head>
<title>Link Test</title>
</head>
<body>
<a id="mylink" href="http://mysite.com">Click me</a><br>
<script>
url = document.links.mylink.href
document.write('The URL is ' + url)
</script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
<?php // login.php
$host = 'localhost';
$data = 'publications';
$user = 'root'; // Change as necessary
$pass = 'mysql'; // Change as necessary
$chrs = 'utf8mb4';
$attr = "mysql:host=$host;dbname=$data;charset=$chrs";
$opts =
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
?>
+5
View File
@@ -0,0 +1,5 @@
<?php // movefile.php
if (!rename('testfile2.txt', 'testfile2.new'))
echo "Could not rename file";
else echo "File successfully renamed to 'testfile2.new'";
?>
+38
View File
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html> <!-- multiplecolumns.html -->
<head>
<title>Multiple Columns</title>
<style>
.columns {
text-align :justify;
font-size :16pt;
-moz-column-count :3;
-moz-column-gap :1em;
-moz-column-rule :1px solid black;
-webkit-column-count:3;
-webkit-column-gap :1em;
-webkit-column-rule :1px solid black;
column-count :3;
column-gap :1em;
column-rule :1px solid black;
}
</style>
</head>
<body>
<div class='columns'>
Now is the winter of our discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths;
Our bruised arms hung up for monuments;
Our stern alarums changed to merry meetings,
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now, instead of mounting barded steeds
To fright the souls of fearful adversaries,
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
</div>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
<script>
onerror = errorHandler
document.writ("Welcome to this website") // Deliberate error ... writ(
function errorHandler(message, url, line)
{
out = "Sorry, an error was encountered.\n\n";
out += "Error: " + message + "\n";
out += "URL: " + url + "\n";
out += "Line: " + line + "\n\n";
out += "Click OK to continue.\n\n";
alert(out);
return true;
}
</script>
+16
View File
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<title>Using Cookies</title>
</head>
<body>
<p>The first time this page loads no cookie should have been set and the message below should show that the cookie with the name <b>test</b> has the value <i>false</i> (meaning it is not set).</p>
<p>But then a value is assigned to the cookie <b>test</b>. To see this new cookie's value click Reload.</p>
<?php
$test = 'false';
if (isset($_COOKIE['test'])) $test = $_COOKIE['test'];
echo "<p><b>The value of the cookie 'test' is: $test</b></p>";
setcookie('test', 'I love cookies');
?>
</body>
</html>
+24
View File
@@ -0,0 +1,24 @@
<?php // query.php
require_once 'login.php';
try
{
$pdo = new PDO($attr, $user, $pass, $opts);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$query = "SELECT * FROM classics";
$result = $pdo->query($query);
while ($row = $result->fetch())
{
echo 'Author: ' . htmlspecialchars($row['author']) . "<br>";
echo 'Title: ' . htmlspecialchars($row['title']) . "<br>";
echo 'Category: ' . htmlspecialchars($row['category']) . "<br>";
echo 'Year: ' . htmlspecialchars($row['year']) . "<br>";
echo 'ISBN: ' . htmlspecialchars($row['isbn']) . "<br><br>";
}
?>
+8
View File
@@ -0,0 +1,8 @@
<?php // sessiontest.php
session_start();
if (!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else ++$_SESSION['count'];
echo $_SESSION['count'];
?>
+49
View File
@@ -0,0 +1,49 @@
<?php //setupusers.php
require_once 'login.php';
try
{
$pdo = new PDO($attr, $user, $pass, $opts);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$query = "CREATE TABLE users (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
)";
$result = $pdo->query($query);
$forename = 'Bill';
$surname = 'Smith';
$username = 'bsmith';
$password = 'mysecret';
$hash = password_hash($password, PASSWORD_DEFAULT);
add_user($pdo, $forename, $surname, $username, $hash);
$forename = 'Pauline';
$surname = 'Jones';
$username = 'pjones';
$password = 'acrobat';
$hash = password_hash($password, PASSWORD_DEFAULT);
add_user($pdo, $forename, $surname, $username, $hash);
function add_user($pdo, $fn, $sn, $un, $pw)
{
$stmt = $pdo->prepare('INSERT INTO users VALUES(?,?,?,?)');
$stmt->bindParam(1, $fn, PDO::PARAM_STR, 32);
$stmt->bindParam(2, $sn, PDO::PARAM_STR, 32);
$stmt->bindParam(3, $un, PDO::PARAM_STR, 32);
$stmt->bindParam(4, $pw, PDO::PARAM_STR, 255);
$stmt->execute([$fn, $sn, $un, $pw]);
}
?>
+78
View File
@@ -0,0 +1,78 @@
<?php // sqltest.php
require_once 'login.php';
try
{
$pdo = new PDO($attr, $user, $pass, $opts);
}
catch (\PDOException $e)
{
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post($pdo, 'isbn');
$query = "DELETE FROM classics WHERE isbn=$isbn";
$result = $pdo->query($query);
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($pdo, 'author');
$title = get_post($pdo, 'title');
$category = get_post($pdo, 'category');
$year = get_post($pdo, 'year');
$isbn = get_post($pdo, 'isbn');
$query = "INSERT INTO classics VALUES" .
"($author, $title, $category, $year, $isbn)";
$result = $pdo->query($query);
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author">
Title <input type="text" name="title">
Category <input type="text" name="category">
Year <input type="text" name="year">
ISBN <input type="text" name="isbn">
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = $pdo->query($query);
while ($row = $result->fetch())
{
$r0 = htmlspecialchars($row['author']);
$r1 = htmlspecialchars($row['title']);
$r2 = htmlspecialchars($row['category']);
$r3 = htmlspecialchars($row['year']);
$r4 = htmlspecialchars($row['isbn']);
echo <<<_END
<pre>
Author $r0
Title $r1
Category $r2
Year $r3
ISBN $r4
</pre>
<form action='sqltest.php' method='post'>
<input type='hidden' name='delete' value='yes'>
<input type='hidden' name='isbn' value='$r4'>
<input type='submit' value='DELETE RECORD'></form>
_END;
}
function get_post($pdo, $var)
{
return $pdo->quote($_POST[$var]);
}
?>
+10
View File
@@ -0,0 +1,10 @@
<html>
<head>
<title>Hello World</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World)
</script>
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
<?php // test1.php
$username = "Fred Smith";
echo $username;
echo "<br>";
$current_user = $username;
echo $current_user;
?>
+4
View File
@@ -0,0 +1,4 @@
<?php // test2.php
echo "a: [" . TRUE . "]<br>";
echo "b: [" . FALSE . "]<br>";
?>
+14
View File
@@ -0,0 +1,14 @@
<?php // testfile.php
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>
+9
View File
@@ -0,0 +1,9 @@
<?php // update.php
$fh = fopen("testfile.txt", 'r+') or die("Failed to open file");
$text = fgets($fh);
fseek($fh, 0, SEEK_END);
fwrite($fh, "$text") or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' successfully updated";
?>
+22
View File
@@ -0,0 +1,22 @@
<?php // upload.php
echo <<<_END
<html>
<head>
<title>PHP Form Upload</title>
</head>
<body>
<form method='post' action='upload.php' enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='10'>
<input type='submit' value='Upload'>
</form>
_END;
if ($_FILES)
{
$name = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $name);
echo "Uploaded image '$name'<br><img src='$name'>";
}
echo "</body></html>";
?>
+39
View File
@@ -0,0 +1,39 @@
<?php //upload2.php
echo <<<_END
<html>
<head>
<title>PHP Form Upload</title>
</head>
<body>
<form method='post' action='upload2.php' enctype='multipart/form-data'>
Select a JPG, GIF, PNG or TIF File:
<input type='file' name='filename' size='10'>
<input type='submit' value='Upload'>
</form>
_END;
if ($_FILES)
{
$name = $_FILES['filename']['name'];
switch($_FILES['filename']['type'])
{
case 'image/jpeg': $ext = 'jpg'; break;
case 'image/gif': $ext = 'gif'; break;
case 'image/png': $ext = 'png'; break;
case 'image/tiff': $ext = 'tif'; break;
default: $ext = ''; break;
}
if ($ext)
{
$n = "image.$ext";
move_uploaded_file($_FILES['filename']['tmp_name'], $n);
echo "Uploaded image '$name' as '$n':<br>";
echo "<img src='$n'>";
}
else echo "'$name' is not an accepted image file";
}
else echo "No image has been uploaded";
echo "</body></html>";
?>
+62
View File
@@ -0,0 +1,62 @@
<!DOCTYPE html>
<html> <!-- urlget.html -->
<head>
<title>Asynchronous Communication Example</title>
</head>
<body style='text-align:center'>
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
nocache = "&nocache=" + Math.random() * 1000000
request = new asyncRequest()
request.open("GET", "urlget.php?url=news.com" + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Communication error: No data received")
}
else alert( "Communication error: " + this.statusText)
}
}
request.send(null)
function asyncRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
</script>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
<?php // urlget.php
if (isset($_GET['url']))
{
echo file_get_contents("http://".sanitizeString($_GET['url']));
}
function sanitizeString($var)
{
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
+67
View File
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html> <!-- urlpost.html -->
<head>
<title>Asynchronous Communication Example</title>
</head>
<body style='text-align:center'>
<h1>Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
params = "url=news.com"
request = new asyncRequest()
request.open("POST", "urlpost.php", true)
request.setRequestHeader("Content-type",
"application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Communication error: No data received")
}
else alert( "Communication error: " + this.statusText)
}
}
request.send(params)
function asyncRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
</script>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
<?php // urlpost.php
if (isset($_POST['url']))
{
echo file_get_contents("http://" . SanitizeString($_POST['url']));
}
function SanitizeString($var)
{
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
+98
View File
@@ -0,0 +1,98 @@
<!DOCTYPE html>
<html>
<head>
<title>An Example Form</title>
<style>
.signup {
border:1px solid #999999;
font: normal 14px helvetica;
color: #444444;
}
</style>
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else { alert(fail); return false }
}
function validateForename(field)
{
return (field == "") ? "No Forename was entered.\n" : ""
}
function validateSurname(field)
{
return (field == "") ? "No Surname was entered.\n" : ""
}
function validateUsername(field)
{
if (field == "") return "No Username was entered.\n"
else if (field.length < 5)
return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field))
return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field)
{
if (field == "") return "No Password was entered.\n"
else if (field.length < 6)
return "Passwords must be at least 6 characters.\n"
else if (! /[a-z]/.test(field) ||
! /[A-Z]/.test(field) ||
! /[0-9]/.test(field))
return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field)
{
if (isNaN(field)) return "No Age was entered.\\n"
else if (field < 18 || field > 110)
return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field)
{
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) &&
(field.indexOf("@") > 0)) ||
/[^a-zA-Z0-9.@_-]/.test(field))
return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<form method="post" action="adduser.php" onsubmit="return validate(this)">
<tr><td>Forename</td>
<td><input type="text" maxlength="32" name="forename"></td></tr>
<tr><td>Surname</td>
<td><input type="text" maxlength="32" name="surname"></td></tr>
<tr><td>Username</td>
<td><input type="text" maxlength="16" name="username"></td></tr>
<tr><td>Password</td>
<td><input type="text" maxlength="12" name="password"></td></tr>
<tr><td>Age</td>
<td><input type="text" maxlength="3" name="age"></td></tr>
<tr><td>Email</td>
<td><input type="text" maxlength="64" name="email"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Signup"></td></tr>
</form>
</table>
</body>
</html>
+70
View File
@@ -0,0 +1,70 @@
<!DOCTYPE html>
<html> <!-- xmlget.html -->
<head>
<title>Asynchronous Communication Example</title>
</head>
<body>
<h1>Loading XML data into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
nocache = "&nocache=" + Math.random() * 1000000
url = "rss.news.yahoo.com/rss/topstories"
out = "";
request = new asyncRequest()
request.open("GET", "xmlget.php?url=" + url + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
titles = this.responseXML.getElementsByTagName('title')
for (j = 0 ; j < titles.length ; ++j)
{
out += titles[j].childNodes[0].nodeValue + '<br>'
}
document.getElementById('info').innerHTML = out
}
else alert("Communication error: No data received")
}
else alert( "Communication error: " + this.statusText)
}
}
request.send(null)
function asyncRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
</script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
<?php // xmlget.php
if (isset($_GET['url']))
{
header('Content-Type: text/xml');
echo file_get_contents("http://".sanitizeString($_GET['url']));
}
function sanitizeString($var)
{
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>