0% found this document useful (0 votes)
26 views

PHP Total PDF

This is php
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

PHP Total PDF

This is php
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Basic building blocks of PHP:

PHP
 PHP stands for " Hypertext Preprocessor".
 PHP scripts are executed on the server so it is a server side scripting language that is
embedded in HTML.
 PHP is a widely-used, open source scripting language , is free to download and use.
 It is integrated with a number of popular databases, including MySQL, Oracle, Microsoft
SQL Server…etc.
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP files have extension " .php "
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>

<?php
// PHP code goes here
?>

A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:

Example

<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

There are some other ways to write php code in html document. Those are ,
Short-open tags
Short or short-open tags look like this −
<?...?>
Short tags are, as one might expect, the shortest option You must do one of two things to
enable PHP to recognize.
ASP-style tags
ASP-style tags used by Active Server Pages to delineate code blocks. ASP-style tags look like
this −
<%...%>
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
HTML script tags
HTML script tags look like this −
<script language = "PHP">...</script>

Commenting PHP Code


There are two commenting formats in PHP −
Single-line comments − They are generally used for short explanations or notes relevant to
the local code. Here are the examples of single line comments.
# This is a comment
// This is a comment too
Multi-lines comments − The multiline style of commenting is the same as in C. Here are the
example of multi lines comments.
/* This is a comment with multiline
Line2
Line3 …
*/

PHP - Variable
Variables are "containers" for storing information.
All variables in PHP are denoted with a leading dollar sign ($).
Variables are no need, to declare before assignment.
PHP does a good job of automatically converting types from one to another when necessary.
Rules for naming a variable is −
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores only.
Ex : $x

Datatypes:
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP (such as
database connections).
The first five are simple types, and the next two (arrays and objects) are compound - types .

PHP – Operator:
Operator is a symbol which is used to perform an operation. PHP language supports following
type of operators.
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by de-numerator B / A will give 2


% Modulus Operator and remainder of after an integer division B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

== Checks if the value of two operands are equal or not, if yes then (A == B) is
condition becomes true. not true.

!= Checks if the value of two operands are equal or not, if values (A != B) is


are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.

< Checks if the value of left operand is less than the value of right (A < B) is
operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to the (A >= B) is
value of right operand, if yes then condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.

Logical Operators
There are following logical operators supported by PHP language

Operator Description

&& Called Logical AND operator. If both the operands are non zero then condition
becomes true.

|| Called Logical OR Operator. If any of the two operands are non zero then
condition becomes true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true then Logical NOT operator will make false.

Assignment Operators
There are following assignment operators supported by PHP language −
Operator Description Example

= Simple assignment operator, Assigns values from right C = A + B will assign


side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right operand to C += A is equivalent to


the left operand and assign the result to left operand C=C+A

-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to


operand from the left operand and assign the result to C=C-A
left operand

*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to


operand with the left operand and assign the result to C=C*A
left operand

/= Divide AND assignment operator, It divides left operand C /= A is equivalent to


with the right operand and assign the result to left C=C/A
operand

%= Modulus AND assignment operator, It takes modulus C %= A is equivalent


using two operands and assign the result to left operand to C = C % A
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a
true or false value and then execute one of the two given statements depending upon the
result of the evaluation. The conditional operator has this syntax −

Operator Description Example

?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y

PHP Flow control functions:

Decision Making statements:


You can use conditional statements in your code to make your decisions. PHP supports
following three decision making statements −

1. if...else statement
2. elseif statement
3. switch statement

If...Else Statement
It follows the below Syntax.
Syntax:
if (condition)
true block;
else
false block;

Example
<html>
<body>
<?php
$x = 5;
$y =10;
if($x>$y)
{
echo "Biggest value is: $x ";
}
else
{
echo "Biggest value is: $y ";
}
?>
</body>
</html>
It will produce the following result −
Biggest value is : 10

ElseIf Statement
It follows the below syntax.
Syntax

if (condition-1)
statements-1;
elseif (condition-2)
statements-2;
else
Statements-3;

Example

<?php
$x = 5;
$y =10;
$z =15;
if($x>$y && $x>$z)
{
echo "Biggest value is: $x ";
}
elseif($y>$z)
{
echo "Biggest value is: $y ";
}
else
{
echo "Biggest value is: $z ";
}
?>

It will produce the following result –


Biggest value is : 15

Switch Statement
It is a multiway decision-making statement it follows below syntax.
Syntax

switch (Choice)
{
case value1:
Statements;
break;

case value2:
Statements;
break;
……
……
default:
statemts;
}

Example

<html>
<body>

<?php
$ch=”Add”;
$x=10;
$y=3;
switch ($ch)
{
case "Add":
$z=$x+$y;
echo "Addition is $z";
break;

case "Mul":
$p=$x*$y;
echo "Multiplication is $p";
break;

default:
echo "Enter Correct choice.";
}
?>

</body>
</html>
It will produce the following result −
Addition is 13

PHP - Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
1. for
2. while
3. do...while
4. foreach

for loop :
The for statement is used when you know how many times you want to execute a statement or
a block of statements.

Syntax:

for (initialization; condition; increment)


{
code to be executed;
}

Example
<?php
for ($x = 1; $x <= 10; $x++) {
echo “The number is: $x <br>”;
}
?>

while loop :
If the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression is
found to be false.
Syntax:

while (condition)
{
code to be executed;
}

Example
The example below displays the numbers from 1 to 5:
<?php
$x = 1;

while($x <= 5) {
echo “The number is: $x <br>”;
$x++;
}
?>

do…while loop:

The do…while statement will execute a block of code at least once – it then will repeat the loop
as long as a condition is true.
The do- while loop is an exit control loop.
Syntax
do {
code to be executed;
}
while (condition);

Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

foreach loop:
The foreach statement is used to loop through arrays. For each pass the value of the current
array element is assigned to $value and the array pointer is moved by one and in the next pass
next element will be processed.
Syntax

foreach (array as value)


{
code to be executed;
}
Example

<html>
<body>

<?php
$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

break statement
Once control reached to Break statement , it will exit from the iteration permanently.
Example

<?php
for ($x = 1; $x <= 10; $x++)
{
if ($x == 4)
{
break;
}
echo "The number is: $x <br>";
}
?>

Output :
The number is : 1
The number is : 2
The number is : 3

continue statement:
Once control reached to continue statement it will skip that iteration and continue with next
iteration.

Example
<?php
for ($x = 1; $x <= 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

Output:
The number is : 1
The number is : 2
The number is : 3
The number is : 5
The number is : 6
The number is : 7
The number is : 8
The number is : 9
The number is : 10

PHP - Functions

PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.
In PHP also we have 2 types of functions. Those are
1. pre-defined functions
2. user defined functions
In PHP we can use functions by these two following steps,
Creating a PHP Function
Calling a PHP Function

Creating PHP Function


Its very easy to create your own PHP function.
Syntax :

Function functionname(parameters list)


{
Body;
Return statement;
}

Suppose you want to create a PHP function which will simply write a simple message on your
browser when you will call it.
Following example creates a function called Message() and then calls it just after creating it.

while creating a function its name should start with keyword function and all the PHP code
should be put inside { and } braces as shown in the following example below −

<html>
<body>

<?php
/* Defining a PHP Function */
function Message() {
echo "Good morning have a nice day!";
}

/* Calling a PHP Function */


Message();
?>

</body>
</html>

This will display following result −


Good morning have a nice day!

PHP Functions with Parameters


PHP gives you option to pass your parameters inside a function. These parameters work like
variables inside your function. Following example takes two integer parameters and add them
together and then print them.

<html>
<body>

<?php
function add($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

add(10, 20);
?>

</body>
</html>

This will display following result −


Sum of the two numbers is : 30

PHP Functions returning value


A function can return a value using the return statement. return stops the execution of the
function and sends the value back to the calling code.
Following example takes two integer parameters and add them together and then returns their
sum to the calling program. Note that return keyword is used to return a value from a function.

<html>
<body>

<?php
function add($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$res = add(10, 20);

echo "Returned value from the function : $res";


?>

</body>
</html>

This will display following result −


Returned value from the function : 30

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 two different variable scopes:
local
global
Global and Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:
Example
Variable with global scope:
<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "Variable x inside function is: $x ";
}
myTest();

echo "Variable x outside function is: $x ";


?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
Example
Variable with local scope:
<?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>";
?>
1. What is an array. Explain working with array related functions with example.
Array:
An array is a data structure that stores one or more similar type of values in a single variable.
There are three different kind of arrays and each array value is accessed using array index.
1. Numeric array
2. Associative array
3. Multidimensional array
1.Numeric Array:
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default, array index starts from zero.
Here we have used array() function to create array.
Following is the example showing how to create and access numeric arrays.

Example:
<html>
<body>

<?php
/* First method to create array. */
$x = array( 10, 30, 45);

foreach( $x as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$y[0] = "one";
$y[1] = "two";
$y[2] = "three";

foreach( $y as $value )
{
echo "Value is $value <br />";
}
?>

</body>
</html>
OUTPUT:
Value is 10
Value is 30
Value is 45
Value is one
Value is two
Value is three

2.Associative Arrays:
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index.
Associative array will have their index as string so that you can establish a strong
association between key and values.
To store student details in an associative array given below.
Example:

<html>
<body>

<?php
/* First method to associate create array. */
$x = array("name"=>"Anil", "marks"=>67 , "group"=>"mpcs");
echo “Name :” .$x["name"]. "<br/>";

/* Second method to create array. */


$Res[“Anil”] =>"Pass";
$Res[“Ravi”] =>"Fail";
$Res[“Shiva”] =>"Pass";

echo "Result of Anil is ". $Res[“Anil”] . "<br />";

?>

</body>
</html>
OUTPUT:
Name: Anil
Result of Anil is Pass

3.Multidimensional Arrays:
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array
are accessed using multiple indexes.
Example:
In this example we create a two-dimensional array to store marks of students in three subjects

<html>
<body>

<?php
$marks = array(
"Anil" => array (
"physics" => 35,
"maths" => 30,
"Computers" => 39
),

"Ravi" => array (


"physics" => 30,
"maths" => 32,
"Computers" => 29
)

);
echo "Marks for Anil in physics : " ;
echo $marks[“Anil”][“physics”] . "<br />";

echo "Marks for Ravi in maths : ";


echo $marks[“Ravi”][“maths”] . "<br />";

?>

</body>
</html>

This will produce the following result −


Marks for Anil in physics: 35
Marks for Ravi in maths: 32

2.Explain working with class and objects in PHP with example.

Defining PHP Classes


The general form for defining a new class in PHP is as follows −
<?php
class Classname
{
var $var1;
var $var2;

function myfunc ($arg1, $arg2)


{
Body;
}
}
?>

Example
Here is an example which defines a class of Books type −
<?php
class Books
{
var $price;

function setPrice($par)
{
$this->price = $par;
}

function getPrice()
{
echo $this->price ."<br/>";
}

}
?>
The variable $this is a special variable and it refers to the same object i.e.; itself.

Creating Objects in PHP


Once you defined your class, then you can create as many objects using new operator.
$maths = new Books;
$Computers = new Books;

Calling Member Functions


After creating your objects, you will be able to call member functions related to that object.
Following example shows how to set title and prices for the three books by calling member
functions.
$Computers->setPrice( 1500 );
$maths->setPrice( 700 );
Now you call another member functions to get the values set by in above example
$Computers->getPrice();
$maths->getPrice();
This will produce the following result −
1500
700

3.Explain manipulating strings with PHP.


(or)
Explain working with string object in PHP with example.

Strings:
Strings are sequences of characters; PHP supports string operations.
Following are valid examples of string
$string1 = "Hello World";
$string2 = "welcome to PHP";

<?php
$name = "Anil";
$msg = "Welcome $name";

print($msg);
?>
This will produce the following result −
Welcome Anil
String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator −

<?php
$string1="Hello World";
$string2="1234";

echo $string1. " " . $string2;


?>
This will produce the following result −
Hello World 1234
strlen() function:
The strlen() function is used to find the length of a string.

<?php
echo strlen("Hello world!");
?>
This will produce the following result −
12

strpos() function:
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no
match is found, it will return FALSE.

<?php
echo strpos("Hello world!”, “world");
?>
This will produce the following result −
6
As you see the position of the string "world" in our string is position 6.

Strtolower() function :
This function is used to display given string into lower case.
<?php
Echo strtolower(“WORLD”);
?>
This will produce the following result –
world

Strtoupper() function :
This function is used to display given string into uppercase case.
<?php
Echo strtoupper(“world”);
?>
This will produce the following result –
WORLD

Strcmp() function:
The strcmp() function compares two strings.
This function returns:

 0 - if the two strings are equal


 <0 - if string1 is less than string2
 >0 - if string1 is greater than string2

<?php
echo strcmp("Hello world!","Hello world!");
?>
This will produce the following result –
0
Str_repeat() function :

The str_repeat() function repeats a string a specified number of times.

<?php

echo str_repeat(“hello”,3);
?>
This will produce the following result –
hello hello hello

4.Explain usages of date and time functions in PHP.

PHP time() function :


PHP's time() function gives you all the information that you need about the current date and time.
It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight GMT
on January 1, 1970.

Example:
<?php
print time();
?>
This will produce the following result −
1480930103

PHP getdate() function :


The function getdate() optionally accepts a time stamp and returns an associative array
containing information about the date.
Following table lists the elements contained in the array returned by getdate().
Sr.No Key & Description Example

1 seconds 20
Seconds past the minutes (0-59)

2 minutes 29
Minutes past the hour (0 - 59)

3 hours 22
Hours of the day (0 - 23)

4 mday 11
Day of the month (1 - 31)

5 wday 4
Day of the week (0 - 6)

6 mon 7
Month of the year (1 - 12)

7 year 1997
Year (4 digits)

8 yday 19
Day of year ( 0 - 365 )

9 weekday Thursday
Day of the week

10 month January
Month of the year

Example

<?php
$d = getdate();

foreach ( $d as $key => $val )


{
print "$key = $val<br />";
}
?>
This will produce following result −
seconds = 10
minutes = 29
hours = 9
mday = 5
wday = 1
mon = 12
year = 2016
yday = 339
weekday = Monday
month = December

PHP date() function:


The date() function returns a formatted string representing a date.
date(format,timestamp);
The date() optionally accepts a time stamp if omitted then current date and time will be used.
Any other data you include in the format string passed to date() will be included in the return
value.
Following table lists the codes that a format string can contain −
Sr.No Format & Description Example

1 a pm
'am' or 'pm' lowercase

2 A PM
'AM' or 'PM' uppercase

3 d 20
Day of month, a number with leading zeroes
4 h 12
Hour (12-hour format - leading zeroes)

5 i 23
Minutes ( 0 - 59 )

6 m 1
Month of year (number - leading zeroes)

7 s 20
Seconds of hour

8 y 23
Year (two digits)

9 Y 2023
Year (four digits)
Example
Try out following example

<?php
print date("m/d/y h:i:s<br>", time());
echo "<br>";

?>
This will produce following result −
12/05/16 9:29:47
1.Explain how to Combining HTML and PHP code on a single Page with suitable
example.
PHP Form Handling

The example below displays a simple HTML form with two input fields and a submit button:

Example:

<html>
<body>

<form Action ="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php".

The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

Welcome John
Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:

Example:

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

</body>
</html>

and "Hello.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.

2.Explain how to Creating Forms, Accessing Form Input with User defined Arrays.
PHP - GET & POST Methods
There are two ways the browser client can send information to the web server.

 The GET Method


 The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by
the ampersand.
name1=value1&name2=value2&name3=value3
After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method is restricted to send upto 1024 characters only.
 Never use GET method if you have password or other sensitive information to be
sent to the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.
 The PHP provides $_GET associative array to access all the sent information using
GET method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "GET">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on
HTTP protocol. By using Secure HTTP you can make sure that your information is
secure.
 The PHP provides $_POST associative array to access all the sent information using
POST method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −

The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We
will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] )
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −

3.What is a Cookie? Explain working with cookies in PHP with example.

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.

 The following 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 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
?>
<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>
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", "john", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
4.What is session function. Explain working with session in PHP with example.
PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the user’s computer.

When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session.

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

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:

Example
<?php
// Start the session
session_start();
?>
<html>
<body>

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

</body>
</html>
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").

Esxample:
<?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"] . ".";
?>

</body>
</html>

Another way to show all the session variable values for a user session is to run the following
code:

Example :
<?php
session_start();
?>

<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>
Modify a PHP Session Variable

To change a session variable, just overwrite it:

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

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>
Destroy a PHP Session

To remove all global session variables and destroy the session,


use session_unset() and session_destroy():

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

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

// destroy the session


session_destroy();
?>

</body>
</html>
1.Explain working with files in PHP.
file inclusion:
PHP allows you to include file so that a page content can be reused many times. It is very
helpful to include files when you want to apply the same HTML or PHP code to multiple pages
of a website.
PHP include is used to include a file on the basis of given path. You may use a relative or
absolute path of the file.
Syntax: include ('filename');
Example:
File: menu.html
<a href="home.html">Home</a>
<a href="php.html">PHP</a>
<a href="java.html">Java</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
Home
PHP
Java
This is Main Page

PHP has several functions for creating, reading, uploading, and editing files.

Create a new file OR Open a file:

The fopen() function is used to open files and also used to create a file.

If we use fopen() on a file, and that does not exist, at that time it will create it.

Syntax: fopen(“file name ” , “mode”);

The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened.

The file may be opened in one of the following modes:


Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new file if
it doesn't exist. File pointer starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist

Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("Hello.txt"));
fclose($myfile);
?>

Write to File

The fwrite() function is used to write to a file.

Syntax : fwrite(file , string);

The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.

The example below writes a couple of names into a new file called "newfile.txt":

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Hello \n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we open the "newfile.txt" file it would look like this:

Hello
Read File
a) readfile() Function

The readfile() function reads a file and writes it to the output buffer.

Assume we have a text file called "Hello.txt", stored on the server, that looks like this:

Hi, Good Morning.


Welcome to our college.

The PHP code to read the file and write it to the output buffer is as follows.

Note : the readfile() function returns the number of bytes read on success.

Example
<?php
echo readfile("Hello.txt");
?>

b) fread():

The fread() function reads from an open file.

The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.

The following PHP code reads the "Hello.txt" file to the end:

fread($myfile,filesize("Hello.txt"));

c) fgets() -Read Single Line

The fgets() function is used to read a single line from a file.

The example below outputs the first line of the "Hello.txt" file:

Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

Note: After a call to the fgetc() function, the file pointer moves to the next line.
d) fgetc()-Read Single Character

The fgetc() function is used to read a single character from a file.

The example below reads the "Hello.txt" file character by character, until end-of-file is reached:

Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

Note: After a call to the fgetc() function, the file pointer moves to the next character.

Check End-Of-File

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

The example below reads the "Hello.txt" file line by line, until end-of-file is reached:

Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Close File

The fclose() function is used to close an open file.

The fclose() requires the name of the file (or a variable that holds the filename) we want to
close:

<?php
$myfile = fopen("Hello.txt", "r");
// some code to be executed....
fclose($myfile);
?>
Append Text

You can append data to a file by using the "a" mode. The "a" mode appends text to the end of
the file.

In the example below we open our existing file "newfile.txt", and append some text to it:

Example
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "good morning \n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the "newfile.txt" file, we will see that Donald Duck and Goofy Goof is appended
to the end of the file:

Hello
Good morning
2.Explain working with directories in PHP.
Working with directories :

The directory functions allow you to retrieve information about directories and their contents.

getcwd():
This function is used to get current working directory.
<?php

echo getcwd() . "<br>";


?>
Chdir():
The chdir() function changes the current directory.
<?php

chdir("images");

?>
Opendir():
The opendir() function used to open a directory to handle.
Readdir();
The readdir() function is used to read given directory .

Closedir():

The closedir() function closes a directory handle.

Example:
<?php
$dir = getcwd();
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>
3. Explain popen() , Exec() , system() , passthru() commands.

Popen() :
The popen() function in PHP is used to open a pipe to a process using
the command parameter.
Syntax :Popen( command , mode);

 command: command specifies which command is to be executed.


 mode: mode defines whether the pipe is read-only (r) or write-only (w).

<?php
$handle = popen("/bin/ls", "r");
$read = fread($handle, 2096);
print_r("$handle: ".gettype($handle)."\n$read \n");
pclose($handle);
?>
exec() Function
The exec() function is an inbuilt function in PHP which is used to execute an external program
and returns the last line of the output. It also returns NULL if no command run properly.
Syntax:
exec( $command, $return_var )

$command: This parameter is used to hold the command which will be executed.
$return_var: The $return_var parameter is present along with the output argument, then it
returns the status of the executed command will be written to this variable.
Example:

<?php
echo exec('pwd');
?>

System()

system — Execute an external program and display the output

system($command, $result_code )

system() is the function in that it executes the given command and outputs the result.

Parameters

command

The command that will be executed.

result_code

If the result_code argument is present, then the return status of the executed command
will be written to this variable.

Return Values

Returns the last line of the command output on success, and false on failure.

Examples

<?php

$last_line = system('ls', $retval);


echo 'Last line of the output: ' . $last_line.';

?>

Passthru()

passthru — Execute an external program and display raw output

Syntax :
passthru($command, $result_code)

The passthru() function is similar to the exec() function in that it executes a command.

Parameters

command

The command that will be executed.

result_code

If the result_code argument is present, then the return status of the executed command
will be written to this variable.

Return Values

Returns the last line of the command output on success, and false on failure.

Examples

<?php

$last_line = passthru('ls', $retval);


echo 'Last line of the output: ' . $last_line.';

?>
4. Explain working with images in PHP with example.
Working with images in PHP:
The imagecreate() is a function in PHP used to create a new image. This function returns the
blank image of given size.
In general imagecreatetruecolor() function is used instead of imagecreate() function
because imagecreatetruecolor() function creates high quality images.
Syntax: imagecreate( $width, $height )
$width: It is mandatory parameter which is used to specify the image width.
$height: It is mandatory parameter which is used to specify the image height.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
Example:
<?php

// Create the size of image or blank image


$image = imagecreate(500, 300);
// Set the background color of image
$background_color = imagecolorallocate($image, 0, 153, 0);

// Set the text color of image


$text_color = imagecolorallocate($image, 255, 255, 255);

// Function to create image which contains string.


imagestring($image, 5, 180, 100, "Hello World", $text_color);
?>
1.Explain how MySQL varies with MySQLifunctions .

MySQL vs MySQLi

MySQL and MySQLi are PHP database extensions implemented by using the PHP extension framework.
PHP database extensions are used to write PHP code for accessing the database.

MySQL extension is deprecated and will not be available in future PHP versions. It is recommended to use
the MySQLi extension with PHP 5.5 and above.

MYSQLi MYSQL

MySQLi extension added in PHP 5.5 MySQL extension added in PHP version 2.0

Extension directory: ext/mysqli. Extension directory: ext/mysql

The MYSQL does not support prepared


The MySQLi supports prepared statements.
statements.

MySQLi supports transactions through API. Transactions are handled by SQL queries only.

MySQLi provides both object-oriented and procedural


MySQL provides procedural interface.
interfaces.

MySQLi extension is with enhanced security and MySQL extension lags in security and other
improved debugging. special features, comparatively.

MySQL extension does not support stored


MySQLi supports store procedure.
procedure.

mysql_connect($host_name,$user_name,$pa
mysqli_connect($host_name,$user_name,$passwd,$db
sswd) followed by
name)
mysql_select_db($dbname)

2.Explain How to connect MySQL with PHP and workingwith MySQL data.
PHP Connect to MySQL

PHP 5 and later can work with a MySQL database using:

 MySQLi extension (the "i" stands for improved)

 Earlier versions of PHP used the MySQL extension.

Open a Connection to MySQL

Before we can access data in the MySQL database, we need to be able to connect to the server:
<?php
$servername = "localhost";
$username = "root";
$password = "root";

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

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

The connection will be closed automatically when the script ends. To close the connection before, use the
following:

mysqli_close($conn);

3.Explain how to create an online address book in PHP.


PHP Create a MySQL Database:

A database consists of one or more tables.

Here we use mysqli_query() function .

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "college":

Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";

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

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

mysqli_close($conn);
?>

PHP Create MySQL Tables:

A database table has its own unique name and consists of columns and rows.

The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "Student", with 2 columns: "id", "Name" :

CREATE TABLE Student (id INT(6),Name VARCHAR(30))

The following examples shows how to create the table in PHP:

Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "college";

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

// sql to create table


$que = " CREATE TABLE Student (id INT(6),Name VARCHAR(30))”;

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

mysqli_close($conn);
?>

PHP Insert MySQL records :

After a database and a table have been created, we can start adding data in them.

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

The following examples add a new record to the "Student" table:


Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "college";

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

$que = "INSERT INTO StudentVALUES (1 ,'John')”;

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

mysqli_close($conn);
?>

PHP Delete MySQL records:

The DELETE statement is used to delete records from a table:

Syntax : DELETE FROM table_name WHERE Condition ;

The following examples delete the record with id=1 in the "Student" table:

Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "College";

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

// sql to delete a record


$sql = "DELETE FROM Student WHERE id=1";

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

mysqli_close($conn);
?>

PHP viewing MySQL records Data

The SELECT statement is used to select data from one or more tables:

Syntax :SELECT column_name(s) FROM table_name ;

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name ;

Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "College";

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

$sql = "SELECT id, Name FROM Student";


$result = mysqli_query($conn, $sql);

mysqli_close($conn);
?>

You might also like