SlideShare ist ein Scribd-Unternehmen logo
1 von 43
SURENDERA GROUP OFSURENDERA GROUP OF
INSTITUTIONINSTITUTION
SUBMIT TO :- SUBMITTED BY :-
ER. NITIN BHAKAR ASHWIN SINGH
TAJENDER KUMAR
MEENU SHEELA
GoalGoal
• Not to teach everything about PHP, but provide the basic
knowledge
• Explain code of examples
• Provide some useful references
PHP Basics:
Introduction to PHP
• a PHP file, PHP workings, running PHP.
 Basic PHP syntax
• variables, operators, if...else...and switch, while, do while, and
for.
 Some useful PHP functions
 How to work with
• HTML forms, cookies, files, time and date.
 How to create a basic checker for user-entered data
Server-Side Dynamic Web Programming
• CGI is one of the most common approaches to server-side
programming
 Universal support: (almost) Every server supports CGI programming. A great
deal of ready-to-use CGI code. Most APIs (Application Programming Interfaces)
also allow CGI programming.
 Choice of languages: CGI is extremely general, so that programs may be written
in nearly any language. Perl is by far the most popular, with the result that many
people think that CGI means Perl. But C, C++, Ruby, and Python are also used
for CGI programming.
 Drawbacks: A separate process is run every time the script is requested. A
distinction is made between HTML pages and code.
• Other server-side alternatives try to avoid the drawbacks
 Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated
on the server while the pages are being served. Add dynamically generated
content to an existing HTML page, without having to serve the entire page via a
CGI program.
 Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the
web server so it does not require an additional process. It allows programmers to
mix code within HTML pages instead of writing separate programs.
(Drawback(?) Must be run on a server using Microsoft server software.)
 Java Servlets (Sun): As CGI scripts, they are code that creates documents.
These must be compiled as classes which are dynamically loaded by the web
server when they are run.
 Java Server Pages (JSP): Like ASP, another technology that allows developers
to embed Java in web pages.
What do You Need?
• Our server supports PHP
• You don't need to do anything special! *
• You don't need to compile anything or install any extra
tools!
• Create some .php files in your web directory - and the
server will parse them for you.
* Slightly different rules apply when dealing with an
SQL database (as will be explained when we get to that
point).
What is PHP?What is PHP?
• PHP == ‘Hypertext Preprocessor’
• Open-source, server-side scripting language
• Used to generate dynamic web-pages
• PHP scripts reside between reserved PHP tags
• This allows the programmer to embed PHP scripts within HTML
pages
• The acronym PHP means (in a slightly recursive definition)
 PHP: Hypertext Preprocessor
What is PHP (cont’d)What is PHP (cont’d)
• Interpreted language, scripts are parsed at run-time
rather than compiled beforehand
• Executed on the server-side
• Source-code not visible by client
• ‘View Source’ in browsers does not display the PHP code
• Various built-in functions allow for fast development
• Compatible with many popular databases
What does PHP code lookWhat does PHP code look
like?like?
• Structurally similar to C/C++
• Supports procedural and object-oriented paradigm (to
some degree)
• All PHP statements end with a semi-colon
• Each PHP script must be enclosed in the reserved PHP
tag
<?php
…
?>
Comments in PHPComments in PHP
• Standard C, C++, and shell comment symbols
// C++ and Java-style comment
# Shell-style comments
/* C-style comments
These can span multiple lines */
Variables in PHPVariables in PHP
• PHP variables must begin with a “$” sign
• Case-sensitive ($Foo != $foo != $fOo)
• Global and locally-scoped variables
• Global variables can be used anywhere
• Local variables restricted to a function or class
• Certain variable names reserved by PHP
• Form variables ($_POST, $_GET)
• Server variables ($_SERVER)
• Etc.
Constants
A constant is an identifier (name) for a simple value. A constant is case-sensitive by
default. By convention, constant identifiers are always uppercase.
<?php
// Valid constant names
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");
// Invalid constant names (they shouldn’t start
// with a number!)
define("2FOO", "something");
// This is valid, but should be avoided:
// PHP may one day provide a “magical” constant
// that will break your script
define("__FOO__", "something");
?>
You can access
constants
anywhere in your
script without
regard to scope.
Operators
• Arithmetic Operators: +, -, *,/ , %, ++, --
• Assignment Operators: =, +=, -=, *=, /=, %=
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• String Operators: . and .= (for string concatenation)
Example Is the same as
x+=y x=x+y
x-=y x=x-y
x*=y x=x*y
x/=y x=x/y
x%=y x=x%y
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!";
Variable usageVariable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
$foo = ($foo * 7); // Multiplies foo by 7
$bar = ($bar * 7); // Invalid expression
?>
Basic PHP syntax
A PHP scripting block always starts with <?php and ends with ?>. A PHP
scripting block can be placed (almost) anywhere in an HTML document.
<html>
<!-- hello.php -->
<head><title>Hello World</title></head>
<body>
<p>This is going to be ignored by the PHP interpreter.</p>
<?php echo ‘<p>While this is going to be parsed.</p>‘; ?>
<p>This will also be ignored by the PHP preprocessor.</p>
<?php print(‘<p>Hello and welcome to <i>my</i> page!</p>');
?>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
The server executes the print and echo statements, substitutes output.
print and echo
for output
a semicolon
(;) at the end of
each statement
// for a single-line
comment
/* and */ for a large
comment block.
Scalars
All variables in PHP start with a $ sign symbol. A variable's type is determined by the
context in which that variable is used (i.e. there is no strong-typing in PHP).
<html><head></head>
<!-- scalars.php -->
<body> <p>
<?php
$foo = true; if ($foo) echo "It is TRUE! <br /> n";
$txt='1234'; echo "$txt <br /> n";
$a = 1234; echo "$a <br /> n";
$a = -123;
echo "$a <br /> n";
$a = 1.234;
echo "$a <br /> n";
$a = 1.2e3;
echo "$a <br /> n";
$a = 7E-10;
echo "$a <br /> n";
echo 'Arnold once said: "I'll be back"', "<br /> n";
$beer = 'Heineken';
echo "$beer's taste is great <br /> n";
$str = <<<EOD
Example of string
spanning multiple lines
using “heredoc” syntax.
EOD;
echo $str;
?>
</p>
</body>
</html>
Four scalar
types:
boolean
true or false
integer,
float,
floating point
numbers
string
single quoted
double quoted
EchoEcho
• The PHP command ‘echo’ is used to output the
parameters passed to it
• The typical usage for this is to send data to the client’s
web-browser
• Syntax
• void echo (string arg1 [, string argn...])
• In practice, arguments are not passed in parentheses
since echo is a language construct rather than an
actual function
Echo exampleEcho example
• Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
• Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
• This is true for both variables and character escape-sequences (such as “n” or “”)
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
Arithmetic OperationsArithmetic Operations
• $a - $b // subtraction
• $a * $b // multiplication
• $a / $b // division
• $a += 5 // $a = $a+5 Also works for *= and /=
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>
ConcatenationConcatenation
• Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” .
$string2;
Print $string3;
?>
Hello PHP
Escaping the CharacterEscaping the Character
• If the string has a set of double quotation marks that must
remain visible, use the  [backslash] before the quotation
marks to ignore and display them.
<?php
$heading=“”Computer Science””;
Print $heading;
?>
“Computer Science”
PHP Control StructuresPHP Control Structures
 Control Structures: Are the structures within a language that
allow us to control the flow of execution through a program or
script.
 Grouped into conditional (branching) structures (e.g. if/else)
and repetition structures (e.g. while loops).
 Example if/else if/else statement:
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}
If ... Else...If ... Else...
• If (condition)
{
Statements;
}
Else
{
Statement;
}
<?php
If($user==“John”)
{
Print “Hello John.”;
}
Else
{
Print “You are not John.”;
}
?>
No THEN in PHP
Conditionals: if elseCan execute a set of code depending on a condition
<html><head></head>
<!-- if-cond.php -->
<body>
<?php
$d=date("D");
echo $d, “<br/>”;
if ($d=="Fri")
echo "Have a nice weekend! <br/>";
else
echo "Have a nice day! <br/>";
$x=10;
if ($x==10)
{
echo "Hello<br />";
echo "Good morning<br />";
}
?>
</body>
</html>
if (condition)
code to be executed if condition
is true;
else
code to be executed if condition
is false;
date() is a built-in PHP function that
can be called with many different
parameters to return the date
(and/or local time) in various formats
In this case we get a three letter
string for the day of the week.
While LoopsWhile Loops
• While (condition)
{
Statements;
}
<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>
hello PHP. hello PHP. hello PHP.
Looping: for and foreach
Can loop depending on a "counter"
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
loops through a block of code a
specified number of times
<?php
$a_array = array(1, 2, 3, 4);
foreach ($a_array as $value)
{
$value = $value * 2;
echo “$value <br/> n”;
}
?>
loops through a block of code for each
element in an array
<?php
$a_array=array("a","b","c");
foreach ($a_array as $key => $value)
{
echo $key." = ".$value."n";
}
?>
Conditionals: switch
Can select one of many sets of lines to execute
<html><head></head>
<body>
<!–- switch-cond.php -->
<?php
$x = rand(1,5); // random integer
echo “x = $x <br/><br/>”;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
break;
}
?>
</body>
</html>
switch (expression)
{
case label1:
code to be executed if
expression = label1;
break;
case label2:
code to be executed if
expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
break;
}
Date DisplayDate Display
$datedisplay=date(“yyyy/m/d”);
Print $datedisplay;
# If the date is June 25th, 2012
# It would display as 2012/25/6
2012/25/6
$datedisplay=date(“l, F m, Y”);
Print $datedisplay;
# If the date is June 25th
,2012
# Monday, June 25th
,2012
Monday, June 25, 2012
Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys.
array() = creates arrays<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
key = either an integer or a
string.
value = any PHP type.
<?php
array(5 => 43, 32, 56, "b" => 12);
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
if no key given (as in example), the
PHP interpreter uses (maximum of the
integer indices + 1).
if an existing key, its value will be
overwritten.
<?php
$arr = array(5 => 1, 12 => 2);
foreach ($arr as $key => $value) { echo $key, ‘=>’,
$value); }
$arr[] = 56; // the same as $arr[13] = 56;
$arr["x"] = 42; // adds a new element
unset($arr[5]); // removes the element
unset($arr); // deletes the whole array
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
$b = array_values($a);
?>
can set values in an
array
unset() removes a
key/value pair
array_values() makes
reindexing effect (indexing
numerically)
Month, Day & Date Format SymbolsMonth, Day & Date Format Symbols
M Jan
F January
m 01
n 1
Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon
FunctionsFunctions
• Functions MUST be defined before then can be called
• Function headers are of the format
• Note that no return type is specified
• Unlike variables, function names are not case sensitive
(foo(…) == Foo(…) == FoO(…))
function functionName($arg_1, $arg_2, …, $arg_n)
Functions exampleFunctions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
$result_1 = foo(12, 3); // Store the function
echo $result_1; // Outputs 36
echo foo(12, 3); // Outputs 36
?>
User Defined Functions
Can define a function using syntax such as the following:
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.n";
return $retval;
}
?>
Can also define conditional
functions, functions within
functions, and recursive
functions.
<?php
function square($num)
{
return $num * $num;
}
echo square(4);
?>
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
echo $zero, $one, $two;
?>
Can return a value of any type
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));
?>
Variable Scope
The scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */
function Test()
{
echo $a;
/* reference to local scope variable */
}
Test();
?>
The scope is local within functions,
and hence the value of $a is
undefined in the “echo” statement.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
global
refers to its
global
version.
<?php
function Test()
{
static $a = 0;
echo $a;
$a++;
}
Test1();
Test1();
Test1();
?>
static
does not lose
its value.
Including Files
The include() statement includes and evaluates the specified file.
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
*The scope of variables in “included” files depends on where the “include” file is added!
You can use the include_once, require, and require_once statements in similar ways.
<?php
function foo()
{
global $color;
include ('vars.php‘);
echo "A $color $fruit";
}
/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global. */
foo(); // A green apple
echo "A $color $fruit"; // A green
?>
Include FilesInclude Files
Include “opendb.php”;
Include “closedb.php”;
This inserts files; the code in files will be inserted into current code. This will
provide useful and protective means once you connect to a database, as
well as for other repeated functions.
Include (“footer.php”);
The file footer.php might look like:
<hr SIZE=11 NOSHADE WIDTH=“100%”>
<i>Copyright © 2001-2012 gsu</i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.gsu.edu.edu</i></font><br>
PHP - FormsPHP - Forms
•Access to the HTTP POST and GET data is simple in PHPAccess to the HTTP POST and GET data is simple in PHP
•The global variables $_POST[] and $_GET[] contain theThe global variables $_POST[] and $_GET[] contain the
request datarequest data
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="cancel" value="Cancel">
</form>
WHY PHP – Sessions ?WHY PHP – Sessions ?Whenever you want to create aWhenever you want to create a websitewebsite that allows you to store and displaythat allows you to store and display
information about a user, determine which user groups a person belongs to,information about a user, determine which user groups a person belongs to,
utilize permissions on yourutilize permissions on your websitewebsite or you just want to do something cool onor you just want to do something cool on
your site,your site, PHP's SessionsPHP's Sessions are vital toare vital to eacheach of these features.of these features.
Cookies are about 30% unreliable right now and it's getting worse every day.Cookies are about 30% unreliable right now and it's getting worse every day.
More and more web browsers are starting to come with security and privacyMore and more web browsers are starting to come with security and privacy
settings and people browsing the net these days are starting to frown uponsettings and people browsing the net these days are starting to frown upon
Cookies because they store information on their local computer that they doCookies because they store information on their local computer that they do
not want stored there.not want stored there.
PHP has a great set of functions that can achieve the same results ofPHP has a great set of functions that can achieve the same results of
Cookies and more without storing information on the user's computer. PHPCookies and more without storing information on the user's computer. PHP
Sessions store the information on the web server in a location that you choseSessions store the information on the web server in a location that you chose
in special files. These files are connected to the user's web browser via thein special files. These files are connected to the user's web browser via the
server and a special ID called a "Session ID". This is nearly 99% flawless inserver and a special ID called a "Session ID". This is nearly 99% flawless in
operation and it is virtually invisible to the user.operation and it is virtually invisible to the user.
PHP - SessionsPHP - Sessions
•Sessions store their identifier in a cookie in the client’s browserSessions store their identifier in a cookie in the client’s browser
•Every page that uses session data must be proceeded by theEvery page that uses session data must be proceeded by the
session_start()session_start() functionfunction
•Session variables are then set and retrieved by accessing the globalSession variables are then set and retrieved by accessing the global
$_SESSION[]$_SESSION[]
•Save it asSave it as session.phpsession.php
<?php<?php
session_start();session_start();
if (!$_SESSION["count"])if (!$_SESSION["count"])
$_SESSION["count"] = 0;$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";echo "<h1>".$_SESSION["count"]."</h1>";
?>?>
<a href="session.php?count=yes">Click here to count</a><a href="session.php?count=yes">Click here to count</a>
Avoid Error PHP - SessionsAvoid Error PHP - Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>
Error!
PHP Example: <?php
session_start();
echo "Look at this nasty error below:";
?>
Correct
Warning: Cannot send session cookie - headers already sent
by (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3
Warning: Cannot send session cache limiter - headers
already sent (output started at
session_header_error/session_error.php:2) in
session_header_error/session_error.php on line 3
Destroy PHP - SessionsDestroy PHP - Sessions
Destroying a Session
why it is necessary to destroy a session when the session will get
destroyed when the user closes their browser. Well, imagine that you
had a session registered called "access_granted" and you were using
that to determine if the user was logged into your site based upon a
username and password. Anytime you have a login feature, to make
the users feel better, you should have a logout feature as well. That's
where this cool function called session_destroy() comes in handy.
session_destroy() will completely demolish your session (no, the
computer won't blow up or self destruct) but it just deletes the session
files and clears any trace of that session.
NOTE: If you are using the $_SESSION superglobal array, you must
clear the array values first, then run session_destroy.
Here's how we use session_destroy():
Destroy PHP - SessionsDestroy PHP - Sessions
<?php
// start the session
session_start();
header("Cache-control: private"); //IE 6 Fix
$_SESSION = array();
session_destroy();
echo "<strong>Step 5 - Destroy This Session </strong><br />";
if($_SESSION['name']){
    echo "The session is still active";
} else {
    echo "Ok, the session is no longer active! <br />";
    echo "<a href="page1.php"><< Go Back Step 1</a>";
}
?>
THANK YOU FOR
WATCHING

Weitere ähnliche Inhalte

Was ist angesagt? (20)

PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Php basics
Php basicsPhp basics
Php basics
 
PHP
PHPPHP
PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Introduction to PHP - SDPHP
Introduction to PHP - SDPHPIntroduction to PHP - SDPHP
Introduction to PHP - SDPHP
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
php app development 1
php app development 1php app development 1
php app development 1
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
 

Andere mochten auch

Social Contruction of Gender Paper-Finalized and Edited
Social Contruction of Gender Paper-Finalized and EditedSocial Contruction of Gender Paper-Finalized and Edited
Social Contruction of Gender Paper-Finalized and EditedSavannah Anderson-Bledsoe
 
Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...
Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...
Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...Destination Brocéliande
 
Inauguration of Vision Academy of Professional Studies
Inauguration of Vision Academy of Professional Studies Inauguration of Vision Academy of Professional Studies
Inauguration of Vision Academy of Professional Studies Chathuranga Jayanath
 
principle of management
principle of managementprinciple of management
principle of managementAiza Ali
 
Xarxes socials i infancia
Xarxes socials i infancia Xarxes socials i infancia
Xarxes socials i infancia Imma Marín
 
Experimentem amb la llum
Experimentem amb la llumExperimentem amb la llum
Experimentem amb la llumCarme Mestra
 
curriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigo
curriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigocurriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigo
curriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigoMaría Jesús Martínez Porto
 
Radiological approach for malignant breast lesions
Radiological approach for malignant breast lesionsRadiological approach for malignant breast lesions
Radiological approach for malignant breast lesionsNazia Ashraf
 

Andere mochten auch (17)

Evaluacion breve
Evaluacion breveEvaluacion breve
Evaluacion breve
 
Social Contruction of Gender Paper-Finalized and Edited
Social Contruction of Gender Paper-Finalized and EditedSocial Contruction of Gender Paper-Finalized and Edited
Social Contruction of Gender Paper-Finalized and Edited
 
Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...
Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...
Atelier numérique : Soyez visibles et attractifs sur Google - Niveau confirmé...
 
Amics
AmicsAmics
Amics
 
的确很酷
的确很酷的确很酷
的确很酷
 
Inauguration of Vision Academy of Professional Studies
Inauguration of Vision Academy of Professional Studies Inauguration of Vision Academy of Professional Studies
Inauguration of Vision Academy of Professional Studies
 
principle of management
principle of managementprinciple of management
principle of management
 
Breast bpe
Breast bpe Breast bpe
Breast bpe
 
Artem zhukovets smm_sib_v3
Artem zhukovets smm_sib_v3Artem zhukovets smm_sib_v3
Artem zhukovets smm_sib_v3
 
Xarxes socials i infancia
Xarxes socials i infancia Xarxes socials i infancia
Xarxes socials i infancia
 
Semantic web
Semantic webSemantic web
Semantic web
 
Mis lecturas favoritas 2013
Mis lecturas favoritas 2013Mis lecturas favoritas 2013
Mis lecturas favoritas 2013
 
Experimentem amb la llum
Experimentem amb la llumExperimentem amb la llum
Experimentem amb la llum
 
Mahatma mandir
Mahatma mandirMahatma mandir
Mahatma mandir
 
curriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigo
curriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigocurriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigo
curriculum-maria-jesus-martinez-educadora-infantil-y-musico-vigo
 
Radiological approach for malignant breast lesions
Radiological approach for malignant breast lesionsRadiological approach for malignant breast lesions
Radiological approach for malignant breast lesions
 
5è b bongoh
5è b bongoh5è b bongoh
5è b bongoh
 

Ähnlich wie Prersentation

Ähnlich wie Prersentation (20)

Lecture8
Lecture8Lecture8
Lecture8
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Php
PhpPhp
Php
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
Php unit i
Php unit iPhp unit i
Php unit i
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
Intro to php
Intro to phpIntro to php
Intro to php
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
PHP
PHPPHP
PHP
 
php Chapter 1.pptx
php Chapter 1.pptxphp Chapter 1.pptx
php Chapter 1.pptx
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 

Kürzlich hochgeladen

welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
Crystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxCrystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxachiever3003
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentBharaniDharan195623
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 

Kürzlich hochgeladen (20)

welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
Crystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxCrystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptx
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managament
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 

Prersentation

  • 1. SURENDERA GROUP OFSURENDERA GROUP OF INSTITUTIONINSTITUTION SUBMIT TO :- SUBMITTED BY :- ER. NITIN BHAKAR ASHWIN SINGH TAJENDER KUMAR MEENU SHEELA
  • 2. GoalGoal • Not to teach everything about PHP, but provide the basic knowledge • Explain code of examples • Provide some useful references
  • 3. PHP Basics: Introduction to PHP • a PHP file, PHP workings, running PHP.  Basic PHP syntax • variables, operators, if...else...and switch, while, do while, and for.  Some useful PHP functions  How to work with • HTML forms, cookies, files, time and date.  How to create a basic checker for user-entered data
  • 4. Server-Side Dynamic Web Programming • CGI is one of the most common approaches to server-side programming  Universal support: (almost) Every server supports CGI programming. A great deal of ready-to-use CGI code. Most APIs (Application Programming Interfaces) also allow CGI programming.  Choice of languages: CGI is extremely general, so that programs may be written in nearly any language. Perl is by far the most popular, with the result that many people think that CGI means Perl. But C, C++, Ruby, and Python are also used for CGI programming.  Drawbacks: A separate process is run every time the script is requested. A distinction is made between HTML pages and code.
  • 5. • Other server-side alternatives try to avoid the drawbacks  Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated on the server while the pages are being served. Add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program.  Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web server so it does not require an additional process. It allows programmers to mix code within HTML pages instead of writing separate programs. (Drawback(?) Must be run on a server using Microsoft server software.)  Java Servlets (Sun): As CGI scripts, they are code that creates documents. These must be compiled as classes which are dynamically loaded by the web server when they are run.  Java Server Pages (JSP): Like ASP, another technology that allows developers to embed Java in web pages.
  • 6. What do You Need? • Our server supports PHP • You don't need to do anything special! * • You don't need to compile anything or install any extra tools! • Create some .php files in your web directory - and the server will parse them for you. * Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point).
  • 7. What is PHP?What is PHP? • PHP == ‘Hypertext Preprocessor’ • Open-source, server-side scripting language • Used to generate dynamic web-pages • PHP scripts reside between reserved PHP tags • This allows the programmer to embed PHP scripts within HTML pages • The acronym PHP means (in a slightly recursive definition)  PHP: Hypertext Preprocessor
  • 8. What is PHP (cont’d)What is PHP (cont’d) • Interpreted language, scripts are parsed at run-time rather than compiled beforehand • Executed on the server-side • Source-code not visible by client • ‘View Source’ in browsers does not display the PHP code • Various built-in functions allow for fast development • Compatible with many popular databases
  • 9. What does PHP code lookWhat does PHP code look like?like? • Structurally similar to C/C++ • Supports procedural and object-oriented paradigm (to some degree) • All PHP statements end with a semi-colon • Each PHP script must be enclosed in the reserved PHP tag <?php … ?>
  • 10. Comments in PHPComments in PHP • Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */
  • 11. Variables in PHPVariables in PHP • PHP variables must begin with a “$” sign • Case-sensitive ($Foo != $foo != $fOo) • Global and locally-scoped variables • Global variables can be used anywhere • Local variables restricted to a function or class • Certain variable names reserved by PHP • Form variables ($_POST, $_GET) • Server variables ($_SERVER) • Etc.
  • 12. Constants A constant is an identifier (name) for a simple value. A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. <?php // Valid constant names define("FOO", "something"); define("FOO2", "something else"); define("FOO_BAR", "something more"); // Invalid constant names (they shouldn’t start // with a number!) define("2FOO", "something"); // This is valid, but should be avoided: // PHP may one day provide a “magical” constant // that will break your script define("__FOO__", "something"); ?> You can access constants anywhere in your script without regard to scope.
  • 13. Operators • Arithmetic Operators: +, -, *,/ , %, ++, -- • Assignment Operators: =, +=, -=, *=, /=, %= • Comparison Operators: ==, !=, >, <, >=, <= • Logical Operators: &&, ||, ! • String Operators: . and .= (for string concatenation) Example Is the same as x+=y x=x+y x-=y x=x-y x*=y x=x*y x/=y x=x/y x%=y x=x%y $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!";
  • 14. Variable usageVariable usage <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?>
  • 15. Basic PHP syntax A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed (almost) anywhere in an HTML document. <html> <!-- hello.php --> <head><title>Hello World</title></head> <body> <p>This is going to be ignored by the PHP interpreter.</p> <?php echo ‘<p>While this is going to be parsed.</p>‘; ?> <p>This will also be ignored by the PHP preprocessor.</p> <?php print(‘<p>Hello and welcome to <i>my</i> page!</p>'); ?> <?php //This is a comment /* This is a comment block */ ?> </body> </html> The server executes the print and echo statements, substitutes output. print and echo for output a semicolon (;) at the end of each statement // for a single-line comment /* and */ for a large comment block.
  • 16. Scalars All variables in PHP start with a $ sign symbol. A variable's type is determined by the context in which that variable is used (i.e. there is no strong-typing in PHP). <html><head></head> <!-- scalars.php --> <body> <p> <?php $foo = true; if ($foo) echo "It is TRUE! <br /> n"; $txt='1234'; echo "$txt <br /> n"; $a = 1234; echo "$a <br /> n"; $a = -123; echo "$a <br /> n"; $a = 1.234; echo "$a <br /> n"; $a = 1.2e3; echo "$a <br /> n"; $a = 7E-10; echo "$a <br /> n"; echo 'Arnold once said: "I'll be back"', "<br /> n"; $beer = 'Heineken'; echo "$beer's taste is great <br /> n"; $str = <<<EOD Example of string spanning multiple lines using “heredoc” syntax. EOD; echo $str; ?> </p> </body> </html> Four scalar types: boolean true or false integer, float, floating point numbers string single quoted double quoted
  • 17. EchoEcho • The PHP command ‘echo’ is used to output the parameters passed to it • The typical usage for this is to send data to the client’s web-browser • Syntax • void echo (string arg1 [, string argn...]) • In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function
  • 18. Echo exampleEcho example • Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25 • Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP • This is true for both variables and character escape-sequences (such as “n” or “”) <?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable echo $bar; // Outputs Hello echo $foo,$bar; // Outputs 25Hello echo “5x5=”,$foo; // Outputs 5x5=25 echo “5x5=$foo”; // Outputs 5x5=25 echo ‘5x5=$foo’; // Outputs 5x5=$foo ?>
  • 19. Arithmetic OperationsArithmetic Operations • $a - $b // subtraction • $a * $b // multiplication • $a / $b // division • $a += 5 // $a = $a+5 Also works for *= and /= <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?>
  • 20. ConcatenationConcatenation • Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  • 21. Escaping the CharacterEscaping the Character • If the string has a set of double quotation marks that must remain visible, use the [backslash] before the quotation marks to ignore and display them. <?php $heading=“”Computer Science””; Print $heading; ?> “Computer Science”
  • 22. PHP Control StructuresPHP Control Structures  Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script.  Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops).  Example if/else if/else statement: if ($foo == 0) { echo ‘The variable foo is equal to 0’; } else if (($foo > 0) && ($foo <= 5)) { echo ‘The variable foo is between 1 and 5’; } else { echo ‘The variable foo is equal to ‘.$foo; }
  • 23. If ... Else...If ... Else... • If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in PHP
  • 24. Conditionals: if elseCan execute a set of code depending on a condition <html><head></head> <!-- if-cond.php --> <body> <?php $d=date("D"); echo $d, “<br/>”; if ($d=="Fri") echo "Have a nice weekend! <br/>"; else echo "Have a nice day! <br/>"; $x=10; if ($x==10) { echo "Hello<br />"; echo "Good morning<br />"; } ?> </body> </html> if (condition) code to be executed if condition is true; else code to be executed if condition is false; date() is a built-in PHP function that can be called with many different parameters to return the date (and/or local time) in various formats In this case we get a three letter string for the day of the week.
  • 25. While LoopsWhile Loops • While (condition) { Statements; } <?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ?> hello PHP. hello PHP. hello PHP.
  • 26. Looping: for and foreach Can loop depending on a "counter" <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> loops through a block of code a specified number of times <?php $a_array = array(1, 2, 3, 4); foreach ($a_array as $value) { $value = $value * 2; echo “$value <br/> n”; } ?> loops through a block of code for each element in an array <?php $a_array=array("a","b","c"); foreach ($a_array as $key => $value) { echo $key." = ".$value."n"; } ?>
  • 27. Conditionals: switch Can select one of many sets of lines to execute <html><head></head> <body> <!–- switch-cond.php --> <?php $x = rand(1,5); // random integer echo “x = $x <br/><br/>”; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; break; } ?> </body> </html> switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; break; }
  • 28. Date DisplayDate Display $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is June 25th, 2012 # It would display as 2012/25/6 2012/25/6 $datedisplay=date(“l, F m, Y”); Print $datedisplay; # If the date is June 25th ,2012 # Monday, June 25th ,2012 Monday, June 25, 2012
  • 29. Arrays An array in PHP is actually an ordered map. A map is a type that maps values to keys. array() = creates arrays<?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?> key = either an integer or a string. value = any PHP type. <?php array(5 => 43, 32, 56, "b" => 12); array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> if no key given (as in example), the PHP interpreter uses (maximum of the integer indices + 1). if an existing key, its value will be overwritten. <?php $arr = array(5 => 1, 12 => 2); foreach ($arr as $key => $value) { echo $key, ‘=>’, $value); } $arr[] = 56; // the same as $arr[13] = 56; $arr["x"] = 42; // adds a new element unset($arr[5]); // removes the element unset($arr); // deletes the whole array $a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); $b = array_values($a); ?> can set values in an array unset() removes a key/value pair array_values() makes reindexing effect (indexing numerically)
  • 30. Month, Day & Date Format SymbolsMonth, Day & Date Format Symbols M Jan F January m 01 n 1 Day of Month d 01 Day of Month J 1 Day of Week l Monday Day of Week D Mon
  • 31. FunctionsFunctions • Functions MUST be defined before then can be called • Function headers are of the format • Note that no return type is specified • Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…)) function functionName($arg_1, $arg_2, …, $arg_n)
  • 32. Functions exampleFunctions example <?php // This is a function function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2; return $arg_2; } $result_1 = foo(12, 3); // Store the function echo $result_1; // Outputs 36 echo foo(12, 3); // Outputs 36 ?>
  • 33. User Defined Functions Can define a function using syntax such as the following: <?php function foo($arg_1, $arg_2, /* ..., */ $arg_n) { echo "Example function.n"; return $retval; } ?> Can also define conditional functions, functions within functions, and recursive functions. <?php function square($num) { return $num * $num; } echo square(4); ?> <?php function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); echo $zero, $one, $two; ?> Can return a value of any type <?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } takes_array(array(1,2)); ?>
  • 34. Variable Scope The scope of a variable is the context within which it is defined. <?php $a = 1; /* limited variable scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?> The scope is local within functions, and hence the value of $a is undefined in the “echo” statement. <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> global refers to its global version. <?php function Test() { static $a = 0; echo $a; $a++; } Test1(); Test1(); Test1(); ?> static does not lose its value.
  • 35. Including Files The include() statement includes and evaluates the specified file. vars.php <?php $color = 'green'; $fruit = 'apple'; ?> test.php <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?> *The scope of variables in “included” files depends on where the “include” file is added! You can use the include_once, require, and require_once statements in similar ways. <?php function foo() { global $color; include ('vars.php‘); echo "A $color $fruit"; } /* vars.php is in the scope of foo() so * * $fruit is NOT available outside of this * * scope. $color is because we declared it * * as global. */ foo(); // A green apple echo "A $color $fruit"; // A green ?>
  • 36. Include FilesInclude Files Include “opendb.php”; Include “closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: <hr SIZE=11 NOSHADE WIDTH=“100%”> <i>Copyright © 2001-2012 gsu</i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL: http://www.gsu.edu.edu</i></font><br>
  • 37. PHP - FormsPHP - Forms •Access to the HTTP POST and GET data is simple in PHPAccess to the HTTP POST and GET data is simple in PHP •The global variables $_POST[] and $_GET[] contain theThe global variables $_POST[] and $_GET[] contain the request datarequest data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form>
  • 38. WHY PHP – Sessions ?WHY PHP – Sessions ?Whenever you want to create aWhenever you want to create a websitewebsite that allows you to store and displaythat allows you to store and display information about a user, determine which user groups a person belongs to,information about a user, determine which user groups a person belongs to, utilize permissions on yourutilize permissions on your websitewebsite or you just want to do something cool onor you just want to do something cool on your site,your site, PHP's SessionsPHP's Sessions are vital toare vital to eacheach of these features.of these features. Cookies are about 30% unreliable right now and it's getting worse every day.Cookies are about 30% unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacyMore and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown uponsettings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they doCookies because they store information on their local computer that they do not want stored there.not want stored there. PHP has a great set of functions that can achieve the same results ofPHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHPCookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you choseSessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via thein special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99% flawless inserver and a special ID called a "Session ID". This is nearly 99% flawless in operation and it is virtually invisible to the user.operation and it is virtually invisible to the user.
  • 39. PHP - SessionsPHP - Sessions •Sessions store their identifier in a cookie in the client’s browserSessions store their identifier in a cookie in the client’s browser •Every page that uses session data must be proceeded by theEvery page that uses session data must be proceeded by the session_start()session_start() functionfunction •Session variables are then set and retrieved by accessing the globalSession variables are then set and retrieved by accessing the global $_SESSION[]$_SESSION[] •Save it asSave it as session.phpsession.php <?php<?php session_start();session_start(); if (!$_SESSION["count"])if (!$_SESSION["count"]) $_SESSION["count"] = 0;$_SESSION["count"] = 0; if ($_GET["count"] == "yes")if ($_GET["count"] == "yes") $_SESSION["count"] = $_SESSION["count"] + 1;$_SESSION["count"] = $_SESSION["count"] + 1; echo "<h1>".$_SESSION["count"]."</h1>";echo "<h1>".$_SESSION["count"]."</h1>"; ?>?> <a href="session.php?count=yes">Click here to count</a><a href="session.php?count=yes">Click here to count</a>
  • 40. Avoid Error PHP - SessionsAvoid Error PHP - Sessions PHP Example: <?php echo "Look at this nasty error below:<br />"; session_start(); ?> Error! PHP Example: <?php session_start(); echo "Look at this nasty error below:"; ?> Correct Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3
  • 41. Destroy PHP - SessionsDestroy PHP - Sessions Destroying a Session why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Well, imagine that you had a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called session_destroy() comes in handy. session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session. NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy. Here's how we use session_destroy():
  • 42. Destroy PHP - SessionsDestroy PHP - Sessions <?php // start the session session_start(); header("Cache-control: private"); //IE 6 Fix $_SESSION = array(); session_destroy(); echo "<strong>Step 5 - Destroy This Session </strong><br />"; if($_SESSION['name']){     echo "The session is still active"; } else {     echo "Ok, the session is no longer active! <br />";     echo "<a href="page1.php"><< Go Back Step 1</a>"; } ?>