SL Unit-Iv (PHP)
SL Unit-Iv (PHP)
html
Internet information services
Basic PHP Syntax
• A variable must start with a dollar ($) sign, followed by the variable
name.
• It can only contain alpha-numeric character and underscore (A-z, 0-
9, _).
• A variable name must start with a letter or underscore (_) character.
• A PHP variable name cannot contain spaces.
• the variable name cannot start with a number or special symbols.
• PHP variables are case-sensitive, so $name and $NAME both are
treated as different variable.
• <?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>
echo $y;
?>
Output:
Hello world!
5
10.5
PHP Variable: Sum of two variables
Filename: sum.php
• <?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Save: C:\xampp\htdocs\sum.php
Run : http://localhost/sum.php
PHP echo and print Statements
• In PHP, there are two basic ways to get output:
echo and print.
• PHP echo is a language construct, not a function. Therefore, you
don't need to use parenthesis with it.
• <?php
print “ <h2> PHP is Fun! </h2>";
print "Hello world! <br>";
print "I'm about to learn PHP!";
?>
PHP Print
echo print
• echo is a statement, which is • print is also a statement, used as
used to display the output. an alternative to echo at many
• echo can be used with or times to display the output.
without parentheses. • print can be used with or
• echo does not return any without parentheses.
value. • print always returns an integer
• value, which is 1.
We can pass multiple strings
separated by comma (,) in • Using print, we cannot pass
echo. multiple arguments.
• • print is slower than echo
echo is faster than print
statement.
statement.
• We can pass multiple arguments separated by a comma(,)in echo. It
will not generate any syntax error.
Program:
<?php
$fname=“raj”;
$lname=“kumar”;
echo ”my name is:”.$fname, $lname;
?>
PHP Variable Scope
• The global variables are the variables that are declared outside the
function.
• Static variables exist only in a local function, but it does not free its
memory after the program execution leaves the scope
<?php
function myTest()
{
static $x=0;
echo $x;
echo”<br>”;
$x++;
}
myTest();
myTest();
myTest();
?>
Output:
0
1
2
PHP Data Types
PHP data types are used to hold different types of data or
values. PHP supports 8 primitive data types that can be categorized
further in 3 types:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
<?php
$str= “hello";
//both single and double quote statements will treat different
echo "Hai $str";
echo "</br>";
echo 'Hello $str';
?>
Output: Haihello
Hello$str
PHP Array
• An array stores multiple values in one single variable.
• The var_dump() function returns the data type and value.
<?php
$names = array(“ram",“raj",“ravi");
var_dump($names);
?>
Output:
array(3) {
[0]=> string(3) “ram"
[1]=> string(3) “raj"
[2]=> string(4) “ravi" }
PHP NULL Value
• Null is a special data type which can have only one value:
NULL.
• A variable of data type NULL is a variable that has no value
assigned to it.
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output: NULL
PHP Object
• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
Resource
• Resource is a special data type that refers to any external resource.
• A resource variable acts as a reference to external source of data
such as stream, file, database etc.
• PHP uses relevant functions to create these resources.
• For example, fopen() function opens a disk file and its reference is
stored in a resource variable.
PHP Operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators
Example
Output
Not Equal(because string type and integer type are not equal
=== checks datatype and value equality)
The precedence of “AND” operator is lower than the “&&”
Date function
• d - The day of the month (from 01 to 31)
• D - A textual representation of a day (three letters)
• j - The day of the month without leading zeros (1 to 31)
• l (lowercase 'L') - A full textual representation of a day
• N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
• S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works
well with j)
• w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
• z - The day of the year (from 0 through 365)
• W - The ISO-8601 week number of year (weeks starting on Monday)
• F - A full textual representation of a month (January through December)
• m - A numeric representation of a month (from 01 to 12)
• M - A short textual representation of a month (three letters)
• n - A numeric representation of a month, without leading zeros (1 to 12)
• t - The number of days in the given month
• L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
Syntax
date(format, timestamp)
timestamp Optional. It Specifies an integer Unix
timestamp. Default is the current local time
(time())
Control Statements
if (condition)
{
code to be executed if condition is true;
} else
{
code to be executed if condition is false;
}
Example :
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>
PHP switch Statement
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favourite color is red!";
break;
case "blue":
echo "Your favourite color is blue!";
break;
case "green":
echo "Your favourite color is green!";
break;
default:
echo "Your favourite color is neither red, blue, nor green!";
}
?>output:
Your favourite color is red!
PHP Loops
Syntax:
while (condition is true)
{
code to be executed;
}
code
<? php
$x = 1;
while($x <= 5)
{ echo "The number is: $x";
$x++;
}
?>
Syntax:
do {
code to be executed;
} while (condition is true);
Example:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
Syntax:
for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop
ends.
increment counter: Increases the loop counter value.
Example:
<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>
output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Syntax:
For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
output:
red
green
blue
yellow
PHP User Defined Functions
• A function is a block of statements that can be used repeatedly
in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
Syntax:
function function_Name()
{
code to be executed;
}
Example:
<?php
function writeMsg()
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Parameterized Function
• PHP allows you to call function by value and reference both. In case
of PHP call by value, actual value is not modified if it is modified
inside the function.
Program:
<?php
function fun($str2)
In this example, variable $str is passed to
{
the fun function where it is concatenated
$str2 .= 'Call By Value';
with 'Call By Value' string. But, printing
}
$str variable results 'Hello' only. It is
$str = 'Hello '; because changes are done in the local
fun($str); variable $str2 only. It doesn't reflect to
echo $str; $str variable.
?> output:Hello
<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output: 10
Passing Arguments by Reference
The count() function is used to return the length (the number of elements)
of an array
Loop Through an Indexed Array
(or)
• $age[‘ram'] = "35";
$age[‘raj'] = "37";
$age[‘ravi'] = "43";
First method to associate create array
second method to associate create array
PHP Multidimensional Array
<?php
echo str_replace("world", "Dolly", "Hello world!");
// outputs Hello Dolly!
?>
PHP chop() Function
<?php
$str = "Hello World!\n\n";
echo $str;
echo chop($str);
?>
• <?php
$str = "Hello World!";
echo $str . "<br>";
echo chop($str,"World!");
?>
Output:
Hello World!
Hello
PHP chr() Function
• <?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value
?>
Output:
4
*
R
PHP string join() Function
<?php
$arr = array('Hello','PHP','Join','Function');
echo join("-",$arr)."<br>";
?>
Output:
Hello-PHP-Join-Function
implode() Function
• Join array elements with a string:
Syntax:
implode(separator,array);
Parameters:
•Separator Optional ,Specifies what to put between the array
elements. Default is "" (an empty string)
•Array Required. The array to join to a string
Progarm:
<?php
$arr = array('Hello','World!','Beautiful','Day!’);
echo implode(" ",$arr);
?>
Output: Hello World! Beautiful Day!
PHP ord() Function
• The ord() function returns the ASCII value of the first character of a
string.
Syntax:
ord(string);
Program:
<?php
echo ord("h")."<br>";
echo ord("hello")."<br>";
?>
output:
104
104
PHP strtolower() Function
Program:
<?php
echo strtoupper("Hello WORLD!");
?>
Output:
HELLO WORLD
PHP File Handling
• PHP File System allows us to create file, read file line by line, read file character by
character, write file, append file, delete file and close file.
• PHP has many functions to work with normal files. Those functions are:
fopen() –
• PHP fopen() function is used to open a file.
• First parameter of fopen() contains name of the file which is to be opened and
second parameter tells about mode in which file needs to be opened, e.g.,
Parameters:
program:
<?php
$file = fopen(“demo.txt”,’w’);
?>
Files modes
• “w” – Opens a file for write only. If file not exist then new file
is created and if file already exists then contents of file is erased.
• “r” – File is opened for read only.
• “a” – File is opened for write only. File pointer points to end of
file. Existing data in file is preserved.
• “w+” – Opens file for read and write. If file not exist then new
file is created and if file already exists then contents of file is
erased.
• “r+” – File is opened for read/write.
• “a+” – File is opened for write/read. File pointer points to end
of file. Existing data in file is preserved. If file is not there then
new file is created.
fread()
After file is opened using fopen() the contents of data are read using
fread(). It takes two arguments.
syntax: string fread ( $file, $length );
Parameter:
$file: It is a mandatory parameter which specifies the file.
$length: It is a mandatory parameter which specifies the maximum
number of bytes to be read.
fwrite()
New file can be created or text can be appended to an existing file using
fwrite() function.
• Arguments for fwrite() function are file pointer and text that is to written
to file.
• It can contain optional third argument where length of text to written is
specified,
File is closed using fclose() function. Its argument is file which needs
to be closed, e.g.,
Program:
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
PHP Delete File - unlink()
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
// Output one character until end-of-file
while(!feof($myfile))
{
echo fgetc($myfile);
}
fclose($myfile);
?>
PHP Append to File
Program:
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
• We can create and use forms in PHP. To get form data, we need to
use PHP superglobals $_GET and $_POST.
• The form request may be get or post. To retrieve data from get
request, we need to use $_GET, for post request $_POST.
PHP Get Form
Get request is the default form request. The data passed through get
request is visible on the URL browser so it is not secured. You can send
limited amount of data through get request.
File: form1.html
• Post request is widely used to submit form that have large amount of
data such as file upload, image upload, login form, registration form
etc.
• The data passed through post request is not visible on the URL
browser so it is secured. You can send large amount of data through
post request.
• Let's see a simple example to receive data from post request in PHP.
form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></
tr>
<tr><td>Password:</
td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></
tr>
</table>
</form>
login.php
<?php
$name=$_POST["name"];//
receiving name field value in $name variable
$password=$_POST["password"];//
receiving password field value in $password variable