0% found this document useful (0 votes)
66 views

Unit 4 PHP

This document provides an introduction to PHP and XML. It discusses PHP variables, data types, outputting variables, and program control structures like if/else statements. It also covers basic XML concepts like document type definitions and XML parsers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Unit 4 PHP

This document provides an introduction to PHP and XML. It discusses PHP variables, data types, outputting variables, and program control structures like if/else statements. It also covers basic XML concepts like document type definitions and XML parsers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT IV PHP and XML

An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in


functions-Form Validation XML: Basic XML- Document Type Definition- XML Schema
DOM and Presenting XML, XML Parsers and Validation, XSL

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

Global Scope <!DOCTYPE html>


A variable declared outside a <html>
function has a GLOBAL <body>
SCOPE and can only be
accessed outside afunction: <?php
$x = 5; // global scope

function myTest()
{
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

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


?>
</body>
</html>
Output: Variable x inside function is:
Variable x outside function is: 5

LocalScope:A variable declared <?php


within a function has a LOCAL function myTest()
SCOPE and can only be accessed {
within thatfunction $x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
"<p>Variable x outside function is: $x</p>";
?>
Output:
Variable x inside function is: 5
Variable x outside function is:
The global keyword is used to access a global variable from within afunction.

To do this, use the global keyword before the variables (inside thefunction):

PHP The static Keyword <html>


Normally, when a function is <body>
completed/executed, all of <?php
its variables are deleted. function myTest()
However, sometimes we {
want a local variable NOT to static $x = 0; echo $x;
be deleted. We need it for a $x++;
further job. }
Output: myTest();
0 echo "<br>"; myTest();
1 echo "<br>"; myTest();
2 ?>
</body>
</html>

Rules for naming variables:


A variable starts with the $ sign, followed by the name of thevariable
A variable name must start with a letter or theunderscore
A variable name cannot start with anumber
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
Variable names are case-sensitive ($age and $AGE are two different variables
Create a PHP Constant
To create a constant, use the define() function.
Syntax:
define(name, value, case-insensitive)
Example:
define("GREETING", "Welcome”);

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

The if...else Statement: if (condition) <?php


Use the if..else statement to { $a=10;
execute some code if a
code to be $b=20;
condition is trueand
another code if the condition executed if true; if ($a > $b)
is false. } echo "a is bigger than b";
else else
{ echo "b is big"
code to be ?>
executed if Output:b is big
condition is false;
}

The if...elseif....else if (condition) <?php


Statement { if ($a > $b)
code to be executed {
if condition is true; echo "a is bigger than b";
}
}
elseif (condition2)
elseif ($a == $b)
{
code to be executed {
if condition2 is true; echo "a is equal to b";
} }
else else {
{ echo "a is smaller than b";
code to be executed }
if condition is false; ?>
}

The Switch Statement <!DOCTYPE html>


switch (expression) <html><body>
{ <?php
case label1: $favcolor = "red"; switch ($favcolor)
code to be executed if {
expression = label1; case "red":
break; case label2: echo "Your favorite color is red!"; break;
code to be executed if case "blue":
expression = label2; echo "Your favorite color is blue!"; break;
break; case "green":
---- echo "Your favorite color is green!"; break;
---- default:
---- echo "Your favorite color is neither red, blue, nor green!";
default: }?>
code to be executed if </body></html>
expression is different
from both label1 and
label2;
}
PHPLOOPS
while - loops through a while <?php
block of code as long as (condition is $x = 1;
the specified condition true) while($x <= 5) {
istrue { echo "$x ";
code to be $x++;
executed; }
} ?>
Output:1 2 3 4 5
do...while - loops do do
through a block of code {code to {
once, and then repeats the be executed; echo "The number is: $x <br>";
loop as long as the } $x++;
specified condition is true while }
(condition is while ($x <= 5);
true); ?>
for - loops through a block of for (init <?php
code a specified number of counter; test for ($x = 0; $x <= 10; $x++)
times counter; {
increment echo "The number is: $x";
counter) }
{ ?>
code to be
executed;
}
foreach - loops through a foreach <?php
block of code for each element ($array as $colors = array("red", "green", "blue", "yellow");
in an array $value)
foreach ($colors as $value) {
{code to
be echo "$value <br>";
executed;} }
?>

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;
}

Function example for adding two numbers:


<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head> Sum of the two
<body> numbers is : 30
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Built in functions
String Functions
These are functions that manipulate string data. The PHP string functions are part of the PHP core. No
installation is required to use these functions.
Function Description

echo() Outputs one or more strings

htmlspecialchars() Converts some predefined characters to HTML entities

print() Outputs one or more strings

rtrim() Removes whitespace or other characters from the right side


of a string
strlen() Returns the length of a string

strncmp() String comparison of the first n characters (case-sensitive)

strrev() Reverses a string

strripos() Finds the position of the last occurrence of a string inside


another string (case-insensitive)
strstr() Finds the first occurrence of a string inside another string
(case-sensitive)
strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters


strtr() Translates certain characters in a string

substr() Returns a part of a string


Numeric Functions

Numeric functions are function that return numeric results.Numeric php function can be used to format
numbers, return constants, perform mathematical computations etc.

Function Description Example Output


is_number Accepts an argument and returns true if (is_numeric (123)) true
its numeric and false if it’s not

number_format Used to formats a numeric value using <?php 2,509,663


echo number_format(2509663);
digit separators and decimal points
?>
rand Used to generate a random number. <?php Random number
echo rand();
?>
round Round off a number with decimal <?php 3
echo round(3.49);
points to the nearest whole number.
?>
sqrt Returns the square root of a number <?php 10
echo sqrt(100);
?>
cos Returns the cosine <?php 0.52532198881773
echo cos(45);
?>
sin Returns the sine <?php 0.85090352453412
echo sin(45);
?>
tan Returns the tangent <?php 1.6197751905439
echo tan(45);
?>
pi Constant that returns the value of PI <?php 3.1415926535898
echo pi();
?>

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.

Sr.No Function & Description

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"]);
}
}

?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

You might also like