Test Phase & Pre - Final Question by M. Usman
Test Phase & Pre - Final Question by M. Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
A database-driven Web site is a Web site that uses a database to gather, display, or manipulate
information
◦ Databases
MS Access
MySQL, SQL
◦ Integration tools
What is PHP?
What Do I Need?
Install a web server on your own PC, and then install PHP and MySQL
Configuration Steps
PHP program can be run under various like WAMP, XAMPP etc.
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
WAMP Server: this server is a web development platform which helps in creating dynamic
web applications.
XAMPP Server
After downloading, just follow the following step to start xampp server:
Step1
Install XAMPP
Step2
Step3
Now create your first php program in xampp and name it as “add.php”:
<html>
<head><title>Addition php</title></head>
<body>
<?php # operator
$val1 = 20;
$val2 = 20;
</body>
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
</html>
Step4
Now double click on “XAAMP CONTROL PANEL” on desktop and START “Apache”
(icon also appears on the bottom)
Step5
Step6
Step7
Click on “add.php”
PHP Syntax
A PHP file normally contains HTML tags, and some PHP scripting code.
Variables can store data of different types, and different data types can do different things.
String
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
Integer
Float (double)
Boolean
Array
Object
NULL
PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Examples :
$y = 10.5;
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume.
A variable starts with the $ sign, followed by the name of the variable
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
<?php
$txt = “Pakistan";
echo "I love $txt!";
?>
Output will be
I love Pakistan!
Code :
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type
of the variable before using it.
The scope of a variable is the part of the script where the variable can be referenced/used.
◦ local
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
◦ global
◦ static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
Example:
<?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();
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
if statement
if...else statement
switch statement
PHP: if Statement
The if statement is used to execute some code only if a specified condition is true.
Syntax
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
Output:
Use the if.... else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
<?php
$t = date("H");
}
?>
if...elseif....else Statement
Use the if....elseif...else statement to specify a new condition to test, if the first condition is
false.
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise, it will output "Have a good
night!":
<?php
$t = date("H");
Output :
The hour (of the server) is 03, and will give the following message:
The switch statement is used to perform different actions based on different conditions.
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
First we have a single expression n (most often a variable), that is evaluated once. The value of
the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code
from running into the next case automatically. The default statement is used if no match is
found.
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Output:
PHP Loops
PHP Loops:
while
do...while
for
foreach
PHP Array
Example:
<?php
$cars = array(“Honda Civic", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output:
What is an Array?
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
An array can hold many values under a single name, and you can access the values by referring to an
index number.
array();
Types of Array
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
The example below returns the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Output:
12
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Reverse a String
<?php
echo strrev("Hello world!");
The PHP strpos() function searches for a specific text within a string.
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
If a match is found, the function returns the character position of the first match. If no match is found, it
will return FALSE
The example below searches for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The PHP str_replace() function replaces some characters with some other characters in a string.
<?php
echo str_replace("world", "Dolly", "Hello world!");
There are some basic concepts about OOP Which are as follows:
Class
Object
Member Variable
Member function
Inheritance
Parent class.
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
Child Class.
Polymorphism
Overloading
Data Abstraction
Encapsulation
Constructor
Destructor
Class: This is a programmer-defined data type, which includes local functions as well as local
data. You can think of a class as a template for making many instances of the same kind (or
class) of object.
Object An individual instance of the data structure defined by a class. You define a class once
and then make many objects that belong to it. Objects are also known as instance.
Member Variable: These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.
Member function: These are the function defined inside a class and are used to access
object data.
Inheritance: When a class is defined by inheriting existing function of a parent class then
it is called inheritance. Here child class will inherit all or few member functions and
variables of a parent class.
Parent class: A class that is inherited from by another class. This is also called a base
class or super class.
Child Class: A class that inherits from another class. This is also called a subclass or
derived class
Polymorphism: This is an object-oriented concept where same function can be used for
different purposes. For example, function name will remain same but it makes take
different number of arguments and can-do different task.
Overloading: a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments. Similarly, functions can also
be overloaded with different implementation.
Data Abstraction: Any representation of data in which the implementation details are
hidden (abstracted).
Encapsulation: refers to a concept where we encapsulate all the data and member
functions together to form an object.
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
STEP 1:
index.php
class_lib.php
OOP is all about creating modular code, so our object oriented PHP code will be
contained in dedicated files that we will then insert into our normal PHP page using
php 'includes'. In this case all our OO PHP code will be in the PHP file:
class_lib.php
You define your own class by starting with the keyword 'class' followed by the name
<?php
class person {
}
One of the big differences between functions and classes is that a class contains both data
(variables) and functions that form a package called an: 'object'. When you create a
<?php
class person {
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
var $name;
}
Note: The data/variables inside a class (var $name;) are called 'properties'.
In the same way that variables get a different name when created inside a class (they are called:
properties,) functions also referred to by a different name when created inside a class they are
called 'methods'.
<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name; }
}
The $this is a built-in variable (built into all objects) which points to the current
You use $this to access properties and to call other methods of the current class.
function get_name() {
return $this->name;
}
You would never create your PHP classes directly inside your main php pages.
Instead, it is always best practice to create separate php pages that only contain
your classes.
Then you would access your php objects/classes by including them in your main php pages with
either a php 'include' or 'require'.
<html>
<head>
<title>OOP in PHP</title>
</head>
<body>
</body>
</html>
</head>
<body>
<?php
?>
</body>
</html>
The variable $stefan becomes a handle/reference to our newly created person object.
To create an object out of a class, you need to use the 'new' keyword.
When creating/instantiating a class, you can optionally add brackets to the class name.
As we did in the example below. To be clear, you can see in the code below how we can create
multiple objects from the same class.
<body>
<?php
?>
</body>
There are some basic concepts about OOP Which are as follows:
Class
Object
Member Variable
Member function
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
Inheritance
Parent class.
Child Class.
Polymorphism
Overloading
Data Abstraction
Encapsulation
Constructor
Destructor
Class: This is a programmer-defined data type, which includes local functions as well as local
data. You can think of a class as a template for making many instances of the same kind (or
class) of object.
Object An individual instance of the data structure defined by a class. You define a class once
and then make many objects that belong to it. Objects are also known as instance.
Member Variable: These are the variables defined inside a class. This data will be invisible to the
outside of the class and can be accessed via member functions. These variables are called
attribute of the object once an object is created.
Member function: These are the function defined inside a class and are used to access object
data.
Inheritance: When a class is defined by inheriting existing function of a parent class then it is
called inheritance. Here child class will inherit all or few member functions and variables of a
parent class.
Parent class: A class that is inherited from by another class. This is also called a base class or
super class.
Child Class: A class that inherits from another class. This is also called a subclass or derived class
Polymorphism: This is an object-oriented concept where same function can be used for
different purposes. For example, function name will remain same but it makes take different
number of arguments and can-do different task.
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
Data Abstraction: Any representation of data in which the implementation details are hidden
(abstracted).
Encapsulation: refers to a concept where we encapsulate all the data and member functions
together to form an object.
Constructor: refers to a special type of function which will be called automatically whenever
there is an object formation from a class.
Destructor: refers to a special type of function which will be called automatically whenever an
object is deleted or goes out of scope.
We have created our two separate 'person' objects, we can set their properties using
the methods (the setters) we created.
class person {
var $name;
$this->name = $new_name;
}
</head>
<body>
<?php
$stefan->set_name("Stefan John");
?>
</body>
</html>
</head>
<body>
$stefan->set_name("Stefan John");
$jimmy->set_name("Nick Jimmy");
?>
</body>
</html>
You don't have to use methods to access objects properties; you can directly get to them using
the arrow operator (->) and the name of the variable.
</head>
<body>
<?php
$stefan->set_name("Stefan John");
$jimmy->set_name("Nick Jimmy");
?>
</body>
</html>
Constructors
All objects can have a special built-in method called a 'constructor'. Constructors allow you to
initialize your object's properties.
The 'construct' method starts with two underscores (__) and the word 'construct'.
You 'feed' the constructor method by providing a list of arguments (like a function)
<?php
2. class person {
3. var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function set_name($new_name) {
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
$this->name = $new_name;
}
Now that we've created a constructor method, we can provide a value for the $name property
when we create our person objects.
<?php
?>
</body>
</html>
Note: This saves us from having to call the set_name() method reducing the amount of code.
One of the fundamental principles in OOP is 'encapsulation'. The idea is that you create cleaner
better code, if you restrict access to the data structures (properties) in your objects.
You restrict access to class properties using something called 'access modifiers'.
• public
• private
• protected
<?php
class person {
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
var $name;
public $height;
protected $social_insurance;
private $pinn_number;
}
>
Note: When you declare a property with the 'var' keyword, it is considered 'public
When you declare a property as 'private', only the same class can access the property.
When a property is declared 'protected', only the same class and classes derived from that class
can access the property - this has to do with inheritance …more on that later.
Properties declared as 'public' have no access restrictions, meaning anyone can access them.
Like properties, you can control access to methods using one of the three access
modifiers:
public
protected
private
Doing this allows you to efficiently reuse the code found in your base class.
<?php
function __construct($employee_name) {
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
}
?>
Overriding methods
Sometimes (when using inheritance,) you may need to change how a method works from the
base class.
For example, let's say set_name() method in the 'employee' class, had to do something different
than what it does in the 'person' class.
Using :: allows you to specifically name the class where you want PHP to search for
a method - 'person::set_name()' tells PHP to search for set_name() in the 'person‘ class.
<?php
class person {
var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function get_name() {
return $this->name;
}
$this->name = strtoupper($new_name); }
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
}
}
$this->name = $new_name;
}
parent::set_name($new_name);
}
}
function __construct($employee_name) {
$this->set_name($employee_name); }
}
?>
PHP session
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.
So Session variables hold information about one single user, and are available to all pages in one
application
Session variables are set with the PHP global variable: $_SESSION.
Example :
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html> // output : Session variables are set.
Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
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:
<?php
session_start();
?>
<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"] . ".";
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
?>
</body>
</html>
Output :
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html> //output : Array ( [favcolor] => yellow [favanimal] => cat )
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
<?php
session_start();
?>
<html>
<body>
<?php
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
PHP Cookies
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
Only the name parameter is required. All other parameters are optional.
The given example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
<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.
Note: The setcookie() function must appear BEFORE the <html> tag.
Output
Note: You might have to reload the page to see the value of the cookie
To modify a cookie, just set (again) the cookie using the setcookie() function:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
</body>
</html>
Output :
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
<html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
The following example creates a small script that checks whether cookies are enabled. First, try
to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
output : Cookies are enabled
What is an Exception
Exceptions are used to change the normal flow of a script if a specified error occurs.
The code execution will switch to a predefined (custom) exception handler function.
Depending on the situation, the handler may then resume the execution from the saved code
state, terminate the script execution or continue the script from a different location in the code.
When an exception is thrown, the code following it will not be executed, and PHP will try to find
the matching "catch" block.
If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
PHP Question files for Test Phase & Pre-Final viva Solve by Muhammad Usman
(IT OF VU)
We have provided Complete Guidance of CS619.
Contact Us:03086558949
//trigger exception
checkNum(2);
?>
To avoid the error from the example above, we need to create the proper code to handle an
exception.
Try - A function using an exception should be in a "try" block. If the exception does not trigger,
the code will continue as normal. However if the exception triggers, an exception is "thrown"
Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
Catch - A "catch" block retrieves an exception and creates an object containing the exception
information
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Example explained:
The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception
is thrown
The "catch" block retrieves the exception and creates an object ($e) containing the exception
information
The error message from the exception is echoed by calling $e->getMessage() from the exception
object
However, one way to get around the "every throw must have a catch" rule is to set a top level
exception handler to handle errors that slip through.