Unit 4 PHP
Unit 4 PHP
INTRODUCTION TOPHP
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based software
applications
• PHP is an acronym for "PHP: HypertextPreprocessor"
• PHP is a widely-used, open source scriptinglanguage
• PHP files can contain text, HTML, CSS, JavaScript, and PHPcode
• PHP code are executed on the server, and the result is returned to the browser as plainHTML
• PHP files have extension".php"
PHP on WWW
A PHP script is executed on the server, and the plain HTML result is sent back to thebrowser.
The default file extension for PHP files is".php".
A PHP file normally contains HTML tags, and some PHP scriptingcode.
BASIC PHP SYNTAX
A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
PHP EXAMPLE PROGRAM
<html><body>
<?php
echo "Welcome to PHP programming
session!";
?>
</body></html>
Output: Welcome to PHP programmingsession
PHP VARIABLES
➢ Variables are "containers" for storinginformation. Here are the most important things to know about
variables in PHP.
➢ All variables in PHP are denoted with a leading dollar sign($).
➢ The value of a variable is the value of its most recentassignment.
➢ PHP does a good job of automatically converting types from one to another whennecessary.
PHP has a total of eight data types which we use to construct our variables:
1. Integers: are whole numbers, without a decimal point, like4195.
2. Doubles: are floating-point numbers, like 3.14159 or49.1.
3. Booleans: have only two possible values either true orfalse.
4. NULL: is a special type that only has one value:NULL.
5. Strings: are sequences of characters, like 'PHP supports stringoperations.
6. Arrays: are named and indexed collections of othervalues.
7. Objects: are instances of programmer-defined classes, which can package up both other kinds of values
and functions that are specific to theclass.
8. Resources: are special variables that hold references to resources external to PHP (such as
databaseconnections).
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of thevariable:
Example:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Hello world!
5
10.5
Output Variables
The PHP echo statement is often used to output data to the screen. The following
example will show how to output text and avariable:
Example
<?php
$txt = "W3Schools.com";
echo "$txt!";
?>
Output:W3Schools.com!
Example
<?php
$x =5; output:9
$y =4;
echo $x + $y;
?>
PHP Variables Scope
In PHP, variables can be declared anywhere in thescript.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
Local Variable
Global Variable
Static Variable
function myTest()
{
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
To do this, use the global keyword before the variables (inside thefunction):
OUTPUT VARIABLES
1. PHP ECHO
2. PRINT STATEMENTS
The PHP echo statement is often used to output data to thescreen
Example:
<!DOCTYPE html> OUTPUT:
<html><body> Hello world!
5
<?php
10.5
$txt = "Hello world!"; 15.5
$x = 5;
$y = 10.5;
echo $txt; echo "<br>";
echo $x; echo "<br>";
echo $y; echo "<br>";
echo $x + $y;
?>
</body>
</html>
The PHP print Statement
The print statement can be used with or without parentheses: print or print(). Display Text The
following example shows how to output text with the print command (notice that the text can contain
HTML markup):
<!DOCTYPE html>
<html>
<body>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
</body>
</html>
OUTPUT
PHP is Fun!
Hello world!
I'm about to learn PHP!
PHP PROGRAMCONTROL
PHP Program Control has two parts
1. CONDITIONALSTATEMENT
2. LOOPING (OR) ITERATIVE (OR) REPETITIVE STATEMENTS
if (condition) <?php
The if Statement { $a=30;
if statement is used to code to be executed
execute some code only if $b=20;
if condition is true;
a specified condition is if ($a > $b)
}
true. echo "a is bigger than b";
?>
Output: a is bigger than b
PHP FUNCTIONS
PHP User Defined Functions
• Besides the built-in PHP functions, we can create our ownfunctions.
• A function is a block of statements that can be used repeatedly in aprogram.
• A function will not execute immediately when a pageloads.
• A function will be executed by a call to thefunction.
• A user defined function declaration starts with the word"function"
SYNTAX
function functionName()
{
code to be executed;
}
Numeric functions are function that return numeric results.Numeric php function can be used to format
numbers, return constants, perform mathematical computations etc.
Date Function
The date function is used to format Unix date and time to human readable format.
Example
Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Arrays
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("alto", "duster", "innova");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
for($i=0;$i<count($cars);$i++)
{
print("<br>".$cars[$i]);
}
?>
</body>
</html>
REGULAR EXPRESSION:
Refer unit 2 regular expression instead of test and match use methods given in table
Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the
foundation for pattern-matching functionality. Using regular expression you can search a particular string inside
another string, you can replace one string by another string and you can split a string into many chunks. PHP
offers functions specific to regular expression functions, each corresponding to a certain type of regular
expression.
preg_match() The preg_match() function searches string for pattern, returning true
if pattern exists, and false otherwise
preg_match_all() The preg_match_all() function matches all occurrences of pattern in
string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except
that regular expressions can be used in the pattern and replacement
input parameters.
preg_split() The preg_split() function operates exactly like split(), except that
regular expressions are accepted as input parameters for pattern.
The two most commonly used functions are preg_match and preg_replace. Searches subject for a match to t
he regular expression given in pattern.
<?php
$my_url = "www.mind99.com";
if (preg_match("/mind/", $my_url))
{
echo "the url $my_url contains mind";
}
else
{
echo "the url $my_url does not contain mind";
}
?>
Email validation:
<?php
function valid_email($str) {
return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE :
TRUE;
}
if(!valid_email("[email protected]")){
echo "Invalid email address.";
}else{
echo "Valid email address.";
}
?>
Form validation:
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"]))
{
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>