0% found this document useful (0 votes)
75 views34 pages

Test Phase & Pre - Final Question by M. Usman

PHP is a scripting language used to create dynamic and interactive web pages. It allows integration of web pages with databases by executing PHP scripts on the server. To use PHP, a web server like WAMP or XAMPP is required which provides PHP and database support like MySQL. PHP code is written in .php files and uses conditional statements like if/else to perform different actions based on various conditions.

Uploaded by

Iznah Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views34 pages

Test Phase & Pre - Final Question by M. Usman

PHP is a scripting language used to create dynamic and interactive web pages. It allows integration of web pages with databases by executing PHP scripts on the server. To use PHP, a web server like WAMP or XAMPP is required which provides PHP and database support like MySQL. PHP code is written in .php files and uses conditional statements like if/else to perform different actions based on various conditions.

Uploaded by

Iznah Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

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

What is a database-driven Web site?

 A database-driven Web site is a Web site that uses a database to gather, display, or manipulate
information

How to Integrate Databases and the Web?’

◦ Databases

 MS Access

 MySQL, SQL

 Oracle, Sybase, MS SQL Server

◦ Integration tools

 PHP or CGI, Servlets, JSP, ASP etc.

What is PHP?

 PHP is an abbreviation for "PHP: Hypertext Preprocessor"

 PHP is a widely used, open-source scripting language

 PHP scripts are executed on the server

 PHP is free to download and use

Setting Up Web Server

What Do I Need?

 To start using PHP, you can:

 Find a web host with PHP and MySQL support

 Install a web server on your own PC, and then install PHP and MySQL

Configuration Steps

Webservers for PHP

 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: It is a free open-source cross-platform web server package.

XAMPP Server

 you can download it from the following link:


http://www.apachefriends.org/en/xampp-windows.html

 After downloading, just follow the following step to start xampp server:

Step1

 Install XAMPP

Step2

 Assume you installed xampp in C Drive.


Go to: C:\xampp\htdocs

 Create your own folder, name it for example as PHPCode.

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

print "<h2>php program to add two numbers...</h2><br />";

$val1 = 20;

$val2 = 20;

$sum = $val2 + $val2; /* Assignment operator */ echo "Result(SUM): $sum"; ?>

</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)

 (XAAMP Control Panel Screenshot is on next slide)

Step5

 Type localhost on your browser and press enter:

Step6

 Now type the following on browser:


http://localhost/ PHPCode /
Below screenshot shows php files created under folder “PHPCode”

Step7

 Click on “add.php”

PHP Syntax

Basic PHP Syntax

 A PHP script can be placed anywhere in the document.

 A PHP script starts with <?php and ends with ?>

 The default file extension for PHP files is ".php".

 A PHP file normally contains HTML tags, and some PHP scripting code.

PHP Data Types

 Variables can store data of different types, and different data types can do different things.

 PHP supports the following data types:

 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

Elements of the PHP Programming Environment

PHP Variables

 Variables are "containers" for storing information.

How to Declare PHP Variables

 In PHP, a variable starts with the $ sign, followed by the name of the variable:

 Examples :

$txt = "Hello world!";


$x = 5;

$y = 10.5;

Rules for PHP Variables

 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 must start with a letter or the underscore character

 A variable name cannot start with a number

 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)

 Note : Remember that PHP variable names are case-sensitive!


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

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!

Another example for variable addition:

Code :

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

PHP is a Loosely Typed Language

 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.

Elements of the PHP Programming Environment

PHP Variables Scope

 In PHP, variables can be declared anywhere in the script.

 The scope of a variable is the part of the script where the variable can be referenced/used.

 PHP has three different variable scopes:

◦ 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

Global and Local Scope

 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();

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


?

PHP Conditional Statements

 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.

 In PHP we have the following conditional statements:

 if statement

 if...else statement

 if...elseif.... 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");

if ($t < "20") {


echo "Have a good day!";
}
?>

Output:

Have a good day!

PHP: if...else Statement

 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 ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
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...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");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

 Output :

 The hour (of the server) is 03, and will give the following message:

 Have a good morning!

 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;
}

 How switch statement works:

 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:

 Your favorite color is red!

PHP Loops

Why do we need loop structure?

 In computer programming, a loop is a sequence of instruction s that is continually repeated until


a certain condition is reached.

 PHP Loops:

 In PHP, we have the following looping statements:

 while

 do...while

 for

 foreach

PHP Array

 An array stores multiple values in one single variable.

 Example:

<?php
$cars = array(“Honda Civic", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output:

I like Honda Civic, BMW and Toyota

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:

 $cars1 = “Honda Civic";


$cars2 = "BMW";
$cars3 = "Toyota";

An array can hold many values under a single name, and you can access the values by referring to an
index number.

 Create an Array in PHP

 In PHP, the array() function is used to create an array:

 array();

Types of Array

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index

 Associative arrays - Arrays with named keys

 Multidimensional arrays - Arrays containing one or more arrays

Embedded PHP in HTML 5 & Strings in PHP

 <html>
<body>

<h1>My first PHP page</h1>

<?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

Strings and Regular Expression in PHP

 A string is a sequence of characters, like "Hello world!".

 PHP String Functions:

 Get The Length of a String

 The PHP strlen() function returns the length of a string.

 The example below returns the length of the string "Hello world!":

 <?php
echo strlen("Hello world!"); // outputs 12
?>

 Output:

 12

 Count The Number of Words in a String

 The PHP str_word_count() function counts the number of words in a string:

 <?php
echo str_word_count("Hello world!"); // outputs 2
?>

 The output of the code above will be: 2.

 Reverse a String

 The PHP strrev() function reverses a string:

 <?php
echo strrev("Hello world!");

 // outputs !dlrow olleH


?>

 Search For a Specific Text Within a String

 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 output of the code above will be: 6.

 Note: The first character position in a string is 0 (not 1).

 Replace Text Within a String

 The PHP str_replace() function replaces some characters with some other characters in a string.

 The example below replaces the text "world" with "Dolly":

 <?php
echo str_replace("world", "Dolly", "Hello world!");

 // outputs Hello Dolly!


?>

Object Oriented PHP

Basic Concepts of OOP

 Object-Oriented Programming (OOP) is a type of programming added to php5 that


makes building complex, modular and reusable web applications that much easier.

 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

 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.
How to Create a Class & Objects in PHP

STEP 1:

 First thing we need to do is create two PHP pages:

 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

STEP 2: Create a PHP class

 You define your own class by starting with the keyword 'class' followed by the name

 you want to give your new class.

 <?php

 class person {

 }

STEP 3: Add data to your class

 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

 variable inside a class, it is called a 'property'.

 <?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'.

STEP 4: Add functions/methods to your class

 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'.

 A classes' methods are used to manipulate its' own data / properties.

 <?php

 class person {

 var $name;

 function set_name($new_name) {

 $this->name = $new_name;

 }

 function get_name() {

 return $this->name; }

 }

STEP 5: Getter and setter functions

 We have created two interesting functions/methods:

 get_name() and set_name().

 STEP 6: The '$this' variable

 The $this is a built-in variable (built into all objects) which points to the current

 object. Or in other words, $this is a special self-referencing variable.


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

 You use $this to access properties and to call other methods of the current class.

 function get_name() {

 return $this->name;

 }

STEP 7: Include your class in your main PHP page

 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>

 <?php include("class_lib.php"); ?>

 </head>

 <body>

 </body>

 </html>

STEP 8: Instantiate/create your object

 <?php include("class_lib.php"); ?>

 </head>

 <body>

 <?php

 $stefan = new 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

 ?>

 </body>

 </html>

 The variable $stefan becomes a handle/reference to our newly created person object.

 STEP 9: The 'new' keyword

 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

 $stefan = new person();

 $jimmy = new person();

 ?>

 </body>

Object Oriented PHP

Basic Concepts of OOP

 Object-Oriented Programming (OOP) is a type of programming added to php5 that


makes building complex, modular and reusable web applications that much easier.

 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

 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.

 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.

Working with Objects

Set an objects property

 We have created our two separate 'person' objects, we can set their properties using
the methods (the setters) we created.

 class person {

 var $name;

 function set name($new_name) {

 $this->name = $new_name;

 }

 <?php include("class_lib.php"); ?>

 </head>

 <body>

 <?php

 $stefan = new 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

 $jimmy = new person();

 $stefan->set_name("Stefan John");

 $jimmy->set_name(“ Jimmy Nick");

 ?>

 </body>

 </html>

Accessing an object's data

 <?php include("class_lib.php"); ?>

 </head>

 <body>

 <?php$stefan = new person();

 $jimmy = new person();

 $stefan->set_name("Stefan John");

 $jimmy->set_name("Nick Jimmy");

 echo "Stefan's full name: " . $stefan->get_name();

 echo "Nick's full name: " . $jimmy->get_name();

 ?>

 </body>

 </html>

Directly accessing properties

 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.

 See Example on next slide

 <?php include("class_lib.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

 </head>

 <body>

 <?php

 $stefan = new person();

 $jimmy = new person();

 $stefan->set_name("Stefan John");

 $jimmy->set_name("Nick Jimmy");

 echo "Stefan's full name: " . $stefan->name;

 ?>

 </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)

 after the class name.

 <?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;

 }

Create an object with a constructor

 Now that we've created a constructor method, we can provide a value for the $name property
when we create our person objects.

 For example: $stefan = new person("Stefan John");

 <?php

 $stefan = new person("Stefan Mischook");

 echo "Stefan's full name: " $stefan->get_name();

 ?>

 </body>

 </html>

 Note: This saves us from having to call the set_name() method reducing the amount of code.

Restricting access to properties using 'access modifiers'

 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'.

 There are 3 access modifiers:

 • public

 • private

 • protected

 Public is the default modifier.

 <?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

Restricting access to properties

 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.

Restricting access to methods

 Like properties, you can control access to methods using one of the three access

 modifiers:

 public

 protected

 private

Reusing code the OOP way: inheritance

 Doing this allows you to efficiently reuse the code found in your base class.

 <?php

 // 'extends' is the keyword that enables inheritance

 class employee extends person {

 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

 /* explicitly adding class properties are optional - but is good practice */

class person {

 var $name;

 function __construct($persons_name) {

 $this->name = $persons_name;

 }

 function get_name() {

 return $this->name;

 }

// protected methods and properties restrict //access to those elements

protected function set_name($new_name) {

 if (name != "Jimmy Two Guns") {

 $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

 }

 }

 protected function set_name($new_name) {

 if ($new_name == "Stefan Lamp") {

 $this->name = $new_name;

 }

 else if($new_name == "Johnny Fingers") {

 parent::set_name($new_name);

 }

 }

 function __construct($employee_name) {

 $this->set_name($employee_name); }

 }

 ?>

PHP session

What is a 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

Start a PHP Session


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

 A session is started with the session_start() function.

 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.

Get PHP Session Variable Values

 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 :

 Favorite color is green.


Favorite animal is cat.

Modify a PHP Session Variable

 To change a session variable, just overwrite it:

 <?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 )

Destroy a PHP Session

 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

// remove all session variables


session_unset();

// destroy the session


session_destroy();
?>
</body>
</html>

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

Create Cookies With PHP

 A cookie is created with the setcookie() function.

 Syntax

 setcookie(name, value, expire, path, domain, secure, httponly);

 Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie

 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

 Cookie named 'user' is not set!

 Note: You might have to reload the page to see the value of the cookie

Modify a Cookie Value

 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

echo "Value is: " . $_COOKIE[$cookie_name];


}
?>

</body>
</html>

 Output :

 Cookie 'user' is set!


Value is: John DoeNote: You might have to reload the page to see the new value of the cookie.

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>

 Output: Cookie 'user' is deleted.

Check if Cookies are Enabled

 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

PHP Exception Handling

What is an Exception

 Exceptions are used to change the normal flow of a script if a specified error occurs.

 This is what normally happens when an exception is triggered:

 The current code state is saved.

 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.

Basic Use of Exceptions

 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);
?>

 Fatal error: Uncaught exception 'Exception'


with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw and catch

 To avoid the error from the example above, we need to create the proper code to handle an
exception.

 Proper exception code should include:

 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;
}

//trigger exception in a "try" block


try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
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

//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>

 Example explained:

 The code above throws an exception and catches it:

 The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception
is thrown

 The checkNum() function is called in a "try" block

 The exception within the checkNum() function 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.

You might also like