Skip to content

Instantly share code, notes, and snippets.

@vamonke
Last active November 29, 2018 10:57
Show Gist options
  • Select an option

  • Save vamonke/0633ba6e64fa4c0cbe72b7bc12b3043c to your computer and use it in GitHub Desktop.

Select an option

Save vamonke/0633ba6e64fa4c0cbe72b7bc12b3043c to your computer and use it in GitHub Desktop.
Web Application Design Cheatsheets

IM4717 Web Application Design Cheat sheets

Edited and compiled lab exercises woooo

MySQL Class

1_MYSQL_Connect.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}
echo "Connected successfully";
?> 

2_MYSQL_Create_DB.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
  echo "Database created successfully";
} else {
  echo "Error creating database: ".mysqli_error($conn);
}

mysqli_close($conn);
?> 

3_MYSQL_Create_Table.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}

// sql to create table
$sql = "CREATE TABLE MyGuests (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  firstname VARCHAR(30) NOT NULL,
  lastname VARCHAR(30) NOT NULL,
  email VARCHAR(50),
  reg_date TIMESTAMP
)";

/* NOT NULL - Each row must contain a value for that column, null values are not allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT
*/


if (mysqli_query($conn, $sql)) {
  echo "Table MyGuests created successfully";
} else {
  echo "Error creating table: ".mysqli_error($conn);
}

mysqli_close($conn);
?> 

4_MYSQL_Insert_Data.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}

/* The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted*/

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
  echo "New record created successfully";
} else {
  echo "Error: ".$sql."<br>".mysqli_error($conn);
}

mysqli_close($conn);
?> 

5_MYSQL_Get_Last_ID.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}

/* If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

In the table "MyGuests", the "id" column is an AUTO_INCREMENT field:*/


$sql = "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
  $last_id = mysqli_insert_id($conn);
  echo "New record created successfully. Last inserted ID is: ".$last_id;
} else {
  echo "Error: ".$sql."<br>".mysqli_error($conn);
}

mysqli_close($conn);
?>
 

6_MYSQL_Insert_Multiple.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('Julie', 'Dooley', '[email protected]')";

if (mysqli_multi_query($conn, $sql)) {
  echo "New records created successfully";
} else {
  echo "Error: ".$sql."<br>".mysqli_error($conn);
}

mysqli_close($conn);
?> 

7_MYSQL_Select_Data.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}
/*First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.
*/

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  // output data of each row
  while ($row = mysqli_fetch_assoc($result)) {
    echo "id: ".$row["id"]. " - Name: ".$row["firstname"]. " ".$row["lastname"]. "<br>";
  }
} else {
  echo "0 results";
}

mysqli_close($conn);
?> 

8_MYSQL_Delete_Data.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}
/* Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!*/


// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
  echo "Record deleted successfully";
} else {
  echo "Error deleting record: ".mysqli_error($conn);
}

mysqli_close($conn);
?> 

9_MYSQL_Update_Data.php

<?php
$servername = "localhost";
$username = "f32ee";
$password = "f32ee";
$dbname = "f32ee";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: ".mysqli_connect_error());
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: ".mysqli_error($conn);
}

mysqli_close($conn);
?>

PHP Class

1a_HelloWorld.php

<?php
echo "whatsapp";
?>

1b_Intro.php

<?php
echo "whatsapp, hello "."<br>";
echo 232;

$sametext = "hello";
echo $sametext."<br>";

$somenumber = 400;
echo $somenumber."<br>"; 

echo $sametext.$somenumber;
?>

2_Basic_Math.php

<?php
echo 232+400;

$sametext = "hello";
echo $sametext;

$x = 400;
$y = 1200;

echo $x+$y;
?>

3_Constants.php

<!DOCTYPE html>
<html>
<body>
<?php
/* define(name, value, case-insensitive)
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false */

define("GREETING", "Welcome to Google!");   
echo GREETING;
?>

</body>
</html> 

4b_Strings_functions.php

<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello world!")."<br>"; // outputs 12

echo str_word_count("Hello world!")."<br>";  // outputs 2

echo strrev("Hello world!")."<br>";   // outputs !dlrow olleH

echo strpos("Hello world!", "world")."<br>";   // outputs 6

echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!


?>
 
</body>
</html> 

4_Datatype.php

<!DOCTYPE html>
<html>
<body>
<?php 
$x = 5985;
var_dump($x);

$y = 10.365;
var_dump($y);

$cars = array("Volvo","BMW","Toyota");
var_dump($cars);

?>

</body>
</html> 

5_If_else.php

<?php
$first= 30;
$second = 50;

if ($first==$second)
{
echo "this is correct";
}
else {
	echo "this is wrong";
}

?>

6_If_elseif_else.php

<?php
$var= "Sam";

if ($var=="steve")
  echo "hi Stevo";

else if ($var=="brian")
	echo "hi bri";

else if ($var=="Sam")
	echo "hi sam";

else "wrong";
?>

7_Switch.php

<?php
$country= "UK";

switch ($country) {
	case "USA":	 
		echo "Correct USA";
		break;
	
	case "UK":	 
		echo "Correct UK";
		break;
	
	case "UAE":	 
		echo "Correct UAE";
		break;

	default:
		echo "wrong";
		break; 
}
?>

8_While_loop.php

<?php
$var = 4;

while ($var<=10) {
	echo "$var"."</br>";
	$var++;
}
?>

9_Do_loop.php

<?php
$var = 4;

do {
	echo $var;
	$var++;
} while ($var<5);
?>

Loop_through_indexed_Array.php

<!DOCTYPE html>
<html>

<body>
<?php
    $cars = array("Volvo", "BMW", "Toyota");
    $arrlength = count($cars);
    echo $arrlength. "<br>"; 

    for ($x = 0; $x < $arrlength; $x++) {
        echo $cars[$x];
        echo "<br>";
    }
?>

</body>

</html> 

10_For_loop.php

<?php
for ($var = 1; $var< 10; $var++) {
	echo "Hello world".$var."<br/>";
}

?>

11_Arrays.php

<?php
$name= array ('tom', 'sam', 'gab');

$people[0] = "Jane";
$people[1] = "rake";

echo $name[0].$people[0];
?>

12_Associate_Arrays.php

<?php
$name = array ('fingers'=>'hand', 'teeth'=>'mouth');
echo $name['fingers'];	
?>

13_Adding and modifying elements in array.php

<?php
$name [0] = "tom";
$name [1] = "greg";
$name ["person"]= "bucky";

echo $name["person"];	

?>

14_Array_with_loop.php

<?php
$name= array('tom','bucky','don');

for ($x=0; $x<sizeof($name); $x++) {
  echo $name[$x]."<br/>";
}	

?>

15a_Sort_arrays.php

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
    echo $cars[$x];
    echo "<br>";
}
?>

</body>
</html> 

15_Foreach_array_loop.php

<?php
$name= array('tom','bucky','don');

foreach ($name as $x) {
  echo $x."<br/>";
}	
?>

16_Functions.php

<?php
function test() {
	echo "hello how r you";
}	
	
test();
echo "<br/>"."im fine";
?>

17_Functions_params.php

<?php
function test($sub) {
	echo $sub."Bucky <br/>";
}	
	
test("take it easy");
test("have patience");
?>

18a_Globalscope.php

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
 
function myTest() {
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";
} 
myTest();

echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html> 

18b_Localscope.php

<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
    $x = 5; // local scope
    echo "<p>Variable x inside function is: $x</p>";
} 
myTest();

// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html> 

18c_Globalkeyword.php

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
} 

myTest();  // run function
echo $y; // output the new value for variable $y
?>

</body>
</html> 

18d_Statickeyword.php

<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}

myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>

</body>
</html> 

18_Return_values.php

<?php
function test($a, $b) {
	$total= $a + $b;
	return $total;
}	
	
$c = test(8,9);
echo $c;
?>

19a_Beginning_forms_GET.php

<html>

<body>
  <form action="testerpage2.php" method="get">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
  </form>
</body>

</html>
<?php
/*
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
*/
?>

19a_Beginning_forms_POST.php

<html>

<body>
  <form action="testerpage.php" method="post">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit">
  </form>
</body>

</html>
<?php
// Method = "post" An HTML form is submitted using this method. 

/*
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
*/
?>

19b_Superglobal_PHP_Server.php

<!DOCTYPE html>
<html>
<body>
<?php
// $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

</body>
</html> 

19c_PHP_$Request.php

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"
  Name: <input type="text" name="fname">
  <input type="submit">
</form>
<?php
/*
PHP $_REQUEST is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field
*/

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = htmlspecialchars($_REQUEST['fname']); 
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}

?>

</body>
</html> 

19d_PHP_$POST.php

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"
  Name: <input type="text" name="fname">
  <input type="submit">
</form>
<?php
/*
PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input
*/
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname']; 
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html> 

20_Date_Function.php

<?php
echo date("m-d-y");
?>

21_Include_Function.php

<?php
echo "Hello friends"
?>

24_Connecting_SQL_Server.php

<?php
// open connection to mysql server
$dbc = mysql_connect('localhost', bucky, 123456);
if (!$dbc) {
  die("Not connected :". mysql_error());
}
?>

25_Selecting_SQL_database.php

<?php
$dbc = mysql_connect('localhost', bucky, 123456);

if (!$dbc) {
  die("Not connected :". mysql_error());
}

// select database
$db_selected = mysql_select_db("firstTable", $dbc);
if (!$db_selected) {
  die("cant be connected :" . mysql_error());
}
?>

26_Testing_database.php

<?php
$dbc = mysql_connect('localhost', bucky, 123456);

if (!$dbc) {
  die("Not connected :". mysql_error());	
}

// select database
$db_selected = mysql_select_db("firstTable", $dbc);

if (!$db_selected) {
  die("Cant connected :" . mysql_error());
}

// test
$query = "UPDATE FirstTable SET email='[email protected]' WHERE name = 'bucky'";
$result = mysql_query ($query);

?>

testerpage.php

<html>
<body>
<?php
  echo $_POST["name"]."<br>";   
  /* Is used to collect form data after submitting an HTML form*/
  echo $_POST["email"]."<br>";
?>

</body>
</html> 

testerpage2.php

<html>
<body>
<?php
  echo $_GET["name"]."<br>";
  /* Is used to collect form data after submitting an HTML form*/
  echo $_GET["email"]."<br>";
?>

</body>
</html> 

testerpage_1.php

<html>
<body>
<?php
  include("21_Include_Function.php");
?>

<h1>Welocome People</h1>
<p>Hey Guys</p>

</body>
</html> 
 

Session Examples

authmain.php

<?php //authmain.php
include "dbconnect.php";
session_start();

if (isset($_POST['userid']) && isset($_POST['password'])) {
  // if the user has just tried to log in
  $userid = $_POST['userid'];
  $password = $_POST['password'];
  $password = md5($password);

  $query = "SELECT * FROM users WHERE username = '$userid' AND password = '$password'";
  $results = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) == 1) { // check for matching user in the database
    // store user id in session
    $_SESSION['valid_user'] = $userid;    
  }
  mysqli_close($conn);
}
?>
<html>
<body>
<h1>Home page</h1>
<?php
  if (isset($_SESSION['valid_user']))
  {
    echo 'You are logged in as: '.$_SESSION['valid_user'].' <br />';
    echo '<a href="logout.php">Log out</a><br />';
  }
  else
  {
    if (isset($userid))
    {
      // if they've tried and failed to log in
      echo 'Could not log you in.<br />';
    }
    else 
    {
      // they have not tried to log in yet or have logged out
      echo 'You are not logged in.<br />';
    }

    // provide form to log in 
    echo '<form method="post" action="authmain.php">';
    echo '<table>';
    echo '<tr><td>Userid:</td>';
    echo '<td><input type="text" name="userid"></td></tr>';
    echo '<tr><td>Password:</td>';
    echo '<td><input type="password" name="password"></td></tr>';
    echo '<tr><td colspan="2" align="center">';
    echo '<input type="submit" value="Log in"></td></tr>';
    echo '</table></form>';
  }
?>
<br />
<a href="members_only.php">Members section</a>
</body>
</html>
 

cart.php

<?php  //cart.php
session_start();
if (!isset($_SESSION['cart'])){
	$_SESSION['cart'] = array();
}
if (isset($_GET['empty'])) {
	unset($_SESSION['cart']);
	header('location: ' . $_SERVER['PHP_SELF']);
	exit();
}
?>
<html>
<head>
<title>Shopping Cart</title>
</head>
<body>
<h1>Your Shopping Cart </h1>
<?php
$items = array(
	'Canadian-Australian Dictionary',
	'As-new parachute (never opened)',
	'Songs of he Goldfish (2CD Set)',
	'Ending PHP4 (O\'Wroxey Press)');
$prices = array(24.95, 1000, 19.99, 34.95);
?>
<table border="1">
	<thead>
	<tr>
		<th>Item Description</th>
		<th>Price</th>
	</tr>
	</thead>
	<tbody>
<?php
$total = 0;
for ($i=0; $i < count($_SESSION['cart']); $i++){
	echo "<tr>";
	echo "<td>" .$items[$_SESSION['cart'][$i]]. "</td>";
	echo "<td align='right'>$";
	echo number_format($prices[$_SESSION['cart'][$i]], 2). "</td>";
	echo "</tr>";
	$total = $total + $prices[$_SESSION['cart'][$i]];
}
?>
	</tbody>
	<tfoot>
	<tr>
		<th align='right'>Total:</th><br>
		<th align='right'>$<?php echo number_format($total, 2); ?>
		</th>
	</tr>
	</tfoot>
</table>
<p><a href="catalog.php">Continue Shopping</a> or
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?empty=1">Empty your cart</a></p>

</body>
</html> 

catalog.php

<?php //catalog.php
session_start();
if (!isset($_SESSION['cart'])){
	$_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
	$_SESSION['cart'][] = $_GET['buy'];
	header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
	exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product catalog</title>
</head>
<body>
<p>Your shopping cart contains <?php
	echo count($_SESSION['cart']); ?> items.</p>
<p><a href="cart.php">View your cart</a></p>

<?php
$items = array(
	'Canadian-Australian Dictionary',
	'As-new parachute (never opened)',
	'Songs of he Goldfish (2CD Set)',
	'Ending PHP4 (O\'Wroxey Press)');
$prices = array(24.95, 1000, 19.99, 34.95);
?>
<table border="1">
	<thead>
	<tr>
		<th>Item Description</th>
		<th>Price</th>
	</tr>
	</thead>
	<tbody>
<?php
for ($i=0; $i<count($items); $i++){
	echo "<tr>";
	echo "<td>" .$items[$i]. "</td>";
	echo "<td>$" .number_format($prices[$i], 2). "</td>";
	echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
	echo "</tr>";
}
?>
	</tbody>
</table>
<p>All prices are in imaginary dollars.</p>
</body>
</html> 

conn.php

<?php
$dbcnx=@mysql_connect('localhost','root','');
if (!$dbcnx)
	die("Could not connect to mysql");
if (!@mysql_select_db ("newijdb"))
	die("Could not find the database");
?> 

cookiecounter..php

<?php //cookiecounter.php
if (!isset($_COOKIE['visits'])){
	$_COOKIE['visits'] = 0;
}

$visits = $_COOKIE['visits'] + 1;
//	setcookie('visits', $visits, time() + 3600 + 24 + 365);
setcookie('visits', $visits, time() + 10);
echo var_dump($_COOKIE). "<br>";

?>
<html>
<head>
<title>Cookie counter</title>
</head>
<body>
<?php
if ($visits > 1) {
	echo "This is visit number $visits.";
} else {// First visit
	echo 'Welcome to my Web site! Click here for a tour!';
}
?>
</body>
</html> 

dbconnect.php

<?php
@$dbcnx = new mysqli('localhost','f32ee','f32ee','f32ee');
// @ to ignore error message display //
if ($dbcnx->connect_error){
	echo "Database is not online"; 
	exit;
	// above 2 statments same as die() //
	}
/*	else
	echo "Congratulations...  MySql is working..";
*/
if (!$dbcnx->select_db ("f32ee"))
	exit("<p>Unable to locate the f32ee database</p>");
?>	 

hellomail.php

<!DOCTYPE html>
<html>
<body>

<h1>Hello Mail</h1>

<p>My first mail test.</p>

<?php
$to      = 'f32ee@localhost';
$subject = 'the subject';
$message = 'hello from php mail';
$headers = 'From: f32ee@localhost' . "\r\n" .
    'Reply-To: f32ee@localhost' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers,'-ff32ee@localhost');
echo ("mail sent to : ".$to);
?> 

</body>
</html>
 

logout.php

<?php
  session_start();
  
  // store to test if they *were* logged in
  $old_user = $_SESSION['valid_user'];  
  unset($_SESSION['valid_user']);
  session_destroy();
?>
<html>
<body>
<h1>Log out</h1>
<?php 
  if (!empty($old_user))
  {
    echo 'Logged out.<br />';
  }
  else
  {
    // if they weren't logged in but came to this page somehow
    echo 'You were not logged in, and so have not been logged out.<br />'; 
  }
?> 
<a href="authmain.php">Back to main page</a>
</body>
</html>
 

members_only.php

<?php
  session_start();

  echo '<h1>Members only</h1>';

  // check session variable

  if (isset($_SESSION['valid_user']))
  {
    echo '<p>You are logged in as '.$_SESSION['valid_user'].'</p>';
    echo '<p>Members only content goes here</p>';
  }
  else
  {
    echo '<p>You are not logged in.</p>';
    echo '<p>Only logged in members may see this page.</p>';
  }

  echo '<a href="authmain.php">Back to main page</a>';
?>
 

multipurpose_page.php

<!DOCTYPE html>
<html>
<body>
<?phpif (!isset($_GET['fname']) or $_GET['fname'] == '') { ?>

<!-- html content here... -->

<form method="get" action="<?php echo $_SERVER['PHP_SELF'];?>" >
Please enter your name: <input type="text" name="fname">
	  <input type="submit">
</form>
<?php} else { ?>
	<br> Name string submitted: <?php echo $_GET['fname']; ?>
	 <p> It also contains a <a href="newpage.php?name= <?php echo urlencode($_GET['fname']); ?> 
	 ">link</a> that passes the name variable on to the next document.</p>
 <?php } ?>

</body>
</html> 

page1.php

<?php  //page1.php
  session_start();
  var_dump($_SESSION);
  $id = session_id();
  echo "<br> Session id in page 1 = $id <br>";
  
  $_SESSION['sess_var'] = "Hello world!";
  $_SESSION['sess_var2'] = "Hello world2!";

  echo 'The content of $_SESSION[\'sess_var\'] is '
        .$_SESSION['sess_var'].'<br />';
  echo 'The content of $_SESSION[\'sess_var2\'] is '
        .$_SESSION['sess_var2'].'<br />';
?>
<a href="page2.php">Next page</a> 
 

page2.php

<?php // page2.php
if (!isset($_SESSION))  session_start();
  var_dump($_SESSION);
  $id = session_id();
  echo "<br> Session id in page 2 = $id <br>";
  
  echo '<br>The content of $_SESSION[\'sess_var2\'] before unset() is '
        .$_SESSION['sess_var2'].'<br />';

  unset($_SESSION['sess_var2']);
?>
<a href="page3.php">Next page</a>
 

page3.php

<?php //page3.php
  session_start();
  var_dump($_SESSION);
  $id = session_id();
  echo "<br> Session id in page 3 = $id <br>";

  echo '<br>The content of $_SESSION[\'sess_var\'] is '
        .$_SESSION['sess_var'].'<br />';
  echo 'The content of $_SESSION[\'sess_var2\'] is '
        .$_SESSION['sess_var2'].'<br />';

  session_destroy();
  $id=session_id();
  echo '<br>The content of $_SESSION[\'sess_var\'] after destroy is '
        .$_SESSION['sess_var'].'<br />';
  echo "<br>Session id after destroy in page 3 = $id <br>";
?> 
 

register.php

<?php // register.php
include "dbconnect.php";
if (isset($_POST['submit'])) {
	if (empty($_POST['username']) || empty ($_POST['password'])
		|| empty ($_POST['password2']) ) {
	echo "All records to be filled in";
	exit;}
	}
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

// echo ("$username" . "<br />". "$password2" . "<br />");
if ($password != $password2) {
	echo "Sorry passwords do not match";
	exit;
	}
$password = md5($password);
// echo $password;
$sql = "INSERT INTO users (username, password) 
		VALUES ('$username', '$password')";
//	echo "<br>". $sql. "<br>";
$result = $dbcnx->query($sql);

if (!$result) 
	echo "Your query failed.";
else
	echo "Welcome ". $username . ". You are now registered";
	
?> 

1.Create_Cookie_w3.php

<?php
/* A cookie is often used to identify a user. 
A cookie is a small file that the server embeds on 
the user's computer. Each time the same computer 
requests a page with a browser, it will send the cookie too.
Syntax ::: setcookie(name, value, expire, path, domain, secure, httponly);*/

$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html> 

2. Delete_Cookie_w3.php

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html> 

3. Start_Session_w3.php

<?php
/* When you work with an application, you open it, 
do some changes, and then you close it. This is much 
like a Session. The computer knows who you are. 
It knows when you start the application and when you end. 
But on the internet there is one problem: the web server 
does not know who you are or what you do, because the HTTP 
address doesn't maintain state.

Session variables solve this problem by storing user
information to be used across multiple pages 
(e.g. username, favorite color, etc).  By default, session variables 
last until the user closes the browser.
Unlike a cookie, the information is not stored on the users computer.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.*/

// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html> 

4. View-Get_Session_w3.php

<?php
/* Next, we create another page from this page, 
we will access the session information we set earlier.

Notice that session variables are not passed individually 
to each new page, instead they are retrieved from the session
we open at the beginning of each page (session_start()).

Also notice that all session variable values are stored
in the global $_SESSION variable:
Session variables are set with the PHP global variable: $_SESSION.*/

session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html> 

5. Destroy_Session_w3.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset(); 

// destroy the session 
session_destroy(); 
?>

</body>
</html> 

Set_Cookie.php

<?php
setcookie('Username','alex',time()+10);
?>

Set_session.php

<?php
session_start();

$_SESSION['Username']= 'alex';
?>

UnSet_Cookie.php

<?php
setcookie('Username','alex',time()+10);
setcookie('Username','alex',time()-10);
?>

Unset_session_login.php

<?php
session_start();
unset($_SESSION['Username']);
?> 

View_Cookie.php

<?php
echo $_COOKIE['Username'];
?>

View_session.php

<?php
session_start();

echo $_SESSION['Username'];
?>

View_session_login.php

<?php
session_start();

if (isset($_SESSION['Username'])) {
	echo 'Welcome, '.$_SESSION['Username'];
} else {
  echo 'Please login';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment