Você está na página 1de 54

Wachemo University

School of Computing & Informatics


Computer Science
Department

Internet Programming II
What is PHP?
PHP stands for PHP: Hypertext Preprocessor
PHP is a server-side scripting language, like ASP
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.)
Use xamp or wamp which comprises apache server,
PHP and MySQL.
What is a PHP File?
PHP files may contain text, HTML, CSS,
JavaScript, and PHP code
PHP files are returned to the browser as plain
HTML
PHP files have a file extension of ".php
In PHP, all keywords (e.g. if, else, while, echo, etc.),
classes, functions, and user-defined functions are
NOT case-sensitive.
Basic PHP Syntax
A PHP scripting block always starts with <?php and
ends with ?>

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Get Started
1. Install wamp 2.1
2. Run wamp 2.1
3. Wait until the color of wamp icon on the taskbar
changed to GREEN
4. Save your php file by an extention .php(eg. Home.php)
on c:\wamp\www\
5. To run your file, open any browser by writing the
following path on the URL: localhost/home.php
6. Then, load the page by pressing ENTER key
Comments in PHP

<!DOCTYPE html>
<html><body>
<?php
// This is a single-line comment
# This is also a single-line comment
/* This is a multiple-lines comment block
that spans over multiple lines */
// comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body></html>
Variables in PHP
Variables are "containers" for storing information.
all variable names are case-sensitive.
In PHP, a variable starts with the $ sign, followed by the
name of the variable:
$var_name = value;

<?php
$txt = "Hello World!";
$number = 16;
?>
In PHP the variable is declared automatically when you
use it.
PHP Data Types
Variables can store data of different types, and different data
types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
PHP Strings

A string can be any text inside quotes. You can use


single or double quotes:

<?php
$txt1="Hello our";
$txt2='World';
echo $txt1 . " " . $txt2;
?>
PHP String Functions

<?php

echo strlen("Hello world!"); // outputs 12


echo str_word_count("Hello world!"); // outputs 2
echo strrev("Hello world!"); // outputs !dlrow olleH
echo strpos("Hello world!", "world"); // outputs 6
echo str_replace("world", "Dolly", "Hello
world!"); // outputs Hello Dolly!

?>
PHP Constants
Constants are like variables except that once they
are defined they cannot be changed or undefined.
A constant is an identifier (name) for a simple
value. The value cannot be changed during the
script.
A valid constant name starts with a letter or
underscore (no $ sign before the constant name).
Note: Unlike variables, constants are
automatically global across the entire script.
Syntax
define(name, value, case-insensitive)
Examples
<?php
define("GREETING", "Welcome to W3Schools.com!",
true);
echo greeting;
?>

<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric
values to perform common arithmetical operations, such
as addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
Remainder of $x divided by
% Modulus $x % $y
$y
Result of raising $x to the
** Exponentiation $x ** $y $y'th power (Introduced in
Example:
<!DOCTYPE html>
<html>
<body>

<?php
$num1 = 10;
$num2 = 80;
$num3 = 20;

$sum = $num1 + $num2 / $num3 ;

echo $sum;
?>

</body>
</html>
PHP Assignment Operators
The PHP assignment operators are used with numeric values to
write a value to a variable.
The basic assignment operator in PHP is "=". It means that the
left operand gets set to the value of the assignment expression
on the right.
Assignment Same as... Description
The left operand gets set to the value
x=y x=y
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
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$x /= 5;
echo $x;
?>
</body>
</html>
PHP Comparison Operators
The PHP comparison operators are used to compare two
values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
Returns true if $x is equal to $y, and
=== Identical $x === $y
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
Returns true if $x is not equal to $y,
!== Not identical $x !== $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 Returns true if $x is greater than or
>= $x >= $y
equal to equal to $y
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$num='4';
$num2=4;
if($num===$num2)
echo 'Equal';
else
echo 'Inequal';
?>
</body>
PHP Increment / Decrement Operators

The PHP increment operators are used to increment a


variable's value.
The PHP decrement operators are used to decrement a
variable's value.

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
Example:
<!DOCTYPE html>
<html>
<body>

<?php
$x = 10;
echo ++$x;
?>

</body>
</html>
PHP Logical Operators
The PHP logical operators are used to combine
conditional statements.

Operator Name Example Result


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
True if either $x or $y is true, but not
xor Xor $x xor $y
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
Example:
<!DOCTYPE html>
<html>
<body>

<?php
$num = 100;

$lower = 50;
$upper = 1000;

if ($num <= 50 && $num >= 100) {


echo Ok!";
} ?>

</body>
</html>
PHP String Operators
PHP has two operators that are specially designed
for strings.

Operator Name Example Result


Concatenation of
. Concatenation $txt1 . $txt2
$txt1 and $txt2
Concatenation Appends $txt2 to
.= $txt1 .= $txt2
assignment $txt1
Example:
<!DOCTYPE html>
<html>
<body>

<?php
$txt1 = "Hello";
$txt1 .= " world!";
echo $txt1;
?>

</body>
</html>
PHP Array Operators
The PHP array operators are used to compare arrays
Operator Name Example Result
+ Union $x + $y Union of $x and $y
Returns true if $x and $y have the
== Equality $x == $y
same key/value pairs
Returns true if $x and $y have the
=== Identity $x === $y same key/value pairs in the same
order and of the same types
Returns true if $x is not equal to
!= Inequality $x != $y
$y
Returns true if $x is not equal to
<> Inequality $x <> $y
$y
The If...Else Statement
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") {
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
} //else if ($d=="Sun") echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
The Switch Statement
<html>
<body>
<?php
$x=4;
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";
}
?>
</body>
</html>
The while Loop
<?php

$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The do...while Loop
In a do while loop the condition is tested AFTER executing the
statements within the loop. This means that the do while loop
would execute its statements at least once, even if the condition
is false the first time.

<?php
$x = 6;

do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
The for Loop

<?php

for ($x = 10; $x >= 1; $x--) {


echo "The number is: $x <br>";
}

?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to
loop through each key/value pair in an array.
foreach ($array as $value) {
code to be executed; }

<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $val) {
echo "$val <br>";}
?>
die and exit Functions

<?php

echo 'Hello';

die(); //die('the page has been ended');

echo ' World';

?>
PHP Functions
A function name can start with a letter or underscore
(not a number).
Function names are NOT case-sensitive.

<?php
function writeMsg() {
echo " world Hello!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An
argument is just like a variable.
Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
<?php
function familyName($fname) {
echo "$fname David.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
?>
PHP Default Argument Value
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Example
<?php
function add($num1,$num2) {
$result = $num1 + $num2;
return $result;
}
function divide($num1,$num2) {
$result = $num1 / $num2;
return $result;
}
$div = divide(add(10,10),add(5,5));
echo $div;
PHP Arrays
An array can store one or more values in a single variable
name.

In PHP, there are three types of arrays:


Indexed array - An array with a numeric index
Associative array - Arrays with named keys
Multidimensional array - An array containing one or
more arrays
Indexed Arrays
$names = array("Peter","Quagmire","Joe");
the index key assigned manually
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] . " are ".


$names[0] . " 's neighbors";
Examples
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}

?>
Associative Arrays
With associative arrays we can use the values as keys and
assign values to them

<?php
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";


?>
Loop Through an Associative Array
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
foreach($age as $x => $x_val) {
echo "Key=" . $x . ", x_value=" . $x_val;
echo "<br>";
}
?>
Multidimensional Arrays
A multidimensional array is an array containing one or more
arrays.
Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
$cars = array
(
array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2),
array("Land Rover",17,15)
);
Accessing the Elements
<?php
$cars = array ( array("Volvo",22,18), array("BMW",15,13),
array("Saab",5,2), array("Land Rover",17,15) );

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2]. ".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2]. ".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2]. ".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2]. ".<br>";
?>
Cont...
<?php
$cars = array(
array("Volvo",22,18), array("BMW",15,13),
array("Saab",5,2), array("Land Rover",17,15) );
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>"; }
echo "</ul>"; }
?>
PHP - Sort Functions For Arrays

sort() - sort arrays in ascending order


rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order,
according to the value
ksort() - sort associative arrays in ascending order,
according to the key
arsort() - sort associative arrays in descending order,
according to the value
krsort() - sort associative arrays in descending order,
according to the key
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}

?>
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
arsort($age);
foreach($age as $x => $x_val) {
echo "Key=" . $x . ", x_value=" . $x_val;
echo "<br>";
}
?>
PHP Variables Scope
PHP has three different variable scopes: Local, Global, and static
Global Scope
A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
Local Scope
A variable declared within a function has a LOCAL SCOPE and
can only be accessed within that function:

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error

echo "<p>Variable x outside function is: $x</p>";


?>
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to
access global variables from anywhere in the PHP script (also
from within functions or methods).
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP 5 Form Handling

$_GET is an array of variables passed to the current script


via the URL parameters.
$_POST is an array of variables passed to the current script
via the HTTP POST method.
Information sent from a form with the GET method is visible
to everyone (all variable names and values are displayed in
the URL). GET also has limits on the amount of information
to send. The limitation is about 2000 characters.
Information sent from a form with the POST method is
invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the
amount of information to send.
Example
<!DOCTYPE HTML>
<html><body>
<form action="welcome.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body></html>

<html><body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"];?>
</body></html>
Example
<!DOCTYPE HTML>
<html><body>
<?php
$match = 123;
if (isset($_POST['pass'])) {
$psw = $_POST['pass'];
if (!empty($psw)) {
if ($psw==$match){
echo 'correct password';
} else {
echo 'incorrect password';
}
} else {
echo 'enter your password';
}
}
?>
<form action = "cs.php" method = "post">
Password: <input type = "password" name = "pass">
<input type = "submit" value = "submit">
</form>
</body></html>

Você também pode gostar