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

Unit4 PHP

PHP is a widely used open source server-side scripting language used to create dynamically generated web pages. Key things that can be done in PHP include generating pages and files dynamically, collecting and storing user data from forms in databases, sending emails, and restricting unauthorized access. PHP scripts are executed on the server and the results are sent to the browser as HTML. PHP can be integrated with popular databases like MySQL. Common PHP features include variables, constants, data types, conditional statements, loops, functions, and scope of variables.

Uploaded by

Nagendra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Unit4 PHP

PHP is a widely used open source server-side scripting language used to create dynamically generated web pages. Key things that can be done in PHP include generating pages and files dynamically, collecting and storing user data from forms in databases, sending emails, and restricting unauthorized access. PHP scripts are executed on the server and the results are sent to the browser as HTML. PHP can be integrated with popular databases like MySQL. Common PHP features include variables, constants, data types, conditional statements, loops, functions, and scope of variables.

Uploaded by

Nagendra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Unit 4: 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;

• Name of constants must follow the same rules as variable names.


• $ prefix is not required for constant names.
Data Types
1) Integers:
• Integers can be specified in decimal (base 10), hexadecimal (base 16 -
prefixed with 0x) or octal (base 8 - prefixed with 0) notation,
optionally preceded by a sign (- or +).

• $b = -123; // a negative number


• $c = 0x1A; // hexadecimal number
Data Types
2) Strings:
• A string can hold letters, numbers, and special characters and it can
be as large as up to 2GB .
• Specify a string in single quotes (e.g. 'Hello world!'), however you can
also use double quotes ("Hello world!").

• 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.

Name Stock Sold


Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
<?php
$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);
  
for ($row = 0; $row < 4; $row++) {
        echo "<p><b>Row number $row</b></p>";
        echo "<ul>";
        for ($col = 0; $col < 3; $col++) {
            echo "<li>".$cars[$row][$col]."</li>";
    }
  echo "</ul>";
}
?>
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
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "[email protected]",
),
array(
"name" => "Clark Kent",
"email" => "[email protected]",
),
);
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>
Viewing Array Structure and Values
• See the structure and values of any array by using one of two
statements — var_dump() or print_r().
<?php
$cities = array("London", "Paris", "New York");
print_r($cities);
var_dump($cities);
?>
PHP Sorting Arrays
<?php
$colors = array("Red", "Green",
• Functions For Sorting Arrays:
"Blue", "Yellow");
• sort() and rsort() — For sorting sort($colors);
indexed arrays
print_r($colors);
• asort() and arsort() — For sorting
associative arrays by value //Descending order
• ksort() and krsort() — For sorting rsort($colors);
associative arrays by key print_r($colors);
$numbers = array(1, 2, 2.5, 4, 7, 10);
• 1) Sorting Indexed Arrays: sort() sort($numbers);
function print_r($numbers);
?>
PHP Sorting Arrays
2) Sorting Associative Arrays: Sort By Value
<?php
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
asort($age);
print_r($age);
//Descending order
arsort($age);
print_r($age);
?>
PHP Sorting Arrays
3) Sorting Associative Arrays: Sort By Key
<?php
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by key and print
ksort($age);
print_r($age);
//Descending order
krsort($age);
print_r($age);
?>
PHP Form Handling: GET and POST
• The form request may be get or post.
• To retrieve the data from get request, we need $_GET global variable,
and for post request, we need $_POST global variable.

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.

• Example: HTML Form


<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>
PHP Form Handling: GET and POST
• PHP POST:
Example: login.php
<?php
$name=$_POST["name"];
$password=$_POST["password"];
echo "Welcome: $name, your password is: $password";
?>
PHP Form Handling: GET and POST
• $_REQUEST: This variable contains the <html>
contents of both $_GET, $_POST, and <body>
$_COOKIE.
<form action = "<?php $_PHP_SELF ?>"
• Example: test.php method = "POST">
<?php Name: <input type = "text" name =
if( $_REQUEST["name"] || $_REQUEST["age"] "name" />
){ Age: <input type = "text" name = "age" />
echo "Welcome ". $_REQUEST['name']. <input type = "submit" />
"<br />";
</form>
echo "You are ". $_REQUEST['age']. " years
old."; </body>
exit(); </html>
}
?>
PHP Form Handling: GET and POST
• $_REQUEST:
• $_PHP_SELF variable contains the name of self script in which it is
being called.

You might also like