12.module4 PHP-INTRO 10 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

INTRODUCTION TO OPEN

SOURCE & PHP

Prof.N.Nalini
AP(Sr)
SCOPE
VIT
PHP INTRODUCTION

PHP is a recursive acronym for “PHP: Hypertext Preprocessor”


It is a widely-used open source general-purpose scripting
language that is especially suited for web development and can
be embedded into HTML.
PHP INTRODUCTION
> PHP is a server-side scripting language
> PHP scripts are executed on the server
> PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
> PHP is open source software
> PHP is free to download and use
> PHP is easy to learn and runs efficiently on the server
side
FEATURES OF PHP
Cross-platform compatibility.
No need to specify the data type for variable declarations, and predefined variables
can be used.
Availability of predefined error reporting constants.
Supports extended regular expressions.
Has the ability to generate dynamic page content.
Allows the user to create, open, read, write, delete and close files on the server
Output can be in HTML, images, PDF, Flash, XHTML and XML file formats.
Runs on various platforms such as Windows, Linux, UNIX, Mac OSx, etc.
It is compatible with almost all servers being used currently.

4
PHP with HTML

 What makes PHP so different is that it not only allows


HTML pages to be created.

 It is invisible to your Web site visitors. The only thing


they see the resulting HTML output. This gives you more
security for your PHP code and more flexibility in writing it.

 HTML can also be written inside the PHP section of your


page.

 PHP can also be written as a standalone program, with no


HTML

5
PHP Syntax

PHP is denoted in the page with opening and


closing tags as follows:

Opening Tag <?php


//php code;
?>

Closing Tag

6
PHP Programs

Code
Result
<HTML>
<HEAD>
<TITLE>
My First PHP Program
</TITLE> <h1>
</HEAD>
<BODY>
<?php
echo “I’m a PHP Program.”;
?>
</BODY>
</HTML>

7
PHP Programs

Code Result
<?php
$name=“VIT UNIVERSITY”;
echo ‘My name is ‘.$name;
?>

8
Comment Line in PHP

1.Single Line Comment - Single line


comment in PHP is identified with //.
<?Php
// my first prg
?>

2.# -comment
3.Multi Lines Comment - Multi lines
comment in PHP is identified by /* … */
<?Php
/* line1
line2
line 3 */
?>

9
10
Output in PHP

1. Echo & Print is the common method in


outputting data. it is a language construct

2. Output Text Usage:

<?php
echo “Hello World”;
print “Hello World”; // prints out Hello World
?>

11
• Echo display the outputs one or more strings
separated by commas.
• It accepts an list of argument (multiple arguments
can be passed) and returns no value or returns void.

• Print always returns the value 1.


• Unlike echo, print accepts only one argument at a time.
• The print outputs only the strings.
• It is slow compared to that of echo.

12
Output in PHP

3. Output the value of a PHP variable:

<?php
echo $hits; // prints out the number of hits
print $hits; // returns a value if print process success.
?>

4. Can use “<br>”, to print in next line:

<?php
echo $a, “<br>”,$b ; //prints a & b in separate
lines
?>

13
Data Type

• Four basic data types:


1. Integer
2. Float(Double)
3. String
4. Boolean
• More data types
1. Array
2. Object
• PHP is an untyped language
– variables type can change on the fly.

14
<?php
PHP STRING $x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
• A string is a sequence echo $y;
of characters, like ?>
"Hello world!".
• A string can be any
text inside quotes. You
can use single or
double quotes:
Quotes (“ Vs. ‘)
In a double-quoted string any variable names are expanded
to their values.
In a single-quoted string, no variable expansion takes place.

$name = “abc"; $name = “abc";


$age = 23; $age = 23;
echo '$name is $age'; echo “$name is $age”;

Output is Output is
$name is $age abc is 23

16
<?php
$x = 5985;
PHP INTEGER var_dump($x);
?>
• An integer is a whole number (without
decimals). It is a number between -
2,147,483,648 and +2,147,483,647.
• Rules for integers:
• An integer must have at least one digit (0-9)
• An integer cannot contain comma or blanks
• An integer must not have a decimal point
• An integer can be either positive or
negative
• Integers can be specified in three formats:
decimal (10-based), hexadecimal (16-
based - prefixed with 0x) or octal (8-based
- prefixed with 0)
PHP FLOAT <?php
$x = 10.365;
var_dump($x);
?>

• A float (floating point


number) is a number with a
decimal point or a number
in exponential form.
• In the following example $x
is a float. The PHP
var_dump() function returns
the data type and value
PHP BOOLEAN $x = true;
$y = false;

• A Boolean represents two


possible states: TRUE or
FALSE.
• Booleans are often used in
conditional testing. You will
learn more about
conditional testing in a later
chapter of this tutorial.
Constants
• values that never changes.

• A constant is case-sensitive by default.


• A valid constant name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.
• Constants are defined in PHP by using the define( ) function.
– For e.g.
define(“VIT”, “Vellore Institute of Technology”);
echo VIT;//Extract constant value

• defined() function says whether the constant exists or not.

20
21
22
Variables

• The variables in PHP are declared by appending the $ sign to


the variable name.
– For e.g
$company = “NCST”;
$sum = 10.0;
• Variable’s data type is changed by the value that is assigned
to the variable.
• PHP is a Loosely Typed Language which automatically
converts the variable to the correct data type, depending on
its value.
• Type casting allows to change the data type explicitly.

23
Variables
Rules for Naming User Defined Variables:
 In PHP, unlike some other programming languages,
there is no restriction on the size of a variable name.

 Variable names should identified by dollar ($) symbol.


 Variable names can begin with an underscore.
 Variable names cannot begin with a numeric
character.
 Variable names must be relevant and self-
explanatory.

24
Variables

Valid Examples In Valid Examples

$prod_desc $9OctSales
$Intvar Sales123
$_Salesamt $*asgs

25
Variables (cont)

$MyStrVal = "This is an example of a string value";


$MyIntVal = 145665; // An integer value
$MyBoolval = True; // A Boolean value can either be
True or False
$MyFloatVal=2346.45 // A float value
$MyArrVal[0] = "My"; //An array containing three
elements
$MyArrVal[1] = "First";
$MyArrVal[2] = "Array";

26
VARIABLES (CONT)
$Ball = "a";
$Foo = "Ball";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a;
$$a;
$$$a;
$$$$a;
$$$$$a;

1. $$$$$$a; --------------
2. $$$$$$$a; -----------------

27
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Ball
$$$$$a; //Returns a
1. $$$$$$a; --------------
2. $$$$$$$a; -----------------

28
Assign by Reference

PHP also offers another way to assign values to variables:


assign by reference. This means that the new variable
simply references (in other words, "becomes an alias for"
or "points to") the original variable.
Changes to the new variable affect the original, and vice
versa.
To assign by reference, simply prepend an ampersand (&)
to the beginning of the variable which is being assigned
(the source variable).

29
30
31
PHP VARIABLES SCOPE

PHP has three different variable scopes:


local
Global-global and $GLOBALS[index]
static

32
33
PHP SUPER GLOBALS
Super Globals are variables that are automatically
available throughout all program code in all scopes.
These variables do not require declaration and then too
they can be accessed.
Super global variables provide :-
 Useful information about the environment.
 Allow access to HTML form variables or parameters.
 Access to cookies stored on a client.
 Keeping track of sessions and file uploads.
Name Functionality

Contains all global variables in your script, including other super


globals.
$GLOBALS
This is not generally recommended for use, unless you are, for
some reason, not sure where a variable will be stored.

Contains all variables sent via a HTTP GET request. That is, sent
$_GET
by way of the URL.

$_POST Contains all variables sent via a HTTP POST request.

$_FILES Contains all variables sent via a HTTP POST file upload.

$_COOKIE Contains all variables sent via HTTP cookies.

$_SESSION Contains all variables stored in a user's session.

Contains all variables set by the web server you are using, or
$_SERVER
other sources that directly relate to the execution of your script.
Name Functionality

Contains all variables sent via HTTP GET, HTTP POST, and HTTP
cookies. This is basically the equivalent of combining $_GET,
$_POST, and $_COOKIE, and is less dangerous than using
$_REQUEST
$GLOBALS. However, as it does contain all variables from
untrusted sources (that is, your visitors), you should still try to
steer clear unless you have very good reason to use it.

Contains all environment variables set by your system or shell


$_ENV
for the script.
Settype
In PHP, Variable type can be changed by Settype

Settype
Syntax:
Settype(Variablename, “newDataType”);

E.g.
$pi = 3.14 //float
Settype($pi,”string”); //now string – “3.14”
Settype($pi,”integer”);// now integer - 3

37
Settype & Gettype
In PHP, Variable type and can know by Gettype.

Syntax:
Gettype(Variablename);

E.g.
$pi = 3.14;
print gettype($pi);
Print “---$pi <br>”;
Settype($pi,”string”);
print gettype($pi);
Print “---$pi <br>”;
Settype($pi,”integer”);
print gettype($pi);
Print “---$pi <br>”;

38
HERE DOCUMENTS
The heredoc string structure is a method of including larger strings inside the
php code. To create a heredoc, you use a special operator that is made
up of three left brackets ( <<< ). The syntax is as follows:

Syntax:

$longString = <<< termination_marker any amount of content


termination_marker;

39
Operators

• All the operators such as arithmetic,


assignment, Comparison, and logical
operators are similar to the operators in C
and C++.
• In PHP the string concatenation operator is
denoted by ‘.’
– For e.g.
.
$name = “My name is” $myname;

40
PHP ARITHMETIC
OPERATORS
PHP ASSIGNMENT
OPERATORS
Assignment Same as... Description

$x = $y $x =$ y The left operand gets set to the value of the expression on the right

$x += $y $x = $x + $y Addition

$x -= $y $x = $x - $y Subtraction

$x *= $y $x = $x * $y Multiplication

$x /= $y $x = $x / $y Division

$x %= $y $x = $x % $y Modulus
PHP COMPARISON
OPERATORS
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of
the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP INCREMENT /
DECREMENT
OPERATORS
Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one


PHP LOGICAL Operator Name Example Result
OPERATORS and And $x and $y True if both $x and $y are
true

or Or $x or $y True if either $x or $y is
true

xor Xor $x xor $y True if either $x or $y is


true, but not both

&& And $x && $y True if both $x and $y are


true

|| Or $x || $y True if either $x or $y is
true

! Not !$x True if $x is not true


PHP STRING
OPERATORS
Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1


PHP ARRAY
OPERATORS
Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same key/value


pairs

=== Identity $x === $y Returns true if $x and $y have the same key/value
pairs in the same order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y


Conditional Statements
(Branching)
1. If…else Statement – single decision stmt

Syntax E.g.
if (<condition>) if ($num1 > $num2)
{ {
//True part $max = $num1;
Php code }
} else
else {
{ $max = $num2;
//False part }
php code
}

48
Conditional Statements
(Branching)
2. If…else if Statement – multiple decision stmt
Syntax
if (<condition1>) E.g.
{
//True part Php code
} if ($num1 > $num2)
else if (<condition2>) {
{ $max = $num1;
//1st False 2nd true part }
php code else if ($num2 > $num3)
} {
else $max = $num3;
{ }
// false part PhP code else
} $max = $num2;

49
Conditional Statements
(Branching)
3. Switch Statement – replacement of “if ……
else if stmt”.
E.g.
Syntax
switch ($day)
switch (expression) {
{ case 1: {echo “its Sunday”;
case value1: {stmts1; break;}
break;} case 2: {echo “its Monday”;
case value2: {stmts2; break;}
break;} ………
………… ………
………… case 7: {echo “its Saturday”;
[default: stmts;] break;}
} default: {echo “not specified
value”;}
}

50
Conditional Statements
(Looping)
4. For Statement – replacement of “if …… else
if stmt”.

Syntax E.g.

for( initial_expression; for($i=1; $i < 10; $i++)


termination_check; echo $i;
index_updation)
{ (or)
statement (S); $i=1;
} for(;$i<10;)
{
echo $i;
$i=$i+1;
}

51
FOREACH LOOP
The foreach construct provides an easy way to iterate over arrays.
foreach works only on arrays and objects.
foreach will issue an error when you try to use it on a variable with a different data type or
an uninitialized variable.
Syntax : 1 foreach (array_expression as $value)
statement // indexed array
Syntax : 2 foreach (array_expression as $key => $value)
statement // associative array
When foreach first starts executing, the internal array pointer is automatically reset to the
first element of the array. Associative Array :
Indexed Array : <?php
<?php $arr = array(1=>’ABC’,2=>’PQR’);
$array = array(1,2,3,4); foreach ($arr as $key => $val) {
foreach($array as $val) { print "$key = $val\n";
print $val; } }

?> ?>
Conditional Statements
(Looping)
5. Do … While Statement

Syntax E.g.

do do
{ {
Statement (S); $i=$i+1;
} echo $i;
while (<condition>); } while ($i < 10);

53
Conditional Statements
(Looping)
5. While Statement

Syntax E.g.

while(<condition>) while ($i < 10)


{ {
Statement (S); $i=$i+1;
} echo $i;
}

54
<html>
<body>
<form method=POST action="<?php $_SERVER[“PHP_SELF”]; ?>">
[or]
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter your name &nbsp;<input type=text name="tname" value=" ">
<br>
<input type=submit name="submit" value="Click">
</form>
<?php
//if ($_SERVER["REQUEST_METHOD"] == "POST")
if($_POST['submit']=="Click")
{
$var=$_POST['tname'];
echo "Your name is ".$var;
}
?>
</body>
</html>
55

You might also like