Unit4 PHP
Unit4 PHP
Introduction
• PHP stands for Hypertext Preprocessor.
• PHP is a very popular and widely-used open source server-side scripting
language to write dynamically generated web pages.
• PHP was originally created by Rasmus Lerdorf in 1994.
• PHP scripts are executed on the server and the result is sent to the web
browser as plain HTML.
• PHP can be integrated with the number of popular databases, including
MySQL, PostgreSQL, Oracle, Microsoft SQL Server, Sybase, and so on.
Things to do in PHP
• You can generate pages and files dynamically.
• 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 emails to the users of your website.
• You can send and receive cookies to track the visitor of your website.
• You can store, delete, and modify information in your database.
• You can restrict unauthorized access to your website.
• You can encrypt data for safe transmission over internet.
Requirements
• Following programs to be installed on computer.
• The Apache Web server
• The PHP engine
• The MySQL database server
• Install above softwares individually or through Pre-configured
packages.
• Pre-configured packages are XAMPP and Wamp Server (for Windows).
• Download link of XAMPP https://sourceforge.net/projects/xampp/ .
• For Linux, install and use LAMP Server and for Mac, install and use MAMP Server.
Simplex examples
• A PHP script starts with the <?php and ends with the ?> tag.
• PHP statement end with a semicolon (;)
• Syntax:
<?php
echo "Hello, world!";
?>
Embed PHP in HTML
• You can embed PHP codes within HTML to create well-formed
dynamic web pages.
• PHP engine executed the instructions between the <?php … ?> tags
and leave rest of the things as it is.
• In the end, the web server sends the final output back to your
browser which is completely in HTML.
• Example:
• <body>
• <h1><?php echo "Hello, world!"; ?></h1>
• </body>
Variables
• Variable values can change over the course of a script.
• In PHP, a variable does not need to be declared before adding a value
to it.
• PHP automatically converts the variable to the correct data type,
depending on its value.
• After declaring a variable it can be reused throughout the code.
• The assignment operator (=) used to assign value to a variable.
• Syntax:- $var_name = value;
• $txt = "Hello World!";
• $number = 10;
Variables
• Naming rules:
• All variables in PHP start with a $ 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 in PHP can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _).
• A variable name cannot contain spaces.
• Variable names in PHP are case sensitive.
Constants
• Constants are defined using PHP's define() function, which accepts
two arguments: the name of the constant, and its value.
• Example:
• define("URL", "https://www.google.com/");
• echo 'Thank you for visiting - ' . URL;
• Ex:-
$a = 'Hello world!';
echo $a;
echo "<br>";
Data Types
3) Floating point numbers:
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
Data Types
4) Boolean:
• $show_error = true;
• var_dump($show_error);
5) Array:
• $colors = array("Red", "Green", "Blue");
• var_dump($colors);
• echo "<br>";
Data Types
class hello{
6) Objects:
// properties
• An object is a specific instance of public $str = "Hello World!";
a class which serve as templates
// methods
for objects.
function show_hello(){
• Every object has properties and
return $this->str;
methods corresponding to those
of its parent class. }
}
• Every object instance is
completely independent, with its // Create object from class
own properties and methods. $message = new hello;
var_dump($message);
Data Types
7) NULL:
• NULL value is used to represent empty variables in PHP. A variable of
type NULL is a variable without any data.
$a = NULL;
var_dump($a);
echo "<br>";
Data Types
8) Resources:
• A resource is a special variable, holding a reference to an external
resource.
$handle = fopen("note.txt", "r");
PHP Strings
• Example:- $my_string = 'Hello World’;
• Strings enclosed in single-quotes are treated almost literally,
• whereas the strings delimited by the double quotes replaces variables
with the string representations of their values as well as specially
interpreting certain escape sequences.
• Example:
• $my_str = 'World';
• echo "Hello, $my_str!<br>"; // Displays: Hello World!
• echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
String Functions
• $my_str = 'Welcome to PHP Tutorial';
• echo strlen($my_str);
• $my_str = 'The quick brown fox jumps over the lazy dog.';
• echo str_word_count($my_str);
• echo str_replace(“quick", “slow", $my_str);
• echo strrev($my_str); // String reverse
Operators
• Arithmetic
• Assignment
• Comparison
• Incrementing and Decrementing
• Logical
• String
• Array
Conditional Statements
1) If condition:-
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!"; }
?>
Conditional Statements
2) If - Else condition:-
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
Conditional Statements
3) If – Else IF condition:-
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
Conditional Statements
4) Ternary operator:-
<?php
echo ($age < 18) ? 'Child' : 'Adult’;
?>
Switch Case <?php
$today = date("D");
switch(n){
switch($today){
case label1: case "Mon":
// Code to be executed if echo "Today is Monday. Clean your
n=label1 house.";
break; break;
... case "Tue":
echo "Today is Tuesday. Buy some
default: food.";
// Code to be executed if n is break;
different from all labels default:
} echo "No information available for that
day.";
break; }
?>
Loops
1) While:
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>
Loops
2) do while:
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
Loops
3) for:
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
Loops
4) foreach:
<?php
$colors = array("Red", "Green", "Blue");
foreach($colors as $value){
echo $value . "<br>";
}
?>
Functions – User Defined
Syntax: w/o parameter
function functionName(){
// Code to be executed
}
Example:-
<?php
function display(){
echo "Today is " . "good weather"
}
display();
?>
Functions – User Defined
• Syntax: with parameter
function myFunc($param1, $param2){
// Code to be executed
}
• Example:-
<?php
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20);
?>
Functions – User Defined
• Example:- Default value of parameter
<?php // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Returning value from a function
• Example:-
<?php
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}
echo getSum(5, 10);
?>
• Note:- A function cannot return multiple values. But we can achieve so by
returning an array.
Function: global keyword
• Variable declared inside the <?php
function is not accessible from $greet = "Hello World!";
outside, likewise the variable function test(){
declared outside of the function global $greet;
is not accessible inside of the echo $greet;
function. }
• Use the global keyword before test(); // Output: Hello World!
the variables inside a function. echo $greet; // Output: Hello World!
• It turns the variable into a global $greet = "Goodbye";
variable. test(); // Output: Goodbye
echo $greet; // Output: Goodbye
?>
Scope of Variable:
Ex: <?php
PHP has three different variable scopes: $x = 5; // global scope
• local function myTest() {
• global // using x inside this function will generate an error
• static echo "<p>Variable x inside function is: $x</p>";
}
Global and Local Scope myTest();
• A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function echo "<p>Variable x outside function is: $x</p>";
?>
• A variable declared within a function has a LOCAL
SCOPE and can only be accessed within that function.
Ex:<?php
function myTest() {
Static: $x = 5; // local scope
• Normally, when a function is completed/executed, all of echo "<p>Variable x inside function is: $x</p>";
its variables are deleted. However, sometimes we want }
myTest();
a local variable NOT to be deleted. We need it for a
further job. // using x outside the function will generate an error
• To do this, use the static keyword when you first declare echo "<p>Variable x outside function is: $x</p>";
the variable ?>
PHP The global Keyword
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function)
Ex: <?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Arrays
• 3 Types of Arrays:
• Indexed array — An array with a numeric index.
• Associative array — An array where each key/index has its own
specific value.
• Multidimensional array — An array containing one or more arrays
within itself.
Arrays
1) Indexed array — An array with a numeric index.
<?php
$colors = array("Red", "Green", "Blue");
?>
<?php
$colors[0] = "Red";
$colors[1] = "Green";
?>
Arrays
2) Associate array
<?php
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
?>
Arrays
3) Multidimensional array:- Each element can also be an array and each
element in the sub-array can be an array or further contain array
within itself and so on.
PHP GET:
• Data passed through get request is visible on the URL browser so it is
not secured.
• Send limited amount of data through get request.
PHP Form Handling: GET and POST
PHP GET Example: • welcome.php:
• HTML Form: <?php
<form action="welcome.php" $name=$_GET["name"];
method="get"> echo "Welcome, $name";
Name: <input type="text" ?>
name="name"/>
<input type="submit"
value="visit"/>
</form>
PHP Form Handling: GET and POST
PHP POST:
• Data passed through the post request is not visible on the URL browser so it is secured.
• Send large amount of data (like file upload, image upload, login form, registration data,
etc.) through post request.