0% found this document useful (0 votes)
60 views32 pages

PHP Web Concepts

This document provides an overview of using regular expressions in PHP. It defines what regular expressions are and why they are useful for tasks like validation. It describes the two main parsing engines in PHP - POSIX and PCRE. It provides examples of POSIX-style regular expression functions in PHP like ereg() and ereg_replace() as well as an example of using PCRE functions with preg_match.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views32 pages

PHP Web Concepts

This document provides an overview of using regular expressions in PHP. It defines what regular expressions are and why they are useful for tasks like validation. It describes the two main parsing engines in PHP - POSIX and PCRE. It provides examples of POSIX-style regular expression functions in PHP like ereg() and ereg_replace() as well as an example of using PCRE functions with preg_match.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

PHP ─ Web Concepts

Identifying Browser & Platform


• PHP creates some useful environment variables used to setup the
PHP environment.

• PHP environment variables allow your scripts to glean certain types


of data dynamically from the server.

• One of the environment variables set by PHP in phpinfo.php is


HTTP_USER_AGENT which identifies the user's browser and
operating system.

• PHP provides a function getenv() to access the value of all the


environment variables.

• The information contained in the HTTP_USER_AGENT environment


variable can be used to create dynamic content appropriate to the
browser.
<html>
Example
<body> $platform = "An unidentified OS!";
<?php if( preg_match( "/Windows/i", "$viewer" )
$viewer = getenv( "HTTP_USER_AGENT" ); )
{
$browser = "An unidentified browser"; $platform = "Windows!";
if( preg_match( "/MSIE/i", "$viewer" ) ) }
{ else if ( preg_match( "/Linux/i", "$viewer" )
$browser = "Internet Explorer"; )
} {
else if(preg_match( "/Netscape/i", $platform = "Linux!";
"$viewer" ) ) }
{ echo("You are using $browser on
$browser = "Netscape"; $platform");
} ?>
else if(preg_match( "/Mozilla/i", </body>
"$viewer" ) ) </html>
{
$browser = "Mozilla";
}
Browser Redirection
• The PHP header() function supplies raw HTTP
headers to the browser and can be used to
redirect it to another location.

• The target is specified by the Location: header


as the argument to the header() function.

• After calling this function the exit() function


can be used to halt parsing of rest of the code.
Example
<?php
if( $_POST["location"] ) <option value="http://w3c.org">
{ World Wise Web Consortium
$location = $_POST["location"]; </option>
header( "Location:$location" ); <option
exit(); value="http://www.google.com">
} Google Search Page
?> </option>

<html> </select>
<body> <input type="submit" />
<p>Choose a site to visit :</p> </form>
</body>
<form action="<?php $_PHP_SELF ?>" </html>
method="POST"> <select
name="location">
PHP ─ Sending Emails

• PHP must be configured correctly in the php.ini file with


the details of how your system sends email.

Sending plain text email

• PHP makes use of mail() function to send an email. This


function requires three mandatory arguments that specify
the recipient's email address, the subject of the message
and the actual message additionally there are other two
optional parameters.

• mail( to, subject, message, headers, parameters );


Parameters
Parameter Description

to Required. Specifies the receiver / receivers of the


email

subject Required. Specifies the subject of the email. This


parameter cannot contain any newline characters

message Required. Defines the message to be sent. Each line should


be separated with a LF (\n). Lines should not exceed 70
characters

headers Optional. Specifies additional headers, like From, Cc, and


Bcc. The additional headers should be separated with
a CRLF (\r\n)

parameters Optional. Specifies an additional parameter to the send mail


program
• As soon as the mail function is called, PHP will
attempt to send the email, then it will return
true if successful or false if it is failed.

• Multiple recipients can be specified as the first


argument to the mail() function in a comma
separated list.
Example
<html> if( $retval == true )
<head> {
<title>Sending email using echo "Message sent successfully...";
PHP</title> }
</head> else
<body> {
echo "Message could not be sent...";
<?php }
$to = "[email protected]"; ?>
$subject = "This is subject";
$message = "This is simple text </body>
message."; </html>
$header =
"From:[email protected]
\r\n";
$retval = mail
($to,$subject,message,header);
PHP ─ File Uploading
• A PHP script can be used with a HTML form to allow
users to upload files to the server.

• Initially files are uploaded into a temporary


directory and then relocated to a target destination
by a PHP script.

• Information in the phpinfo.php page describes the


temporary directory that is used for file uploads as
upload_tmp_dir and the maximum permitted size of
files that can be uploaded is stated as
upload_max_filesize. These parameters are set into
PHP configuration file php.ini
Process of File Uploading steps
• The user opens the page containing a HTML form featuring a text files,
a browse button and a submit button.

• The user clicks the browse button and selects a file to upload from the
local PC.

• The full path to the selected file appears in the text field, then the user
clicks the submit button.

• The selected file is sent to the temporary directory on the server.

• The PHP script that was specified as the form handler in the form's
action attribute checks that the file has arrived and then copies the file
into an intended directory.

• The PHP script confirms the success to the user.


• While writing files, it is necessary for both
temporary and final locations to have
permissions set that enable file writing.

• An uploaded file could be a text file or image


file or any document.
Creating an Upload Form
• The following HTML code creates an uploader form.
• This form is having method attribute set to post and enctype attribute is set to
multipart/form-data

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>

Select a file to upload: <br />


<form action="/php/file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />

<input type="submit" value="Upload File" />


</form>
</body>
</html>
Creating an upload script
• There is one global PHP variable called $_FILES.
• This variable is an associate two dimensional
array and keeps all the information related to
uploaded file.
• PHP would create the following five variables if
the value of input’s name attribute in uploading
form was file

$_FILES['file']['tmp_name']- the uploaded file in the temporary


directory on the web server.
$_FILES['file']['name'] - the actual name of the uploaded file.
$_FILES['file']['size'] - the size in bytes of the uploaded file.
$_FILES['file']['type'] - the MIME type of the uploaded file.
$_FILES['file']['error'] - the error code associated with this file upload.
Example
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "/var/www/html" ) or die("Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul> //Unordered list
<li>Sent file: <?php echo $_FILES['file']['name']; ?> //list item
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes //list item
<li>File type: <?php echo $_FILES['file']['type']; ?> //list item
</ul>
</body>
</html>
PHP ─ Regular Expression
What is a Regular Expressions?
• Regular expressions are powerful pattern
matching algorithm that can be performed in
a single expression.
• Regular expressions use arithmetic operators
such as (+,-,^) to create complex expressions.
• Regular expressions help you accomplish tasks
such as validating email addresses, IP address
etc.
Why to use regular expressions
• Regular expressions simplify identifying
patterns in string data by calling a single
function.
• This saves us coding time.
– When validating user input such as email address,
domain names, telephone numbers, IP addresses,
– Highlighting keywords in search results
– When creating a custom HTML template. Regular
expressions can be used to identify the template
tags and replace them with actual data.
Types
• PHP has implemented quite a few regex functions
which uses different parsing engines.
• There are two major parser in PHP.
POSIX Regular Expressions
PERL Compatible Regular Expressions (PCRE)

• The PHP function prefix for POSIX is ereg_. Since


the release of PHP 5.3 this engine is deprecated.

• In PHP every PCRE function starts with preg_ such


as preg_match or preg_replace.
PHP's Regexp POSIX Functions
PHP offers seven functions for searching strings using POSIX-style regular expressions

Function Description

ereg() Perform regular expression match


ereg_replace() Replace regular expression

eregi() Case insensitive regular expression match.

eregi_replace() Replace regular expression case insensitive.


split() Split string into array by regular expression

spliti() Split string into array by regular expression case insensitive

sql_regcase() Make regular expression for case insensitive match


PHP's Regexp PERL Compatible Functions
• PHP functions for searching strings using Perl-compatible regular expressions

Function Description

preg_match() Perform a regular expression match

preg_match_all() Perform a global regular expression match

preg_replace() Perform a regular expression search and replace

preg_split() Split string by a regular expression

preg_grep() Return array entries that match the pattern


preg_ quote() Quote regular expression characters
Brackets
• Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.

S.No Expression Description

1 [0-9] It matches any decimal digit from 0 through 9.

2 [a-z] It matches any character from lower-case a through lowercase z.

3 [A-Z] It matches any character from uppercase A through uppercase Z.

4 [a-Z] It matches any character from lowercase a through uppercase Z.


Quantifiers
• The frequency or position of bracketed character sequences and single
characters can be denoted by a special character.

Expression Description

p+ It matches any string containing at least one p.

p* It matches any string containing zero or more p's.

p? It matches any string containing zero or one p's.

p{N} It matches any string containing a sequence of N p‘s

p{2,3} It matches any string containing a sequence of two or three p's.

p{2, } It matches any string containing a sequence of at least two p's.

p$ It matches any string with p at the end of it.

^p It matches any string with p at the beginning of it.


Quantifiers - Examples
For example, we can find a match to both "color" and "colour" by
using the following regular expression:

$regex = "colou{0,1}r";

Here, the use of the quantifier makes the 'u' optional.

The following expression can match both "color" and "colour".


$regex = "colou?r";

Since the "?" metacharacter makes the one character that it follows
optional, the regular expression finds a match with or without
the "u".
Shorthand characters
• We have shortcuts for some of the most
commonly used character sets.

The shorthand matches


\s White space characters
like space, tab and new line
\d Matches any digit (0-9)
\w Matches word characters,
including the English letters
(a-zA-Z), digits (0-9), and
underscore (_)
Example
For example, the regular expression: $regex = "/\s\w\s\d\d\d\d$/";

Searches for a pattern that matches white space, a word character, another
white space, and than 4 digits.
Let's test the expression with the following code:

$regex = "/\s\w\s\d\d\d\d/"; //pattern


$string = "bat a 1000";

if (preg_match($regex, $string, $match))


{
echo "We found a match: <i>$match[0]</i>";
}
Else
{
echo "No match!";
}
Result:
We found a match: a 1000
How to find matching strings? ( preg_match )
• preg_match is built-in PHP function, that
searches for a match to regular expressions
within strings. If it finds a match, it returns true,
otherwise it returns false.
Syntax :
• preg_match($regex, $string, $match);
– $regex - is the regular expression, and it needs to be
encompassed with slashes (/).
For example: $regex = "/exp/";
– $string - the string inside which we look for the
matching pattern.
– $match is the array that stores the first match that the
function finds (preg_match stops searching as soon as
it finds the first match).
Example
<?php // The regex here is the word 'go'.
$regex = "/go/"; // We search for a match inside the string.
$string = "you gotta give the go kart a try"; // preg_match returns true or
false.

if(preg_match($regex, $string, $match))


{
echo "We found a match to the expression: " . $match[0];
}
else
{
echo "We found no match.";
}
?>

Result:
We found a match to the expression: go
• preg_match searches for a string that matches the regular expression
($regex) in the string ($string), and the first match it finds is stored as
the first item of the $match array.

• If we change the string to something that doesn't match the


pattern, preg_match will return false.

The i modifier
• Regular expressions are by default case sensitive.
The regular expressions /chr*/ is different from /Chr*/, because the the
first expression starts with a lowercase 'c' while the second starts with
a capital 'C'.
But we can change this behavior by adding the i modifier, right after the
closing delimiter of the regular expression.
So, the regular expression:
$regex = "/Chr*/i"; will match both 'Chrome' as well as 'chrome'.
Global regular expression matching (preg_match_all)

Example :

$regex = "/reg/"; //pattern


$string = "Both regex and regexp are short for regular expression";

if(preg_match_all($regex, $string, $matches))


{
print_r($matches[0]);
}

Result:
Array
(
[0] => reg
[1] => reg
[2] => reg
)
Search and replace with preg_replace
• In order to replace strings, we use the preg_replace() function, with the
following syntax:

preg_replace($regex, $replace, $string);


$regex - the expression or pattern that we search for.
$replace - what we want the match to be replaced with.
$string - the string in which we look for the expression.

In the following example, we replace all the wrong forms of the


word 'misspelled' with the correct form.

$regex = "/miss?pp?ell?e?d/";
$replace = "misspelled";
$string = "He mispeled the word in all of his emails.";
echo preg_replace($regex, $replace, $string);

Result is:
He misspelled the word in all of his emails.
split strings by regular expressions(preg_split )
preg_split is the built-in PHP function that we use when we want to split a string by regular
expression. It has the following syntax:

preg_split($regex, $string);
$regex - the expression that we search for, and want to split at.
$string - the string in which we search for the expression.

In the following example we want to split at the comma followed by any number of spaces.

$regex = "/,\s+/";
$string = "html, css, javascript, php";
$languages = preg_split($regex, $string);
print_r($languages);

Result is:
Array
(
[0] => html
[1] => css
[2] => javascript
[3] => php
)
search for matches inside arrays(preg_grep)
preg_grep searches for matches inside arrays, and brings back an array that is
consisted only of matching items.
The syntax:
preg_grep($pattern, $array);
$array stands for the array in which we search for matching items.

In the following example, we search inside the $cars array for items that start with
't' (lower or upper case):

$models = array("Bentley", "Tesla", "Maserati", "toyota", "Subaru", "Alpha");


$output = preg_grep('/^t[a-z]+/i', $models);
print_r( $output );

Result is:
Array
(
[1] => Tesla
[3] => toyota
)

You might also like