PHP Unit 1
PHP Unit 1
Unit - I
• Introduction to PHP:
Introduction to PHP:
What is PHP
• PHP is faster than other scripting languages, for example, ASP and JSP.
1
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
PHP Features
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.
2
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
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.
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 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.
3
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.
Security:
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.
• You can create, open, read, write and close files on the server.
• You can collect data from a web form such as user information,
email, phone no, etc.
• You can send and receive cookies to track the visitor of your website.
4
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
If you're familiar with other server-side languages like ASP.NET or Java, you
might be wondering what makes PHP so special. There are several
advantages why one should choose PHP.
File: first.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
echo "<h2>Hello First PHP</h2>";
5. ?>
6. </body>
7. </html>
5
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
Output:
Web Technology
You probably know that computers don't communicate with each other the way that people
do. Instead, computers require codes, or directions. These binary codes and commands
allow computers to process needed information. Every second, billions upon billions of ones
and zeros are processed in order to provide you with the information you need.
So what does that have to do with your ability to post your latest pictures online? Everything.
The methods by which computers communicate with each other through the use of markup
languages and multimedia packages is known as web technology.
Client-Side Scripting
Generally refers to computer programs on the web that are executed by the user's web
browser, instead of on a web server, enabling web pages to be scripted. Client-side scripts
do not require additional software on the server but instead utilize the user's web browser to
understand the scripting language in which it is written.
Example-javascript,vbscript
JavaScript
JavaScript is a scripting language that is used along with HTML and CSS as the three core
components of the World Wide Web. JavaScript has first-class functions and is used in most
websites. JavaScript does not have any I/O which means that it has to be embedded in the
host environment. JavaScript is also used in PDF documents, game development, and
desktop and mobile applications. JavaScript is most commonly used to make DHTML by
adding client-side behavior to HTML pages.
Server-Side Scripting
Server-side scripting is a technique used in web development that involves using scripts on a
web server which produce a unique response for each user's request to the website.
Example-php,jsp
Web Browser
6
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
Web Server
7
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>
<html>
<head></head>
<body>
<ul>
<?php for($i=1;$i<=5;$i++){ ?>
<li>Menu Item <?php echo $i; ?></li>
<?php } ?>
</ul>
</body>
</html>
<html>
<head></head>
<body class="page_bg">
Hello, today is <?=date('l, F jS, Y'); ?>.
</body>
</html>
<?php
echo "<html>";
echo "<head></head>";
echo "<body class=\"page_bg\">";
echo "Hello, today is ";
echo date('l, F jS, Y'); //other php code here echo "</body>";
echo "</html>";
?>
8
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
PHP Variables
Variables are "containers" for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the
variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will
hold the value Hello world!, the variable $x will hold the value 5, and the
variable$y will hold the value 10.5.
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
9
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The scope of a variable is the part of the script where the variable can be
referenced/used.
• local
• global
• static
Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
10
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
To do this, use the global keyword before the variables (inside the
function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
11
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
LOCAL SCOPE
A variable declared within a function has a LOCAL SCOPE and can only
be accessed within that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
12
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
myTest();
myTest();
myTest();
?>
13
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
PHP - Functions
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.
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 – Syntax
function name_of_function()
Php code;
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice
time!";
}
PHP gives you option to pass your parameters inside a function. You can pass
as many as parameters your like. These parameters work like variables inside
your function. Following example takes two integer parameters and add them
together and then print them.
14
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
Any changes made to an argument in these cases will change the value of the
original variable. You can pass an argument by reference by adding an
ampersand to the variable name in either the function call or the function
definition.
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
A function can return a value using the return statement in conjunction with a
value or object. return stops the execution of the function and sends the value
back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and
then returns their sum to the calling program. Note thatreturn keyword is used
to return a value from a function.
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
You can set a parameter to have a default value if the function's caller doesn't
pass it.
Following function prints NULL in case use does not pass any value to this
function.
?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
16
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
$function_holder = "sayHello";
$function_holder();
?>
PHP if statement
if (expression)
statement
$num = 31;
if ($num > 0) {
echo "\$num variable is positive\n";
echo "\$num variable equals to $num\n";
}
17
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
If-else statement
<?php
$sex = "female";
if ($sex == "male") {
echo "It is a boy\n";
} else {
echo "It is a girl\n";
}
<?php
$a = intval(fgets(STDIN));
if ($a < 0) {
printf("%d is a negative number\n", $a);
} elseif ($a == 0) {
printf("%d is a zero\n", $a);
} elseif ($a > 0) {
printf("%d is a positive number\n", $a);
}
We read a value from the user using the fgets() function. The value is
tested if it is a negative number or positive or if it equals to zero.
The switch statement works with two other keywords: case and break.
The case keyword is used to test a label against a value from the round
brackets. If the label equals to the value, the statement following the case is
executed. The break keyword is used to jump out of the switchstatement.
18
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
domains.php
<?php
$domain = 'sk';
switch ($domain) {
case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}
while (expression):
statement
The while loop executes the statement when the expression is evaluated to
true. The statement is a simple statement terminated by a semicolon or a
compound statement enclosed in curly brackets.
whilestm.php
<?php
19
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
$i = 0;
The for loop does the same thing as the while loop. Only it puts all three
phases, initialization, testing and updating into one place, between the
round brackets. It is mainly used when the number of iteration is know
before entering the loop.
forloop.php
<?php
$len = count($days);
foreachstm.php
<?php
20
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
echo "\n";
?>
foreachstm2.php
<?php
The break statement is used to terminate the loop. The continue statement is
used to skip a part of the loop and continue with the next iteration of the
loop.
testbreak.php
<?php
while (true) {
echo "\n";
We define an endless while loop. There is only one way to jump out of a
such loop—using thebreak statement. We choose a random value from 1 to
30 and print it. If the value equals to 22, we finish the endless while loop.
$ php testbreak.php
6 11 13 5 5 21 9 1 21 22
21
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
testcontinue.php
<?php
$num = 0;
$num++;
if (($num % 2) == 0) continue;
echo "\n";
if (($num % 2) == 0) continue;
Forms can be used to pass values to different sites. Forms can submit
the data to a processing script running at a different URL in different server.
These are some of the way of transferring data variables between pages.
22
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
PHP $GLOBALS
The example below shows how to use the super global variable
$GLOBALS:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
23
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
PHP $_SERVER
PHP $_REQUEST
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form
data after submitting an HTML form with method="post". $_POST is also
widely used to pass variables.
24
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form
data after submitting an HTML form with method="get".
<html>
<body>
</body>
</html>
25
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
example
<?php
$foo = "5bar"; // string
$bar = true; // boolean
<?php
?>
Output
integer
double
NULL
object
string
26
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<?php
$yes = array('this', 'is', 'an array');
Output
Array
not an Array
Returns the int value of value, using the specified base for the conversion (the
default is base 10). intval() should not be used on objects, as doing so will emit
an E_NOTICE level error and return 1.
<?php
echo intval(42); // 42
echo intval(4.2); // 4
?>
<?php
echo strval(42);?> output “42”
27
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
Return Values
The float value of the given variable. Empty arrays return 0, non-empty arrays
return 1.
<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>
<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>
isset() Function
Check whether a variable is empty. Also check whether the variable is
set/declared:
isset(variable, ....);
<?php
$a = 0;
// True because $a is set
if (isset($a)) {
echo "Variable 'a' is set.<br>";
}
$b = null;
// False because $b is NULL
if (isset($b)) {
echo "Variable 'b' is set.";
}
?>
28
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
unset() Function
Syntax:-unset(variable, ....);
<?php
$a = "Hello world!";
echo "The value of variable 'a' before unset: " . $a . "<br>";
unset($a);
echo "The value of variable 'a' after unset: " . $a;
?>
print_r() Function
The print_r() function prints the information about array/variable in a
more human-readable way.
Syntax:-print_r(variable, return);
<?php
$a = array("red", "green", "blue");
print_r($a);
echo "<br>";
Output:-
Array ( [0] => red [1] => green [2] => blue )
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
Check if several dates are valid Gregorian dates: return true or false
<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
29
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
getdate(timestamp)
The getdate() function returns date/time information of a
timestamp or the current local date/time.
date(format, timestamp)
The date() function formats a local date and time, and returns the
formatted date string.
<?php
// Prints the day
echo date("l") . "<br>";
Output
Saturday
Saturday 30th of January 2021 05:11:07 AM
strtotime(time, now);
<?php
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
?>
30
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
date_format(object, format)
<?php
$date=date_create("2013-03-15");
echo date_format($date,"d/m/Y H:i:s");
?>
Output
15/03/2013 00:00:00
31
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
32
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
PHP Arrays
An array is used to store multiple values, generally of same type, in a single
variable.
n such case, PHP arrays are used. Arrays can store multiple values together in
a single variable and we can traverse all the values stored in the array using the
foreach ad other loop statement.
Creating an Array
We can create an array in PHP using the array() function.
Syntax:
<?php
/*
a simple array with car names
*/
$$cars= array("Maruti", "Hundai", "Tata");
?>
33
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
To access the data stored in an array, we can either use the index numbers or
we can use a foreach loop to traverse the array elements.
<?php
/*
access array element using index
*/
$$cars= array("Maruti", "Hundai", "Tata");
echo $cars[0];
//or
?>
<?php
/*
access array element using foreach
*/
$$cars= array("Maruti", "Hundai", "Tata");
foreach($cars as $val)
{
echo $val.”<br>”;
}
//
?>
34
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<?php
?>
<?php
/*
*/
?>
35
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
and the syntax for the 2nd way to create associative array is:
<?php
/*
*/
$cars["hatch"] = "Swift";
$suzuki["utility"] = "Ertiga";
$suzuki["suv"] = "maruti";
?>
36
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar