Php workshop
-
Upload
gautam-kumar -
Category
Education
-
view
11.539 -
download
0
description
Transcript of Php workshop
By K.Gautam
Client Server Architecture
Client Server Architecture
Server Side Scripting
• Server-side scripting is a Web server technology
• Generates Dynamic Web Pages• Practically invisible to end-user
Server Vs Client side Scripting
WEB Application
WEB Application
• An Application accessed over a network.• Runs inside a Web Browser
What is PHP?
• PHP is a web development language
• PHP: Hypertext Preprocessor• PHP6 • Created by Rasmus Lerdorf in
1995
Why PHP?
• Open Source• Free• Very Good set of built-in functions• Very Good Database support• Great support Community• Large number of Frameworks
Getting Started with PHP
Basic PHP Program
<HTML><HEAD><TITLE>My first PHP program</TITLE></HEAD><BODY><?php
print("Hello, World<BR />\n");phpinfo();
?></BODY></HTML>
Index.php
Including files
• Separate Client and Server code <?phpinclude('/filepath/filename')require('/filepath/filename') include_once('/filepath/filename')require_once('/filepath/filename') ?>
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
PHP Is Forgiving
• Focuses on convenience for the programmer• Doesn’t focus that much on correctness
HTML Is Not PHP
• PHP Syntax applies only within
• PHP should not be confused with HTML
<?php
?>
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
?>
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
PHP’s Syntax Is C-Like
• PHP is sometimes case sensitive• <?php
HELLO();function hello(){
PrINT("hello"); }?>
• Output: hello
PHP’s Syntax Is C-Like
• Statements are expressions terminated by semicolons<?php$greeting = "Welcome to PHP!";?>
Expressions and types
• $value = 2 + 2 * "nonsense" + TRUE ; • Output : 3
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>"); }?>
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. ?>
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.
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
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
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
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
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.'
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).
Outputting
• Echo and print– Basic constructs of the PHP language
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!");
• 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
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).
PHP Control Structures and Functions
• Topics – Boolean Expressions– Branching– Looping– Terminating Execution– Using Functions
Boolean Expressions
• Boolean constantsif (TRUE) print("This will always print<BR>");else print("This will never print<BR>");
Logical operators
Comparison operators
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>"); }
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;
}
Looping
• While$count = 1;while ($count <= 10) { print("count is $count<BR>"); $count = $count + 1; }
Looping
• Do-while$count = 45;do { print("count is $count<BR>"); $count = $count + 1; } while ($count <= 10);
Looping
• For$limit=5;for ($count = 0; $count < $limit;
$count = $count + 1) print "hello <br>";
Using Functions
function function-name ($argument-1, $argument-2, ..){ statement-1; statement-2; ...}
Functions
<?php
sayhello("Welcome To PHP");
function sayhello($hello_string){print $hello_string;
}?>
Functions with return-values<?php
$sum=add(5,3);echo "5+3=",$sum;
function add($a,$b){
return $a+$b;}
?>
HTTP Requests
• HTTP Is Stateless• GET Arguments• POST Arguments
GET Request
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>
GET Request
GET Request
<?php
echo "Hello " , $_GET['Name'];echo '<br>';echo 'from ' , $_GET['College'];
?>
POST Request
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>
POST Request
POST Request
<?php
echo "Hello " , $_POST['Name'];echo '<br>';echo 'from ' , $_POST['College'];
?>
mySQL Database Connectivity
<?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>';
}?>
PHP File Handling
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>
PHP File Handling
<?php
$file=fopen("welcome.txt","a+");$name=$_POST['name'];fwrite($file,$name.'');header("location:fileform.php");
?>
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';
PHP Arrays
$fruit_basket = array(0 => 'apple', 1 => 'orange', 2 => 'banana', 3 => 'pear');
$fruit_basket = array('red' => 'apple', 'orange' => 'orange‘, 'yellow' => 'banana',
'green' => 'pear');
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'));
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] = '';
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>';}
}?>
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>
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.
Working with Sessions
Session.php<?phpsession_start();if(! isset($_SESSION['username'] )){header('location:login.php');}echo 'Hello ' . $_SESSION['username'];session_destroy();?>
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");?>
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");?>
Cookies
Cookie.php<?phpif(! isset($_COOKIE['username'] )){header('location:login.php');}echo 'Hello ' . $_COOKIE['username'];setcookie('username','' );?>
A simple web applicationDatabase Schema
Index.php
<?php session_start();if (!isset($_SESSION['uid']))
header('location:login.html');else
header('location:main.php');?>
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>
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');?>
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>
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');?>
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>
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>';
}?>
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'); ?>
Logout.php
<?php session_start();session_destroy();header('location:index.php');?>
bibliography
• PHP6 and MySQL bible by Steve Suehring, Tim Converse, and Joyce Park
• W3schools.com• Php.net
Presentation
• This presentation is available online at http://j.mp/ki0GlO