Professional Documents
Culture Documents
CS310 final term
CS310 final term
WEEK 7
The include statement takes all the text/code/markup that exists in the specified file
and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or text
on multiple pages of a website.
Syntax
include 'filename';
<?php
?>
To include the footer file in a page, use the include statement:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
date(format,timestamp)
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time
The required format parameter of the date() function specifies how to format the
date (or time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to
add additional formatting.
Example
The example below formats today's date in three different ways:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Here are some characters that are commonly used for times:
h - 12-hour format of an hour with leading zeros (01 to 12)
i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
a - Lowercase Ante meridiem and Post meridiem (am or pm)
Example
<?php
date_default_timezone_set("Asia/Karachi");
echo "The time is " . date("h:i:sa");
?>
What is a Cookie?
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.
With PHP, you can both create and retrieve cookie values.
Syntax
Example
<?php
$cookie_name = "user";
$cookie_value = "Ahmed";
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>
<?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>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600,"/");
?>
<html><body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body></html>
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html><body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body></html>
week 8
What is a Session?
A session is a way to store information (in variables) to be used across several pages.
Unlike a cookie, the information is not stored on the users computer.
When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session.
On the internet there is one problem: the web server does not know who you are,
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 etc.). By default, session variables last until the user
closes the browser.
Session variables hold information about one single user, and are available to all
pages in one application.
Example
<?php
// 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>
All session variable values are stored in the global $_SESSION variable
Example
<?php
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>
Example 2
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// remove all session variables
session_unset();
</body></html>
week 9
Sanitize a String
The following example uses the filter_var() function to remove all HTML tags from a
string:
Example
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Sanitize and Validate an Email Address
The following example uses the filter_var() function to first remove all illegal
characters from the $email variable, then check if it is a valid email address:
Example
<?php
$email = "john.doe@example.com";
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
week 10
Introduction to Databases
Data base
A database is an organized collection of data.
Database management system (DBMS)
It is a computer software application, designed to allow the definition, creation,
querying, update, and administration of databases.
Example
Some examples of DBMS are :
MySQL
PostgreSQL
Microsoft SQL Server
Oracle
Sybase
MySQL Database
A free, fast, reliable, easy-to-use, multi-user multi-threaded relational database
system.
SQL (Structured Query Language) is use in MYSQL database system.
It is freely available and released under GPL (GNU General Public License ).
Officially pronounced “my Ess Que Ell” (not my sequel).
Database tools
There are many tools available for handling MY SQL databases such as:
PhpMyAdmin
Is a FREE software tool written in PHP intended to handle the administration of
MySQL over the Internet.
PhpMyAdmin supports a wide range of operations with MySQL, the most frequently
used being the managing of databases, tables, fields, relations, indexes, users,
permissions.
You still have the ability to execute SQL statements directly as well
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
MySQL Connect
Earlier versions of PHP used the MySQL extension. PHP version 5 and after that work
with a MySQL database using:
MySQL Create DB
Examples
SQL Statement:-
When a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
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
The INSERT INTO statement is used to add new records to a MySQL table
SQL Statement: INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
MySQL Get Last ID
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.
Example
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
MySQL Insert in Multiple
Multiple SQL statements must be executed with the mysqli_multi_query() function.
The following examples add three new records to the “student" table:
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
MySQL Prepared
A prepared statement is a feature used to execute the same (or similar) SQL
statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the database. Certain
values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO
student VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on the SQL
statement template, and stores the result without executing it
Execute: At a later time, the application binds the values to the parameters, and the
database executes the statement.
The application may execute the statement as many times as it wants with different
values
Compared to executing SQL statements directly, prepared statements have two main
advantages:
Prepared statements reduces parsing time as the preparation on the query is done
only once (although the statement is executed multiple times)
Bound parameters minimize bandwidth to the server as you need send only the
parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because parameter
values, which are transmitted later using a different protocol, need not be correctly
escaped. If the original statement template is not derived from external input, SQL
injection cannot occur.
Example
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
week 12
The SELECT statement is used to select data from one or more tables:
Example
SELECT column_name(s) FROM table_name
Example
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
MySQL Select Data
The SELECT statement is used to select data from one or more tables:
Example
SELECT column_name(s) FROM table_name
we can use the * character to select ALL columns from a table:
Example
SELECT * FROM table_name
Example
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example(continued)
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example:-
$sql = "SELECT * FROM student Orders LIMIT 05";
When the SQL query above is run, it will return the first 05 records
week 13
When you are manipulating files you must be very careful. You can do a lot of
damage if you do something wrong.
Common errors are: