php workshop

89
By K.Gautam

Upload: gautam-kumar

Post on 14-Dec-2014

11.539 views

Category:

Education


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Php workshop

By K.Gautam

Page 2: Php workshop

Client Server Architecture

Page 3: Php workshop

Client Server Architecture

Page 4: Php workshop

Server Side Scripting

• Server-side scripting is a Web server technology

• Generates Dynamic Web Pages• Practically invisible to end-user

Page 5: Php workshop

Server Vs Client side Scripting

Page 6: Php workshop
Page 7: Php workshop

WEB Application

Page 8: Php workshop

WEB Application

• An Application accessed over a network.• Runs inside a Web Browser

Page 9: Php workshop

What is PHP?

• PHP is a web development language

• PHP: Hypertext Preprocessor• PHP6 • Created by Rasmus Lerdorf in

1995

Page 10: Php workshop

Why PHP?

• Open Source• Free• Very Good set of built-in functions• Very Good Database support• Great support Community• Large number of Frameworks

Page 11: Php workshop

Getting Started with PHP

Page 12: Php workshop

Basic PHP Program

<HTML><HEAD><TITLE>My first PHP program</TITLE></HEAD><BODY><?php

print("Hello, World<BR />\n");phpinfo();

?></BODY></HTML>

Index.php

Page 13: Php workshop

Including files

• Separate Client and Server code <?phpinclude('/filepath/filename')require('/filepath/filename') include_once('/filepath/filename')require_once('/filepath/filename') ?>

Page 14: Php workshop

PHP SYNTAX

• PHP Is Forgiving• HTML Is Not PHP• PHP’s Syntax Is C-Like– PHP is whitespace insensitive– PHP is sometimes case sensitive– Statements are expressions terminated by

semicolons• Braces make blocks

Page 15: Php workshop

PHP Is Forgiving

• Focuses on convenience for the programmer• Doesn’t focus that much on correctness

Page 16: Php workshop

HTML Is Not PHP

• PHP Syntax applies only within

• PHP should not be confused with HTML

<?php

?>

Page 17: Php workshop

PHP’s Syntax Is C-Like

• PHP is whitespace insensitive<?php

$four = 2 + 2; // single spaces$four = 2 + 2 ; // spaces and tabs$four =2+2; // multiple lines

?>

Page 18: Php workshop

PHP’s Syntax Is C-Like

• PHP is sometimes case sensitive<?php $capital = 67; print("Variable capital is $capital<BR>");

print("Variable CaPiTaL is $CaPiTaL<BR>");?>

OUTPUT :Variable capital is 67

Notice: Undefined variable: CaPiTaL in D:\xampp\htdocs\php\index.php on line 5Variable CaPiTaL is

Page 19: Php workshop

PHP’s Syntax Is C-Like

• PHP is sometimes case sensitive• <?php

HELLO();function hello(){

PrINT("hello"); }?>

• Output: hello

Page 20: Php workshop

PHP’s Syntax Is C-Like

• Statements are expressions terminated by semicolons<?php$greeting = "Welcome to PHP!";?>

Page 21: Php workshop

Expressions and types

• $value = 2 + 2 * "nonsense" + TRUE ; • Output : 3

Page 22: Php workshop

Braces make blocks

<?php if (3 == 2 + 1) print("Good Morning have a nice day<BR>");if (3 == 2 + 1) { print("Good Morning "); print("have a nice day<BR>"); }?>

Page 23: Php workshop

Comments

<?php /* This is a comment in PHP */

# This is a comment, andNot a Comment # this is the second line of the comment Not a Comment// This is a comment too. ?>

Page 24: Php workshop

Variables

• All variables in PHP are denoted with a leading dollar sign ($).

• The value of a variable is the value of its most recent assignment.

• Variables are assigned with the = operator, with the variable on the

left-hand side and the expression to be evaluated on the right.

• Variables can, but do not need, to be declared before assignment.

• Variables have no intrinsic type other than the type of their current

value.

• Variables used before they are assigned have default values.

Page 25: Php workshop

Variables

• PHP variables are Perl-like• All variables in PHP start with a leading $ sign• Variable names must be composed of– letters (uppercase or lowercase)– digits (0–9)– underscore characters ( _ )

• The first character after the $ may not be a number

Page 26: Php workshop

Variables

• Declaring variables (or not)• Assigning variables– $pi = 3 + 0.14159; // Double– $pi = "3 + 0.14159"; // String

• Reassigning variables– $my_num_var = "This should be a number – hope it’s reassigned";– $my_num_var = 5;

• Unassigned variables

Page 27: Php workshop

Variable scope• You can switch modes if you want<HTML><HEAD><?php $username = "Jane Q. User";?></HEAD><BODY><?php print("$username<BR>");?></BODY></HTML>Output :Jane Q. User

Page 28: Php workshop

Types in PHP: Don’t Worry, Be Happy

• No variable type declarations– $first_number = 55.5;– $second_number = "Not a number at all";

• Automatic type conversion– $pi = 3 + 0.14159;

• Types assigned by context– print( substr(12345, 1, 2) );– Output : 23

Page 29: Php workshop

Type Summary

• Integers are whole numbers, without a decimal point, like 495.

• Doubles are floating-point numbers, like 3.14159 or 49.0.

• Booleans have only two possible values: TRUE and FALSE.

• NULL is a special type that only has one value: NULL .• Strings are sequences of characters, like

'PHP 4.0 supports string operations.'

Page 30: Php workshop

Type Summary

• Arrays are named and indexed collections of other values.

• Objects are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.

• Resources are special variables that hold references to resources external to PHP (such as database connections).

Page 31: Php workshop

Outputting

• Echo and print– Basic constructs of the PHP language

Page 32: Php workshop

Echo

• echo "This will print in the user’s browser window.";

• echo ("This will print in the user’s browser window.");

• Both are equivalent.

• Multiple parameters can be used• echo "This will print in the ", "user’s browser

window.";• But not like this• echo ("This will produce a ", "PARSE ERROR!");

Page 33: Php workshop

Print

• The command print is very similar to echo, with two important differences:– Unlike echo , print can accept only one

argument.– Unlike echo , print returns a value, which

represents whether or not the print statement succeeded.

• print("3.14159"); // print a string• print(3.14159); // print a number

Page 34: Php workshop

Variables and strings

$animal = "antelope";$animal_heads = 1;$animal_legs = 4;print("The $animal has $animal_heads

head(s).<BR>");print("The $animal has $animal_legs

leg(s).<BR>");

OutputThe antelope has 1 head(s).The antelope has 4 leg(s).

Page 35: Php workshop

PHP Control Structures and Functions

• Topics – Boolean Expressions– Branching– Looping– Terminating Execution– Using Functions

Page 36: Php workshop

Boolean Expressions

• Boolean constantsif (TRUE) print("This will always print<BR>");else print("This will never print<BR>");

Page 37: Php workshop

Logical operators

Page 38: Php workshop

Comparison operators

Page 39: Php workshop

Branching

• If-else if ($first > $second) { $difference = $first - $second; print("The difference is $difference<BR>"); } else { $difference = $second - $first; print("The difference is $difference<BR>"); }

Page 40: Php workshop

Branching• Switch$day=5;switch($day){

case 1:echo "Sunday" ; break;case 2:echo "Monday" ; break;case 3:echo "Tuesday" ; break;case 4:echo "Wednesday" ; break;case 5:echo "Thursday" ; break;case 6:echo "Friday" ; break;case 7:echo "Saturday" ; break;default :echo "Not a day" ; break;

}

Page 41: Php workshop

Looping

• While$count = 1;while ($count <= 10) { print("count is $count<BR>"); $count = $count + 1; }

Page 42: Php workshop

Looping

• Do-while$count = 45;do { print("count is $count<BR>"); $count = $count + 1; } while ($count <= 10);

Page 43: Php workshop

Looping

• For$limit=5;for ($count = 0; $count < $limit;

$count = $count + 1) print "hello <br>";

Page 44: Php workshop

Using Functions

function function-name ($argument-1, $argument-2, ..){ statement-1; statement-2; ...}

Page 45: Php workshop

Functions

<?php

sayhello("Welcome To PHP");

function sayhello($hello_string){print $hello_string;

}?>

Page 46: Php workshop

Functions with return-values<?php

$sum=add(5,3);echo "5+3=",$sum;

function add($a,$b){

return $a+$b;}

?>

Page 47: Php workshop

HTTP Requests

• HTTP Is Stateless• GET Arguments• POST Arguments

Page 48: Php workshop

GET Request

Page 49: Php workshop

GET Request<html>

<head><title>Http Get Request </title>

</head><body>

<form method="GET" action="get.php" >Name:<input type="text" name="Name" /><br>College : <input type="text" name="College" /> <br><input type="submit" /></form>

</body></html>

Page 50: Php workshop

GET Request

Page 51: Php workshop

GET Request

<?php

echo "Hello " , $_GET['Name'];echo '<br>';echo 'from ' , $_GET['College'];

?>

Page 52: Php workshop

POST Request

Page 53: Php workshop

POST Request<html>

<head><title>Http Get Request </title>

</head><body>

<form method="POST" action="get.php" >Name:<input type="text" name="Name" /><br>College : <input type="text" name="College" /> <br><input type="submit" /></form>

</body></html>

Page 54: Php workshop

POST Request

Page 55: Php workshop

POST Request

<?php

echo "Hello " , $_POST['Name'];echo '<br>';echo 'from ' , $_POST['College'];

?>

Page 56: Php workshop

mySQL Database Connectivity

Page 57: Php workshop
Page 58: Php workshop
Page 59: Php workshop
Page 60: Php workshop
Page 61: Php workshop
Page 62: Php workshop

<?php$db_username="phpuser";$db_password="phppassword";$db="phpdb";$db_host="localhost";$db_table="login";$conn=mysql_connect($db_host,$db_username,$db_password) or

die(mysql_error());mysql_select_db($db);$query="Select * from $db_table";$result=mysql_query($query,$conn);while ($array=mysql_fetch_array($result)){

for($i=0;$i<3;$i++){

echo $array[$i].' ' ;}echo '<br>';

}?>

Page 63: Php workshop

PHP File Handling

Page 64: Php workshop

PHP File HandlingFileForm.php<html><body><form method="POST" action="file.php">Name:<input type="text" name="name" /></form>Names : <br><?php$file=fopen("welcome.txt","r+");while (! feof( $file ) ){

echo fgets($file) .'<br>';}?></body></html>

Page 65: Php workshop

PHP File Handling

<?php

$file=fopen("welcome.txt","a+");$name=$_POST['name'];fwrite($file,$name.'');header("location:fileform.php");

?>

Page 66: Php workshop

PHP Arrays

• Creating Arrays• $fruit_basket = array('apple', 'orange', 'banana', 'pear');• OR• $fruit_basket[0] = 'apple';• $fruit_basket[1] = 'orange';• $fruit_basket[] = 'banana';• $fruit_basket[] = 'pear';

Page 67: Php workshop

PHP Arrays

$fruit_basket = array(0 => 'apple', 1 => 'orange', 2 => 'banana', 3 => 'pear');

$fruit_basket = array('red' => 'apple', 'orange' => 'orange‘, 'yellow' => 'banana',

'green' => 'pear');

Page 68: Php workshop

PHP Arrays• echo $fruit_basket['yellow'] ;

• Multidimensional Arrays$cornucopia = array('fruit' => array('red' => 'apple', 'orange' => 'orange', 'yellow' => 'banana', 'green' => 'pear'), 'flower' => array('red' => 'rose', 'yellow' => 'sunflower', 'purple' => 'iris'));

Page 69: Php workshop

PHP Arrays Deleting

• Deleting from Arrays$my_array[0] = 'wanted';$my_array[1] = 'unwanted';$my_array[2] = 'wanted again';unset($my_array[1]);

Unset is not the same as

$my_array[1] = '';

Page 70: Php workshop

PHP Arrays Iteration<?php$cornucopia = array('fruit' => array('red' => 'apple', 'orange' => 'orange', 'yellow' => 'banana', 'green' => 'pear'), 'flower' => array('red' => 'rose', 'yellow' => 'sunflower', 'purple' => 'iris'));foreach( $cornucopia as $cor ){

foreach($cor as $c){

echo $c.'<br>';}

}?>

Page 71: Php workshop

Randomness<html><head><?php$hex=array('a','b','c','d','e','f',1,2,3,4,5,6,7,8,9,0);$color='';for($i=0;$i<6;$i++){

$random=mt_rand(0,sizeof($hex)-1);$color=$color.$hex[$random];

}

?><style>

body{

background-color:<?php echo $color; ?>;}

</style></head></html>

Page 72: Php workshop

Session

• A PHP session variable is used to store information about, or change settings for a user session.

• Session variables hold information about one single user, and are available to all pages in one application.

Page 73: Php workshop

Working with Sessions

Session.php<?phpsession_start();if(! isset($_SESSION['username'] )){header('location:login.php');}echo 'Hello ' . $_SESSION['username'];session_destroy();?>

Page 74: Php workshop

SessionsLogin.php<?phpif(!isset($_POST['uname'])){

echo "<form method='POST' action='' >username:<input type='text' name='uname' /></form>";

exit();}session_start();$uname=$_POST['uname'];$_SESSION['username']=$uname;header("location:session.php");?>

Page 75: Php workshop

CookiesLogin.php<?phpif(!isset($_POST['uname'])){

echo "<form method='POST' action='' >username:<input type='text' name='uname' /></form>";exit();

}$uname=$_POST['uname'];setcookie('username',$uname );header("location:cookie.php");?>

Page 76: Php workshop

Cookies

Cookie.php<?phpif(! isset($_COOKIE['username'] )){header('location:login.php');}echo 'Hello ' . $_COOKIE['username'];setcookie('username','' );?>

Page 77: Php workshop

A simple web applicationDatabase Schema

Page 78: Php workshop

Index.php

<?php session_start();if (!isset($_SESSION['uid']))

header('location:login.html');else

header('location:main.php');?>

Page 79: Php workshop

Login.html

<h1>Login</h1><form method="POST"

action="login.php" >Username:<input type="text"

name="USERNAME" /><br>Password:<input type="password"

name="PASSWORD" /><br><input type="submit"

value="login" /></form><br><a

href="register.html">Register</a>

Page 80: Php workshop

Login.php

<?php$conn=mysql_connect('localhost','phpuser','phppassword') or

die(mysql_error());mysql_select_db('userdata')or die(mysql_error());$username=$_POST['USERNAME'];$password=$_POST['PASSWORD'];$password=sha1($password);$result=mysql_query("Select * from login where

username='$username' and password='$password' ;", $conn)or die(mysql_error()) ;

if(!mysql_num_rows($result)){

echo "Invalid Username / Password<br>Please go back !";exit();

}$row=mysql_fetch_array($result) or die(mysql_error());session_start();$_SESSION['uid']=$row['uid'];$_SESSION['username']=$row['username'];header('location:main.php');?>

Page 81: Php workshop

Register.html

<h1>Register</h1><form method="POST"

action="register.php" >Username:<input type="text"

name="USERNAME" /><br>Password:<input type="password"

name="PASSWORD" /><br><input type="submit" value=“register" /></form><br><a href="login.html">Login</a>

Page 82: Php workshop

Register.php

<?phpsession_start();session_destroy();$conn=mysql_connect('localhost','phpuser','phppassword') or

die(mysql_error());mysql_select_db('userdata')or die(mysql_error());$username=$_POST['USERNAME'];$password=$_POST['PASSWORD'];$password=sha1($password);$result=mysql_query("Select * from login where

username='$username' ;", $conn)or die(mysql_error()) ;if(mysql_num_rows($result)){

echo "Username Already in use <br>Please go back !";exit();

}mysql_query("Insert into login

values(null,'$username','$password');",$conn)or die(mysql_error());

header('location:login.html');?>

Page 83: Php workshop

Main.php

<?php session_start();if (!isset($_SESSION['uid']))

header('location:login.html');?>

<h1>Main page</h1><h2>Hello <?php echo $_SESSION['username']; ?

></h2><h3><a href="logout.php" >Logout</a></h3><form action="add.php" method="POST" > Data :<input type="text" name="data" /><input

type="submit" value="Add Data" /> </form> <h3>Your Data:</h3>

Page 84: Php workshop

Main.php

<?php$conn=mysql_connect('localhost','phpuser','phppassword') or die(mysql_error());mysql_select_db('userdata')or die(mysql_error());$result=mysql_query("select * from data where uid=".$_SESSION['uid']." ;",$conn);if(!mysql_num_rows($result))

exit();echo 'Did uid data<br>';while($row=mysql_fetch_array($result)){

for($i=0;$i<3;$i++){

echo $row[$i].' ' ;}echo '<br>';

}?>

Page 85: Php workshop

Add.php

<?php session_start();if (!isset($_SESSION['uid']))

header('location:login.html');$conn=mysql_connect('localhost','phpuser','phppassword') or

die(mysql_error());mysql_select_db('userdata')or die(mysql_error());if(!isset($_POST['data']))

header('location:main.php');$uid=$_SESSION['uid'];$data=$_POST['data'];mysql_query("insert into data values(null,$uid,'$data');",$conn);

header('location:main.php'); ?>

Page 86: Php workshop

Logout.php

<?php session_start();session_destroy();header('location:index.php');?>

Page 87: Php workshop

bibliography

• PHP6 and MySQL bible by Steve Suehring, Tim Converse, and Joyce Park

• W3schools.com• Php.net

Page 88: Php workshop

Presentation

• This presentation is available online at http://j.mp/ki0GlO

Page 89: Php workshop