0% found this document useful (0 votes)
20 views64 pages

PHP Sem 1 - 2

The document provides a comprehensive overview of PHP, including its installation, features, and syntax, along with various programming examples. It covers the history of PHP, its advantages for web development, and instructions for setting up different versions of PHP in XAMPP. Additionally, it explains PHP variables, constants, and the use of Composer for dependency management.

Uploaded by

ahajang141
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)
20 views64 pages

PHP Sem 1 - 2

The document provides a comprehensive overview of PHP, including its installation, features, and syntax, along with various programming examples. It covers the history of PHP, its advantages for web development, and instructions for setting up different versions of PHP in XAMPP. Additionally, it explains PHP variables, constants, and the use of Composer for dependency management.

Uploaded by

ahajang141
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/ 64

Semester I PHP

1) Introduction Of PHP and installation Of PHP

2) Operators in PHP

3) Program for Even odd no

4) PHP switch statement with character

5) For each Example

6) Program on Sum of Digits

7) Program to Check whether number is Prime or not

8) Program for Table of Number

9) Program For Factorial of number

10) program to check whether given number is Armstrong Number

11 ) Program to check given number is Palindrome Number or not

12) Program to print Fibonacci Series


Assignment No- 1

Assignment name- . Introduction Of PHP and installation Of PHP

Roll No-

What is PHP

PHP is an open-source, interpreted, and object-oriented scripting language that can be


executed at the server-side. PHP is well suited for web development. Therefore, it is used to
develop web applications (an application that executes on the server and generates the
dynamic page.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0
is the latest version of PHP, which was released on 28 November. Some important points
need to be noticed about PHP are as followed:

PHP stands for Hypertext Preprocessor.

PHP is an interpreted language, i.e., there is no need for compilation.

PHP is faster than other scripting languages, for example, ASP and JSP.

PHP is a server-side scripting language, which is used to manage the dynamic content of the
website.

PHP can be embedded into HTML.

PHP is an object-oriented language.

PHP is an open-source scripting language.

PHP is simple and easy to learn language.

Why use PHP

PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.

It handles dynamic content, database as well as session tracking for the website.

You can create sessions in PHP.

It can access cookies variable and also set cookies.

It helps to encrypt the data and apply validation.


PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.

Using PHP language, you can control the user to access some pages of your website.

As PHP is easy to install and set up, this is the main reason why PHP is the best language to
learn.

PHP can handle the forms, such as - collect the data from users using forms, save it into the
database, and return useful information to the user. For example - Registration form.

PHP Features
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:

Performance:

PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.

Open Source:

PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding with it.

Embedded:

PHP code can be easily embedded within HTML tags and script.

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.

Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken automatically
at the time of execution based on the type of data it contains on its value.

Web servers Support:

PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft
IIS, etc.

Security:

PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.

Control:

Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.

A Helpful PHP Community:

It has a large community of developers who regularly updates documentation, tutorials,


online help, and FAQs. Learning PHP from the communities is one of the significant benefits.

Web Development

PHP is widely used in web development nowadays. PHP can develop dynamic websites
easily. But you must have the basic the knowledge of following technologies for web
development as well.

o HTML

o CSS

o JavaScript

o Ajax

o XML and JSON

o jQuery

Install PHP

To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that
are given below:
WAMP for Windows

LAMP for Linux

MAMP for Mac

SAMP for Solaris

FAMP for FreeBSD

XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.

Upgrading PHP in Xampp


It is not very complex but some time very essential when we need latest version of php for

new project without changing the current local server settings. so i am trying to cover the
changing the version by keeping the old version manually.

 PHP 7 is almost twice as fast as lower version of PHP

 Low memory usage

 Facilitates Error Handling

 64-Bit Windows Systems Support

 New Spaceship and Null Coalescing Operators

 Enables Accurate Type Declarations

 Add Anonymous Classes

 Facilitates Imports From the Same Namespace

 Introducing null coalescing & Spaceship operator and more

Now i am going to show how you will overcome this situation. my present php version is php-
5.6.36
Step 1: First download the latest php version from http://windows.php.net/download#php-

7.0 Download the VC14 x86 Thread Safe or VC14 x64 Thread Safe deciding upon your

Windows version( x86 for 32-bit and x64 for 64-bit ). Next extract the zip file in a folder
named php.

Step 2: Go to your XAMPP installation directory and rename your old php directory with old

version prefix like php to php_5_6_36. Now copy & paste the extracted new php folder to
here.

Step3: Next, open httpd-xampp.conf from XAMPP configuration.

On PHP-Module setup section, comment these two lines and add the two lines below

# PHP-Module setup

#LoadFile “D:/xampp/php/php5ts.dll”

#LoadModule php5_module “D:/xampp/php/php5apache2_4.dll”


LoadFile “D:/xampp/php/php7ts.dll”

LoadModule php7_module “D:/xampp/php/php7apache2_4.dll”

That’s it. Now restart your XAMPP server and keep coding.

Run multiple version of PHP in XAMPP Windows (Without installing multiple XAMPP)

Why switch between PHP versions when you can use multiple PHP version at a same time
with a single xampp installation? With a single xampp installation, you have 2 options:

1. Run an older PHP version for only the directory of your old project: This will serve the
purpose most of the time, you may have one or two old projects that you intend to run
with older PHP version. Just configure xampp to run older PHP version only for those
project directories.
2. Run an older PHP version on a separate port of xampp: Sometimes you may be
upgrading and old project to latest PHP version when you need to run the same project
on new and older php version back and forth. Then you can set an older PHP version on a
different port (say 8056) so when you go to http://localhost/any_project/ xampp runs
php 7 and when you go to http://localhost:8056/any_project/ xampp runs php 5.6.
Lets set it up.

Step 1: Download PHP


So you have php 7 running under xampp, you want to add an older php version to it, say
php 5.6. Download the php zip archive from here and extract the files
under c:\xampp\php56.
Step 2: Configure php.ini
Open c:\xampp\php56\php.ini file in notepad. If the file does not exist copy php.ini-
developmentto php.ini and open it in notepad. Then uncomment the following line:
extension_dir = "ext"
Step 3: Configure apache
Open xampp control panel, click config button for apache, and click Apache (httpd-
xampp.conf). A text file will open up put the following settings at the bottom of the file:
ScriptAlias /php56 "C:/xampp/php56"
<Directory "C:/xampp/php56">
AllowOverride None
Options None
Require all denied
<Files "php-cgi.exe">
Require all granted
</Files>
</Directory>
Note: You can add more versions of PHP to your xampp installation following step 1 to 3 if
you want.
Step 4 (option 1): [Add Directories to run specific PHP version]
Now you can set directories that will run in php 5.6. Just add the following at the bottom of
the config file to set directories.

<Directory "C:\xampp\htdocs\my_old_project1">
UnsetEnv PHPRC
<FilesMatch "\.php$">
SetHandler application/x-httpd-php56
Action application/x-httpd-php56 "/php56/php-cgi.exe"
</FilesMatch>
</Directory>

<Directory "C:\xampp\htdocs\my_old_project2">
UnsetEnv PHPRC
<FilesMatch "\.php$">
SetHandler application/x-httpd-php56
Action application/x-httpd-php56 "/php56/php-cgi.exe"
</FilesMatch>
</Directory>
Step 4 (option 2): [Run older PHP version on a separate port]
Now to to set PHP v5.6 to port 8056 add the following code to the bottom of the config file.

Listen 8056
<VirtualHost *:8056>
UnsetEnv PHPRC
<FilesMatch "\.php$">
php_flag engine off
SetHandler application/x-httpd-php56
Action application/x-httpd-php56 "/php56/php-cgi.exe"
</FilesMatch>
</VirtualHost>
Finish: Save and Restart Apache
Save and close the config file, Restart apache from xampp control panel. If you went for
option 2 you can see the additional port(8056) listed in your xampp control panel.

Running PHP in apache

I suggest you read the official PHP documentation about installing it on Windows systems.
Download the latest PHP binaries from the official PHP for Windows download page, choose
the thread-safe version that matches your Apache installation's bit-version (x86 for 32-Bit,
x64 for 64-Bit).
The non thread-safe version is only when running as a CGI binary - more info here.
The version I used is this : PHP 5.6.2 VC11 x64 Thread Safe. The latest version when this
answer was last updated: PHP 7.3.3 VC15 x64 Thread Safe (look at the edit date at the
bottom of the post).
Create an empty PHP folder at the root of your hard drive, and extract the previously
downloaded archive there, you should have a path like C:\PHP\ext, otherwise you did
something wrong.
In C:\PHP, rename the php.ini-production or php.ini-development (depending on what you
want) to php.ini.
Open that php.ini file, search for extension_dir = "ext" and uncomment that line (remove
the first ;). This sets the default extension dir to ext (which resolves to C:\PHP\ext and
avoids having to prepend ext/ to all extension's paths manually like in previous versions of
this post.
Now configure Apache to use that PHP, by editing C:\Apache24\conf\httpd.conf - after all
the LoadModule lines, add the following :
(The follow is for PHP 7 only)
LoadModule php7_module "c:\php\php7apache2_4.dll"

<IfModule php7_module>

AddHandler application/x-httpd-php .php


AddType application/x-httpd-php .php .html
PHPIniDir "c:\php"
</IfModule>
(The following is for PHP 5 only)
LoadModule php5_module C:/PHP/php5apache2_4.dll

<IfModule php5_module>
DirectoryIndex index.html index.php
AddHandler application/x-httpd-php .php
PHPIniDir "C:/PHP"
</IfModule>
Now try to start Apache manually by opening a command prompt in C:\Apache24\bin and
running httpd.exe - if you see no errors, it means your configuration file is valid and PHP
is most likely working.
You can test your PHP installation by creating a file like info.php with <?php phpinfo(); inside
and going to http://localhost/info.php - you should see quite a bit of info about your system
and your PHP installation and all its modules. If you get something else like an "Internal
server error" that means something's wrong.
You can now kill your current Apache process (Ctrl+C in the console) and start the service -
the following part doesn't interact with Apache and can be done with the server already
started.

Composer - optional
Composer is a tool for dependency management in PHP, like a package manager. It allows to
easily install PHP packages and even entire frameworks.

Composer requires the PHP OpenSSL extension to be enabled, so let's enable it


in C:\PHP\php.ini.
Use your text editor's search function to search for php_openssl.dll, there should already be
a commented line for it, just uncomment that line.
Now download Composer's Windows installer from their download page - or just use
this direct link.
Follow the instructions, when prompted for the path to PHP, browse to C:\PHP and
select php.exe.
That's it, Composer is now installed system-wide and can be used from anywhere - you can
try it out, just open a new command prompt (you can't use one that's already open since it
needs to read the new PATH variable set by Composer's installer) and type composer.
You should get a nice ASCII-art logo and something like this :

WhatisthePHP/JavaBridge?

The PHP/Java Bridge is an implementation of a streaming, XML-based network protocol,


which can be used to connect a native script engine, for example PHP, Scheme or Python,
with a Java virtual machine. It is up to 50 times faster than local RPC via SOAP, requires
less resources on the web-server side. It is faster and more reliable than direct
communication via the Java Native Interface, and it requires no additional components to
invoke Java procedures from PHP or PHP procedures from Java.
J2EE back end clustering and Apache load balancing are supported as well as running PHP
scripts within JSP, JSF or other frameworks.

The bridge uses "continuation passing" to invoke procedures/methods from each


environment. Although this may be unusual, it is a fast and reliable mechanism to
connect different script environments.

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.

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
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Out put

My first PHP page

Hello World!

PHP Variables
Example

<?php
$txt = "Hello world!";

$x = 5;

$y = 10.5;

?>

Rules for PHP variables:

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)

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during
the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant
name).

Note: Unlike variables, constants are automatically global across the entire script.

Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

name: Specifies the name of the constant

value: Specifies the value of the constant

case-insensitive: Specifies whether the constant name should be case-insensitive. Default


is false
Example

Create a constant with a case-insensitive name:

<?php

define("GREETING", "Welcome to PHP!", true);

echo greeting;

?>

Out put

Welcome to PHP!
Assignment No- 2

Assignment name- Operators in PHP

Roll No-

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4
and 5 are called operands and + is called operator. PHP language supports following type of
operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by PHP language −


Assume variable A holds 10 and variable B holds 20 then −
Show Examples

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 −
Show Examples

Operator Description Example

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

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

> Checks if the value of left operand is greater than the value of right (A > B) is not
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 true.
operand, if yes then condition becomes true.

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

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

Logical Operators

There are following logical operators supported by PHP language


Assume variable A holds 10 and variable B holds 20 then −
Show Examples

Operator Description Example


and Called Logical AND operator. If both the operands are true then (A and B) is
condition becomes true. true.

or Called Logical OR Operator. If any of the two operands are non zero (A or B) is
then condition becomes true. true.

&& Called Logical AND operator. If both the operands are non zero then (A && B) is
condition becomes true. true.

|| Called Logical OR Operator. If any of the two operands are non zero (A || B) is
then condition becomes true. true.

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

Assignment Operators

There are following assignment operators supported by PHP language −


Show Examples

Operator Description Example

= Simple assignment operator, Assigns values from right side C = A + B will assign
operands to left side operand value of A + B into C

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


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

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


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

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


operand with the left operand and assign the result to left C=C*A
operand
/= Divide AND assignment operator, It divides left operand with C /= A is equivalent to C
the right operand and assign the result to left operand =C/A

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


two operands and assign the result to left operand 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 −
Show Examples

Operator Description Example

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

Operators Categories

All the operators we have discussed above can be categorised into following categories −
 Unary prefix operators, which precede a single operand.
 Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
 The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
 Assignment operators, which assign a value to a variable.

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left


Assignment No- 3

Assignment name- . Program for Even odd no

Roll No-

<?php

$num=12;

if($num%2==0){

echo "$num is even number";

}else{

echo "$num is odd number";

?>

Output:

12 is even number
Assignment No- 4

Assignment name- PHP switch statement with character

Roll No-

<?php

$ch = 'U';

switch ($ch)

case 'a':

echo "Given character is vowel";

break;

case 'e':

echo "Given character is vowel";

break;

case 'i':

echo "Given character is vowel";

break;

case 'o':

echo "Given character is vowel";

break;

case 'u':

echo "Given character is vowel";

break;

case 'A':
echo "Given character is vowel";

break;

case 'E':

echo "Given character is vowel";

break;

case 'I':

echo "Given character is vowel";

break;

case 'O':

echo "Given character is vowel";

break;

case 'U':

echo "Given character is vowel";

break;

default:

echo "Given character is consonant";

break;

?>

Output:

Given character is vowel


Assignment No- 5

Assignment name- For each Example

Roll No-

<?php

//declare array

$season = array ("Summer", "Winter", "Autumn", "Rainy");

//access array elements using foreach loop

foreach ($season as $element) {

echo "$element";

echo "</br>";

?>

Out put

Summer

Winter

Autumn

Rainy
Assignment No- 6

Assignment name- Program on Sum of Digits

Roll No-

<?php

$num = 14597;

$sum=0; $rem=0;

for ($i =0; $i<=strlen($num);$i++)

$rem=$num%10;

$sum = $sum + $rem;

$num=$num/10;

echo "Sum of digits 14597 is $sum";

?>

Output:
Assignment No- 7

Assignment name- Program to Check whether number is Prime or not

Roll No-

<?php

$count = 0;

$num = 2;

while ($count < 15 )

$div_count=0;

for ( $i=1; $i<=$num; $i++)

if (($num%$i)==0)

$div_count++;

if ($div_count<3)

echo $num." , ";

$count=$count+1;

$num=$num+1;

}
?>

Output:
Assignment No- 8

Assignment name - Program for Table of Number

Roll No-

<?php

define('a', 7);

for($i=1; $i<=10; $i++)

echo $i*a;

echo '<br>';

?>

Output:
Assignment No- 9

Assignment name- Program For Factorial of number

Roll No-

<?php

$num = 4;

$factorial = 1;

for ($x=$num; $x>=1; $x--)

$factorial = $factorial * $x;

echo "Factorial of $num is $factorial";

?>

Output:
Assignment No- 10

Assignment name- Program to check whether given number is Armstrong Number

Roll No-

<?php

$num=407;

$total=0;

$x=$num;

while($x!=0)
{
$rem=$x%10;
$total=$total+$rem*$rem*$rem;
$x=$x/10;
}
if($num==$total)
{
echo "Yes it is an Armstrong number";
}
else

echo "No it is not an armstrong number";

?>

Output:
Assignment No- 11

Assignment name- Program to check given number is Palindrome Number or not

Roll No-

<?php

function palindrome($n){

$number = $n;

$sum = 0;

while(floor($number)) {

$rem = $number % 10;

$sum = $sum * 10 + $rem;

$number = $number/10;
}
return $sum;
}
$input = 1235321;
$num = palindrome($input);
if($input==$num){

echo "$input is a Palindrome number";

} else {

echo "$input is not a Palindrome";

?>

Output:
Assignment No- 12

Assignment name- Program to print Fibonacci Series

Roll No-

<?php

$num = 0;

$n1 = 0;

$n2 = 1;

echo "<h3>Fibonacci series for first 12 numbers: </h3>";

echo "\n";

echo $n1.' '.$n2.' ';

while ($num < 10 )

$n3 = $n2 + $n1;

echo $n3.' ';

$n1 = $n2;

$n2 = $n3;

$num = $num + 1;

?>

Output:
Semester II PHP
1) Arrays in PHP

2) Function in PHP

3) Exception Handling in PHP

4) GET and POST in PHP

5) htmlspecialchars() function

6) Simple form example

7) PHP Form Validation Example

8) Multivalued form fields Example

9) PHP File Upload Example


Assignment No- 1

Assignment name- Arrays in PHP

Roll No-

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.

Example 1

<?php

$season=array("summer","winter","spring","autumn");

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

?>

Output:

Season are: summer, winter, spring and autumn

Example 2

<?php

$season[0]="summer";

$season[1]="winter";

$season[2]="spring";

$season[3]="autumn";

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

?>

Output:

Season are: summer, winter, spring and autumn


PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

Example 1

<?php

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";

echo "John salary: ".$salary["John"]."<br/>";

echo "Kartik salary: ".$salary["Kartik"]."<br/>";

?>

Output:

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000

Example 2

<?php

$salary["Sonoo"]="350000";

$salary["John"]="450000";

$salary["Kartik"]="200000";

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";

echo "John salary: ".$salary["John"]."<br/>";

echo "Kartik salary: ".$salary["Kartik"]."<br/>";

?>

Output:

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000


PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix which
is represented by row * column.

Example

<?php

$emp = array

array(1,"sonoo",400000),

array(2,"john",500000),

array(3,"rahul",300000)

);

for ($row = 0; $row < 3; $row++) {

for ($col = 0; $col < 3; $col++) {

echo $emp[$row][$col]." ";

echo "<br/>";

?>

Output:

1 sonoo 400000

2 john 500000

3 rahul 300000

PHP sort() function

PHP sort() function sorts all the elements in an array.

Example

<?php
$season=array("summer","winter","spring","autumn");

$reverseseason=array_reverse($season);

foreach( $reverseseason as $s )

echo "$s<br />";

?>

Output:

autumn

spring

winter

summer

Program to Display data from numeric Array in HTML table

<?php

// Numeric array with data that will be displayed in HTML table

$aray = array('https://coursesweb.net', 'marplo.net', 'Courses', 'Web Programming', 'PHP-


MySQL');

$nr_elm = count($aray); // gets number of elements in $aray

// Create the beginning of HTML table, and of the first row

$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';

$nr_col = 2; // Sets the number of columns

// If the array has elements

if ($nr_elm > 0) {

// Traverse the array with FOR

for($i=0; $i<$nr_elm; $i++) {


$html_table .= '<td>' .$aray[$i]. '</td>'; // adds the value in column in table

// If the number of columns is completed for a row (rest of division of ($i + 1) to $nr_col is
0)

// Closes the current row, and begins another row

$col_to_add = ($i+1) % $nr_col;

if($col_to_add == 0) { $html_table .= '</tr><tr>'; }

// Adds empty column if the current row is not completed

if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col - $col_to_add).


'">&nbsp;</td>';

$html_table .= '</tr></table>'; // ends the last row, and the table

// Delete posible empty row (<tr></tr>) which cand be created after last column

$html_table = str_replace('<tr></tr>', '', $html_table);

echo $html_table; // display the HTML table

?>

Output

https://coursesweb.net marplo.net
Courses Web
Programming
PHP-MySQL
Assignment No- 2

Assignment name- Function in PHP

Roll No-

PHP simple Function code

<?php

function sayHello(){

echo "Hello PHP Function";

sayHello();//calling function

?>

Output:

Hello PHP Function

Function with Arguments

<?php

function sayHello($name,$age){

echo "Hello $name, you are $age years old<br/>";

sayHello("Sonoo",27);

sayHello("Vimal",29);

sayHello("John",23);

?>

Output:

Hello Sonoo, you are 27 years old

Hello Vimal, you are 29 years old


Hello John, you are 23 years old

Function Call By Value

<?php

function adder($str2)

$str2 .= 'Call By Value';

$str = 'Hello ';

adder($str);

echo $str;

?>

Output:

Hello

Function Call By Reference

<?php

function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';

adder($str);

echo $str;

?>

Output:

This is Call By Reference


Function With Default Arguments

<?php

function sayHello($name="Ram"){

echo "Hello $name<br/>";

sayHello("Sonoo");

sayHello();//passing no value

sayHello("Vimal");

?>

Output:

Hello Sonoo

Hello Ram

Hello Vimal

Static variable in PHP function

<!DOCTYPE html>

<html>

<body>

<?php

function add1() {

static $number = 0;

$number++;

return $number;

echo add1();

echo "<br>";
echo add1();

echo "<br>";

echo add1();

?>

</body>

</html>

Out put

Passing an Array To Function

<?php

// create the 'scores' array

$scores = array(10,20,30,40,50,90);

// create the 'average' function

function average($array){

// set 'total' to 0

$total = 0;

foreach($array as $value){

// adds the value of each item in the array, one by one

$total += $value;

// calculate the average and return the result

return $total/count($array);

}
// call the 'average' function and use the 'scores' array as argument

echo "Average = ", average($scores);

?>

Output

Avarage =40

Nested Function in Php

<?php

function salestax($price,$tax) {

function convert_pound($dollars, $conversion=1.6) {

return $dollars * $conversion;

$total = $price + ($price * $tax);

echo "Total cost in dollars: $total. Cost in British pounds: ".convert_pound($total);

salestax(15.00,.075);

echo convert_pound(15);

?>

Out put

Total cost in dollars: 16.125. Cost in British pounds: 25.8 24

PHP Recursive Function

<?php

function display($number) {

if($number<=5){
echo "$number <br/>";

display($number+1);

display(1);

?>

Output:

Anonymous function variable assignment example

<?php

$greet = function($name)

printf("Hello %s\r\n", $name);

};

$greet('World');

$greet('PHP');

?>

Out put

Hello World Hello PHP


Dynamic function calls

<?php

function sayHello() {

print "hello<br>";

$function_holder = "sayHello";

$function_holder();

?>

Out put

Hello

PHP Callback Functions

A callback function (often referred to as just "callback") is a function which is passed as an


argument into another function.

Example 1

<html>

<body>

<?php

function my_callback($item) {

return strlen($item);

$strings = ["apple", "orange", "banana", "coconut"];

$lengths = array_map("my_callback", $strings);

print_r($lengths);

?>

</body>
</html>

Out put

Array
(
[0] => 5
[1] => 6
[2] => 6
[3] => 7
)

Example 2

<?php

function exclaim($str) {

return $str . "! ";

function ask($str) {

return $str . "? ";

function printFormatted($str, $format) {

// Calling the $format callback function

echo $format($str);

// Pass "exclaim" and "ask" as callback functions to printFormatted()

printFormatted("Hello world", "exclaim");

printFormatted("Hello world", "ask");

?>

Output

Hello world! Hello world?


Call Back Function in PHP

Callback Functions

A callback function (often referred to as just "callback") is a function which is passed as an


argument into another function.

Example 1

<?php

function my_callback($item) {

return strlen($item);

$strings = ["apple", "orange", "banana", "coconut"];

$lengths = array_map("my_callback", $strings);

print_r($lengths);

?>

Out put

Array
(
[0] => 5
[1] => 6
[2] => 6
[3] => 7
)

Example 2

<?php

function exclaim($str) {

return $str . "! ";

function ask($str) {

return $str . "? ";


}

function printFormatted($str, $format) {

// Calling the $format callback function

echo $format($str);

// Pass "exclaim" and "ask" as callback functions to printFormatted()

printFormatted("Hello world", "exclaim");

printFormatted("Hello world", "ask");

?>

Out put

Hello world! Hello world?


Assignment No- 3

Assignment name- Exception Handling in PHP

Roll No-

Exceptions Vs Errors in PHP

Error: An Error is an unexpected program result, which can not be handled by the program
itself. That can be solved by using the issue in the code manually. An Error can be an infinite
loop that can not be handled by the program itself so you have to manually repair that
issue. There is an easy procedure to handle error i.e. using die() function.

Example

<?php

// Open file in read mode

$file_var = fopen("myfile.txt", "r");

// Check for file existence

if (!file_exists("myfile.txt")) {

die("Sorry Error!! file does not exists");

else {

fopen("myfile.txt", "r");

?>

Output:

Sorry Error!! file does not exists

Exception: An Exception also is an unexpected result of a program but Exception can be


handled by the program itself by throwing another exception. Exceptions should only be
used with error conditions, where the error is non removal. There is an easy way to
overcome the Exception by using try and catch method.
Example

<?php

function valid_division($x, $y) {

if($y != 0) {

return true;

else {

throw new Exception("y should not be equal to 0");

try {

valid_division(2, 0);

// Try block will only run if

// there is no exception

echo "Valid division";

catch(Exception $e) {

// Catch block will run if an

// exception occurs

echo "Error\n";

echo $e->getmessage();

?>

Output:

Error

y should not be equal to 0


Difference Between Exception and Error

ERROR EXCEPTION

Error are the procedural approach. Exceptions are an object-oriented approach


to programming.

The default error handling in PHP is very Exceptions are used to change the normal
simple. An error message with filename, flow of a script if a specified error occurs.
line number and a message describing
the error is sent to the browser.

This can be done using PHP Basic Exception Handling using throw new
die() Function. Exception() in case of advance Exception
handling youn have to
use try and catch method.

Errors are mostly caused by the Program itself is responsible for causing
environment in which program is exceptions.
running.

Example: PHP Program to illustrate normal try catch block code

<?php

function demo($var) {

echo " Before try block";

try {

echo "\n Inside try block";

// If var is zero then only if will be executed

if($var == 0)
{

// If var is zero then only exception is thrown

throw new Exception('Number is zero.');

// This line will never be executed

echo "\n After throw (It will never be executed)";

// Catch block will be executed only

// When Exception has been thrown by try block

catch(Exception $e) {

echo "\n Exception Caught", $e->getMessage();

// This line will be executed whether

// Exception has been thrown or not

echo "\n After catch (will be always executed)";

// Exception will not be rised

demo(5);

// Exception will be rised here

demo(0);

?>

Output:

Before try block

Inside try block

After catch (will be always executed)

Before try block


Inside try block

Exception CaughtNumber is zero.

After catch (will be always executed)

Multiple Catch Example

<?php

declare(strict_types=1);

function divide(int $a, int $b) : int {

return $a / $b;

$a=10;

$b=0;

try{

if (!$b) {

throw new DivisionByZeroError('Division by zero.');}

if (is_int($a)==FALSE || is_int($b)==FALSE)

throw new InvalidArgumentException("Invalid type of arguments");

$result=divide($a, $b);

echo $result;

catch (TypeError $x)//if argument types not matching{

echo $x->getMessage();

catch (DivisionByZeroError $y) //if denominator is 0{

echo $y->getMessage();

}
catch (ArgumentCountError $z) //if no.of arguments not equal to 2{

echo $z->getMessage();

catch (InvalidArgumentException $i) //if argument types not matching{

echo $i->getMessage();

catch (Exception $ex) // any uncaught exception{

echo $ex->getMessage();

?>

Output

To begin with, since denominator is 0, Divide by 0 error will be displayed


Division by 0

Set $b=3 which will cause TypeError because divide function is expected to return integer
but dividion results in float
Return value of divide() must be of the type integer, float returned

If just one variable is passed to divide function by changing res=divide(a); this will result
ArgumentCountError
Too few arguments to function divide(), 1 passed in C:\xampp\php\test1.php on line 13 and
exactly 2 expected

If one of arguments is not integer, it is a case of InvalidArgumentException


Invalid type of arguments

Extending Exception Class

<?php
class myException extends Exception{
function message(){
return "error : " . $this->getMessage() . " in line no " . $this->getLine();
}
}
$num=125;
try{
if ($num>100 || $num<0)
throw new myException("$num is invalid number");
else
echo "$num is a valid number";
}
catch (myException $m){
echo $m->message();
}
?>

Output
Run above code with num=125andnum=90 to get error message and message of valid
number

error : 125 is invalid number in line no 10


Assignment No- 4

Assignment name- GET and POST in PHP


Roll No-

Difference between Get and Post methods

There are two ways the browser client can send information to the web server.

The GET Method


The POST 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 produces a long string that appears in your server logs, in the
browser's Location: box.
 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.

Get method Example


<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";

exit();
}
?>
<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>

Output

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.

Post method Example


<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

exit();
}
?>
<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>

Output
Assignment No- 5

Assignment name- htmlspecialchars() function

Roll No-

The htmlspecialchars() function converts some predefined characters to HTML entities.

The predefined characters are:

& (ampersand) becomes &amp;


" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;

Example
<?php
$str = "This is some <b>bold</b> text.";
echo $str ;
echo "<br>";
echo htmlspecialchars($str);
?>
Out put
This is some bold text.
This is some <b>bold</b> text.
Assignment No- 6

Assignment name- Simple form example

Roll No-

Form1.html
<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>

Welcome.php

<html>
<body>

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


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

</body>
</html>

Out put

Welcome ram
Your email address is [email protected]
Assignment No- 7

Assignment name- PHP Form Validation Example

Roll No-

<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Out put
PHP Form Validation Example
Name:
E-mail:
Website:

Comment:
Gender: Female Male Other
Submit

Your Input:
rupesh
[email protected]
google.com
like this website
male
Assignment No- 8

Assignment name- Multivalued form fields Example

Roll No-

Multivalued.html
<html>
<body>
<form action="indexdemo.php" method="post">
<label for="firstName">First name</label>
<input type="text" name="firstName" id="firstName" value="" />
<label for="mySelection">What are your favorite widgets?</label>
<select name="mySelection[]" id="mySelection" size="3" multiple="multiple">
<option value="PHP">PHP Language</option>
<option value="Java">Java Language</option>
<option value="CSS">CSS Language</option>
</select>
<label for="tested">Choice One?</label>
<input type="checkbox" name="chioces[]" id="ChoiceOne" value="testTask" />
<label for="designed">Choice Two?</label>
<input type="checkbox" name="chioces[]" id="ChoiceTwo" value="designTask" />
<input type="submit" name="submitButton" id="submitButton" value="Send Details"
/>
<input type="reset" name="resetButton" id="resetButton" value="Reset Form"/>
</div>
</form>
</body>
</html>

indexdemo.php

<html>
<body>
<?php
$mySelection = "";
$chiocess = "";
if ( isset( $_POST["mySelection"] ) ) {
foreach ( $_POST["mySelection"] as $widget ) {
$mySelection .= $widget . ", ";
}
}

if ( isset( $_POST["chioces"] ) ) {
foreach ( $_POST["chioces"] as $chioces ) {
$chiocess .= $chioces . ", ";
}
}
$mySelection = preg_replace( "/, $/", "", $mySelection );
$chiocess = preg_replace( "/, $/", "", $chiocess );
?><dl>
<dt>First name</dt><dd><?php echo $_POST["firstName"]?></dd>
<dt>Favorite widgets</dt><dd><?php echo $mySelection?></dd>
<dt>You want to receive the following chiocess:</dt><dd>
<?php echo $chiocess?></dd>

</dl>

</body>
</html>

Out put

Rupesh
First name
PHP Language
Java Language
What are your favorite widgets? CSS Language

Send Details Reset Form


Choice One? Choice Two?

First name
Rupesh
Favorite widgets
PHP, Java, CSS
You want to receive the following chiocess:
testTask, designTask
Assignment No- 9

Assignment name- PHP File Upload Example

Roll No-

uploadform.html
<html>
<body>
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</body>
</html>

uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);

if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
Output

You might also like