• No results found

Lec 10 PHP - II.pptx

N/A
N/A
Protected

Academic year: 2020

Share "Lec 10 PHP - II.pptx"

Copied!
66
0
0

Loading.... (view fulltext now)

Full text

(1)

1

CS428 Web Engineering Lecture 10

Data Types , Arrays, SuperGlobal Arrays Include, require, Cookies & Sessions

(2)

STRINGS

• <?php

echo “Hello World <br />”;

echo ‘Hello World <br />’;

$my_variable = “Hello World”;

echo $my_variable;

echo $my_variable . “ Again”;

?>

• Output: Hello World Again

HTML tags can also be

used in strings

We can also concatenate

(3)

EXAMPLE

• We can use variable in double quotes as well.

• <?php

$my_variable = “Hello World”; ?>

• <?php

echo “$my_variable Again.”; ?>

(4)

String Functions

• <?php

$firstString = “The quick brown tiger”;

$secondString = “ jumped over the lazy cat”; ?>

• <?php

$thirdString = $firstString;

$thirdString .= $secondString;

echo $thirdString; ?>

• Output: The quick brown tiger jumped over the lazy cat.

Another way of

(5)

• <?php $firstString = “The quick brown tiger”; ?> <br />

• Lower case:

<?php echo strtolower($firstString); ?><br />

• Upper case:

<?php echo strtoupper($firstString); ?><br />

• Uppercase first-letter:

<?php echo ucfirst($firstString); ?><br />

• Uppercase words:

(6)

• Length:

<?php echo strlen($firstString); ?><br/>

• Trim:

<?php echo $fourthString = $firstString .

Trim(secondString); ?><br/>

• Find:

<?php echo strstr($thirdString, “brown”); ?><br />

• Replace by String:

<?php echo str_replace(“quick”, “super-fast”, $thirdString); ?>

(7)

MORE STRING FUNCTIONS

• Repeat:

str_repeat($thirdString, 2);

• Make substring:

substr($thirdString, 5, 10);

• Find position:

strpos($thirdString, “brown”);

• Find character:

(8)
(9)

Numbers

• <?php

$var1 = 3; $var2 = 4;

?>

Basic Math:

<?php echo ((1 + 2 + $var1)* var2) / 2 -5; ?>

<br />

(10)

EXAMPLE

• <?php

$var1 = 3; $var2 = 4;

?>

+=: <?php

$var2 += 4;

echo $var2;

?>

• Output: +=: 8

You can add any value and

(11)

• +=: <?php $var2 += 4; echo $var2; ?> <br/> • -=: <?php $var2 -= 4; echo $var2; ?> <br/> • *=: <?php $var2 *= 3; echo $var2; ?> <br/> • /=: <?php $var2 /= 4; echo $var2; ?> <br/>

• Output: +=: 8 -=: 4

(12)

INCREMENT & DECREMENT

• Increment by 1.

Increment: <?php $var2++; echo $var2; ?>

• Decrement by 1.

(13)

FLOATING POINT NUMBERS

• <?php $var1 = 3.14; ?>

• Floating Point: <?php echo $myFloat = 3.14; ?>

• Round: <?php echo round($myFloat, 1); ?>

• Ceiling: <?php echo ceil($myFloat); ?>

• Floor: <?php echo floor($myFloat); ?>

• Output: Floating Point: 3.14 Round: 3.1

(14)

FLOATING POINT FUNCTIONS

Absolute Value: abs(0 - 300);

Exponential: pow(2, 8);

Square Root: sqrt(100);

Modulo: fmod(20, 7);

Random (any): rand();

(15)

ARRAYS

• You can think of an array is a variable, in which you can assign multiple values.

• <?php $array = array(4, 8, 16, 17 , 23, 42); ?> <?php echo $array[1]; ?>

Output: 8

(16)

EXAMPLE

• <?php

$array2 = array(6, “amjad”, “aslam”, array(“x”, “y”, “z”)); ?>

<?php echo $array2[2]; ?> <br/> <?php echo $array2[3]; ?>

<?php echo $array2[3][1]; ?>

• Output: aslam Array

(17)

ADD/UPDATE THE VALUE OF ARRAY

• <?php

$array2[3] = “cat”;

?>

<br />

• <?php

echo $array2[3];

(18)

ASSOCIATIVE ARRAY

• <?php $array3 = array(“first_name” => “Yasir”, “last_name” => “Naeem”);

?>

• <?php echo $array3[“first_name”]; ?> <br/> • <?php echo $array3[“first_name”] . “ ” .

$array3[“last_name”]; ?>

• Output: Yasir

Yasir Naeem

(19)

• <?php $array3[“first_name”] = “Kashif”; ?>

• <?php echo $array3[“first_name”] . “ ” . $array3[“last_name”]; ?>

• Output: Kashif Naeem

• <pre><?php print_r($array2); ?></pre>

Print readable command gives

contents of an array in readable form

(20)

ARRAY FUNCTIONS

• <?php $array1 = array(4, 8, 15, 16, 23, 42); ?> Count: <?php echo count($array1); ?><br/>

Max value: <?php echo max($array1); ?><br/>

Min value: <?php echo min($array1); ?><br/>

Sort: <?php sort($array1); print_r($array1); ?>

(21)

• Implode: <?php echo $string1 = implode(“*”, $array1); ?> <br/>

Implode function is used to separate the array by * to make a string.

• Explode: <?php print_r(explode(“ * ”, $string1)); ?>

It does the reverse, it takes the string that we just created find every instance,

(22)

• In array: <?php

echo in_array(3, $array1);

?>

This function help us to find a

particular string or value in our array.

(23)

BOOLEANS

• <?php

$bool1 = true; $bool2 = false;

?>

$bool1: <?php echo $bool1; ?><br/> $bool2: <?php echo $bool2; ?><br/>

• Output: $bool1: 1 $bool2:

true/false doesn’t mean it’s a string. When we type true, php understands its

(24)

• <?php

$var1 = 3;

$var2 = “cat”;

?>

$var1 is set: <?php echo isset($var1); ?>

$var2 is set: <?php echo isset($var2); ?>

• Note: isset() is very useful function, which

we can use with conditional statements.

Through this function we are asking, is the value of the variable is set or not. It will

(25)

• <?php unset($var1); ?>

$var1 is set: <?php echo isset($var1); ?>

$var2 is set: <?php echo isset($var2); ?>

• Output: $var1 is set: $var2 is set: 1

This function will unset the value of a

(26)

• <?php

var4 = 0; var5 = “0”;

var6 = NULL;

?>

(27)

• <?php echo is_array($var1); ?><br/>

• <?php echo is_bool($var1); ?><br/>

• <?php echo is_float($var1); ?><br/>

• <?php echo is_int($var1); ?><br/>

• <?php echo is_null($var1); ?><br/>

• <?php echo is_numeric($var1); ?><br/>

(28)

CONSTANTS

• <?php

$max_width = 980;

define(“MAX_WIDTH”, 980);

echo MAX_WIDTH; echo “<br />” // MAX_WIDTH += 1;

// echo MAX_WIDTH; $max_width += 1;

echo $max_width;

?>

Error: Cannot apply += to constant. Because

MAX_WIDTH is fixed and unchangeable

It should be in all caps, and shouldn’t have $ sign

(29)

SuperGlobal Arrays

• In PHP, there is pre-defined array variables

present that is called superglobals.

(30)

Array Details

$_GET Store data that is sent from URL as query string

$_POST Data from FORM fields store in this array

$_COOKIE Data from Cookie store in this array e.g. you login to

hotmail.com, you provide username and password below it there is a checkbox and when you check this checkbox your username and password stored in cookie, next time to log on you don’t need to provide username and password it

retrieve from cookie.

$_FILES When through POST method we upload any file its

information stored in this array

$_SESSION

$_REQUEST Data in $_POST, $_GET, $_COOKIE store in this array, 3 in 1.

(31)

$_POST

• We use post method in a form. When we submit the button of form, all the data of form is send to $_POST array.

<form method=“post” action=“process.php”>

(32)

EXAMPLE

• Forms.php

• <form action = “process.php” method=“post”>

Username: <input type=“text” name=“username”

value=“” /> <br />

Password: <input type=“password” name=“password” value=“” /> <br />

<input type=“submit” name=“submit” value=“Submit” />

(33)

• Process.php (we just want to display values back to our page)

• <?php

$username = $_POST[‘username’]; $password = $_POST[‘password’];

echo “{$username}: {$password}”;

(34)

$_GET

The data that we send through URL also known as

query string is stored in this super global array $_GET.

http://www.example.com/search.php?keyword=pakistan

• Query string started in URL after ? Sign.

• In a URL there may be more than one query string.

http://www.example.com/search.php?

(35)

HOW TO USE PHP WITH LINKS/URL’s

• <a href=“secondpage.php?id=1”>Second Page </a>

• What if instead on second page grasp this value of id, and be able to work with it.

(36)

EXAMPLE

• Firstpage.php

<a href=“secondpage.php?name=Yasir”>Second Page</a>

• Secondpage.php

<?php

print_r($_GET);

$name = $_GET[‘name’];

echo “<br/><strong>” . $name . “</strong>”;

?>

(37)

• When after ? You insert key value pair, PHP converts it into an array and we get the value of array in second page. This array is called super global. It is called

super global because it creates before the load of the page.

• We can access this super global array through $_GET

(38)

EXAMPLE

• Multiple values from URL, & is use to separate values.

• Firstpage.php

<a href=“secondpage.php?name=Yasir&id=1”>Second Page</a>

• Secondpage.php <?php

print_r($_GET);

$id = $_GET[‘id’];

$name = $_GET[‘name’];

echo “<br/><strong>” . $id . “: {$name} </strong>”; ?>

(39)

urlencode()

• What if the & is included in the name. we could come with some kind of string that we passes &, % # sign.

• Firstpage.php

<a href=“secondpage.php?name=<?php echo

urlencode(“Yasir&”); ?>&id=42”>Second Page</a>

• Secondpage.php

<?php

print_r($_GET); $id = $_GET[‘id’];

$name = $_GET[‘name’];

(40)

$_FILES

• When we upload a file or an image to server, it stores in $_FILES array.

• Example:

• User uploads a file from his computer c:\ docs\project.zip

• Its size is 20,000 bytes

(41)

• C:\docs\project.zip : $_FILES[userfile][name]

20000 : $_FILES[userfile][size]

(42)

• $file_name = $_FILES[‘userfile’][‘name’];

• $file_tmp_name = $_FILES[‘userfile’][‘tmp_name’]; • $file_size = $_FILES[‘userfile’][‘size’];

• $file_type = $_FILES[‘userfile’][‘type’];

• Because the file is uploaded on a

(43)

EXAMPLE

• Upload_form.php

<html> <head>

<title>Upload File</title> </head>

<body>

<form method=“post” action=“upload.php” enctype=“multipart/form-data”>

<input type=“file” name=“userfile” />

<input type=“submit” value=“Upload” name=“action” /> </form>

(44)

• Upload.php

<?php

$upload_dir = “./user_files”;

$file_name = $_FILES[‘userfile’][‘name’];

$file_tmp_name = $_FILES[‘userfile’][‘tmp_name’]; $file_size = $_FILES[‘userfile’][‘size’];

$file_type = $_FILES[‘userfile’][‘type’];

if($file_size <= 0){

die(“cannot upload empty file”); }

if(is_uploaded_file($_FILES[‘userfile’][‘tmp_name’])){

move_uploaded_file($file_tmp_name, “$upload_dir/$file_name”); echo “$file_name has been successfully uploaded.”;

}else{

die(“possible file upload attack”); }

(45)

• There are three ways that we get data from our users on the web. User can provide

information to server through three ways.

• URL’s/Links GET

• Forms POST

• Cookies COOKIE

(46)

FORMS

• Forms are also known as POST method, because when user enter any data in form,

it is posted to our web server.

• When data is submitted to server, you can do lots of things with data i.e. You can

display on the web page, you can save it

in the database, you can give

(47)

COOKIE

• Another way to interact with our users in user’s browser is COOKIES.

• Cookies are very useful, putting data on user’s browser.

• Our web server make a request to their web browser to send back a cookie.

• Cookies are going to be access in the same way as POST.

(48)

SETTING COOKIE

• Format

setcookie($name, $value, $expire);

(49)

EXAMPLE

• <?php

setcookie(‘test’, 42, time()+(60*60*24*7));

?>

This command means our

cookie date of birth is declared

Expiration that we set in

(50)

READING COOKIES

• <?php

$var1 = $_COOKIE[‘test’]; echo $var1;

?>

• Deleting cookies

<?php

// this will delete the cookie

setcookie(‘test’, 0, time()-(60*60*24*7));

?>

(51)

DELETING COOKIE

• Whenever we read a cookie, its going to be a very good practice.

• <?php

$var1 = 0;

if(isset($_COOKIE[‘test’])) { $var1 = $_COOKIE[‘test’]; }

echo $var1; ?>

<?php

(52)

SESSION

• Session is a file that store on web server. And in

that file we can store whatever information we want.

• The way we find out which file belongs to which user is by using a cookie.

• So we set a special session cookie on their

(53)

• So, in order to use the session, we are going to have the first create this file and set the cookie on user’s machine. Or if we already done that. We are going to need to find that cookie and than find that

(54)

EXAMPLE

• We will go above the HTML and make sure the session start commands.

• <?php

// this command is going to say, PHP go to their

browser. Get the ID number for this session cookie. Come back find the file. Open it up, so we can use it.

session_start();

?>

<html> ……

(55)

HEADERS & PAGE REDIRECTION

• Whenever a server make a request to a PHP page, Before the server response to user browser’s request the HTML. It is

going to construct a set of headers. This is send these headers along to their web

page first.

(56)

• There are high level types of header commands we can get.

header( header information );

• Example:

header(“Content-type: application/pdf”);

header(“Content-type: application/vnd.ms-excel; name=‘excel’”);

(57)

• We going to sent PDF, say content type coming going to be a PDF to tell the

browser to take appropriate steps for pdf.

• For excel file, we will use second

(58)

• Because headers are very first thing is being sent. We want to make any

manipulation to headers whatsoever. It has to occur before anything else.

Remember we are telling their browser,

here is coming down to pipe. Get ready for it and then we send it. So we need to have headers at very beginning.

(59)

• <?php

// this is how you return 404 error

header(“HTTP/1.0 404 Not Found”);

exit;

?>

<html> …

(60)

EXAMPLE

• <?php

// this is how you redirect a page

header(“Location: basic.html”);

exit;

?>

<html> …

(61)

INCLUDE

• Through include feature you may include another PHP file in our PHP.

(62)

EXAMPLE

• Includes.php

<?php

include(“included_func.php”);

?>

• Included_func.php

(63)

EXAMPLE

• Includes.php

<?php

include(“included_func.php”);

?>

<?php hello(“Everyone”); ?>

• Included_func.php <?php

function hello($name) { echo “Hello {$name}!”; }

(64)

• We can develop a one file which includes all of our functions. Or all of our functions which is related to certain types. E.g. functions related to filling of forms. Or functions related to

retrieving information from session variables.

• Included files includes another files.

• This is how we able to structure our code such a way, we don’t have to added the hello

(65)

• Now there is variation in include, there is also be using REQUIRE.

• <?php

require(“included_func.php”);

?>

(66)

• We can handle with require whenever

something like functions that is definitely going to be required. And use include whenever we are loading HTML or something that’s not

absolutely essential.

• There is one last variation in include and require, which is require_once.

• <?php

References

Related documents

If the delivery of your baggage has been delayed, please approach the Baggage Assistance Counter located at the arrival area and file a report for your missing baggage. We transform

All of our plans offer the essential health benefits required by the Affordable Care Act (ACA), including preventive care services without a copayment, brand-name and

 مسب هللا نمحرلا ميحرلا   لقو اولمعأ ىريسف هللا مكلمع هلوسرو نونمؤملاو  قدص هللا ميظعلا ةداسلا لضافلا … / ىندعسي ىنفرشيو نأ مدقأ اذه لمعلا عضاوتملا …

Chitosan may offer some benefi t in this area as a nutraceutical food or supplement with the potential to help reduce total cholesterol levels and body weight.. 6.4.7.1.1

Since PHP variables can receive input values from HTML forms, we’ll also review how to create and use HTML form elements (such as checklists, radio boxes, text boxes, and submit

Weaker than expected economic data tends to send bond prices up and interest rates down, while positive data points to lower bond prices and rising loan

real gross domestic product, a well known case study in the application of the HP filter, illustrating how the estimates of the cycle de- pend on the time series model adapted to

The Motor Vehicle Insurance PDS is available by calling 1300 654 166 and should be considered before deciding if the product is right for you.... Building &amp; Contents