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

PHP-Chapter-4-١

PHP-Chapter-4

Uploaded by

taj200153
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

PHP-Chapter-4-١

PHP-Chapter-4

Uploaded by

taj200153
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Web Applications

Development
ITSE 3302
‫تطوير تطبيقات الشبكة العالمية‬
Dr. Moamar Elyazgi
PHP Language

Chapter 4
PHP
Strings, Web Concepts and
GET and POST Methods
4.1 Strings

 A string is series of characters, where a character is the same as a byte.


 This means that PHP only supports a 256-character set, and hence does not
offer native Unicode support.
 As of PHP 7.0.0, there are no particular restrictions regarding the length of a
string on 64-bit builds.
 On 32-bit builds and in earlier versions, a string can be as large as up to 2GB
(2147483647 bytes maximum).
3
4.1 Strings
 A string literal can be specified in
 Single Quoted
 The simplest way to specify a string is to enclose it in single quotes (the
character ‘).
 To specify a literal single quote, escape it with a backslash (\).
 To specify a literal backslash, double it (\\).
 All other instances of backslash will be treated as a literal backslash: this
means that the other escape sequences you might be used to, such as \r or \n,
4
will be output literally as specified rather than having any special meaning.
4.1 Strings
 Single Quoted Exmple: // Outputs: You deleted C:\*.*?
<?php echo 'You deleted C:\*.*?';
echo 'this is a simple string'; // Outputs: This will not expand: \n a
echo 'You can also have embedded newline
newlines in echo 'This will not expand: \n a
strings this way as it is newline';
okay to do'; // Outputs: Variables do not $expand
// Outputs: Arnold once said: "I'll be $either
back" echo 'Variables do not $expand
echo 'Arnold once said: "I\'ll be back"'; $either';
// Outputs: You deleted C:\*.*? ?>
5
echo 'You deleted C:\\*.*?';
4.1 Strings

 Double Quoted
 You can also use double quotation marks (").
 However, single and double quotation marks work in different ways.
 Strings enclosed in single-quotes are treated almost literally, whereas the
strings delimited by the double quotes replaces variables with the string
representations of their values as well as specially interpreting certain escape
sequences.
6
4.1 Strings
 To include a literal string in your PHP script, simply enclose the string in:
 Single quotes — e.g. 'Hello there!', or
 Double quotes — e.g. "Hello there!".
 If you use single quotes then PHP reads the string exactly as you typed it. Double
quotes work in a similar way, but a couple of extra features also come into play:
 Variable parsing: Variable names within the string are replaced with the
corresponding variable values
 Character escaping: You can use escape sequences to include special characters
7
in the string
4.1 Strings
<? <!DOCTYPE html>
<html lang="en">
$variable = "name";
<head>
$literally = 'My $variable will not print!\\n'; <title>PHP Single and Double Quoted
print($literally); Strings</title>
$literally = "My $variable will print!\\n"; </head>
print($literally); <body>
<?php
?>
$my_str = 'World';
My $variable will not echo "Hello, $my_str!<br>";
print!\n echo 'Hello, $my_str!<br>';
My name will print echo '<pre>Hello\tWorld!</pre>';
echo "<pre>Hello\tWorld!</pre>";
Hello, World!
echo 'I\'ll be back';
Hello, $my_str!
Hello\tWorld!
?>
Hello World! </body>
I'll be back </html 8
4.1.1 String Concatenation Operator
 To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
Hello World 1234
$string2="1234"; empty space
echo $string1 . " " . $string2;
?>

 we used the concatenation operator two times. This is because we had to insert a
third string.
 Between the two string variables we added a string with a single character, an
empty space, to separate the two variables. 9
‫‪4.1.1 More String Operator‬‬
‫ً‬
‫طويال‪ ،‬فقد قسمناها إلى قسمين‪ ،‬لنأخذ فكرة ً عن محتواهما‪:‬‬ ‫ول ّما كان الحديث عن السالسل النصيّة يحتاج شر ًحا‬
‫القسم األول‪:‬‬
‫‪.1‬إنشاء والوصول إلى السالسل النصية باستخدام ‪ $‬و {}‪ ،‬واستخدام الدالة )(‪.strlen‬‬
‫‪.2‬البحث في السالسل النصية باستعمال الدوال‪:‬‬
‫‪strstr().1‬‬
‫‪ strpos() .2‬و )(‪strrpos‬‬
‫‪substr_count().3‬‬
‫‪strpbrk().4‬‬
‫‪.3‬االستبدال في السالسل النصية باستخدام الدوال‪:‬‬
‫‪str_replace() .1‬‬
‫‪substr_replace ().2‬‬
‫‪Strtr().3‬‬
‫‪.4‬التعامل مع حاالت الحروف الكبيرة ( )‪ uppercase‬والصغيرة )‪ )lowercase‬باستخدام الدوال‪:‬‬
‫‪strtolower().1‬‬
‫‪strtoupper().2‬‬
‫‪ucfirst().3‬‬
‫‪lcfirst().4‬‬
‫‪10‬‬
‫‪ucword().5‬‬
‫‪ .5‬النسخ غير الحساسة لحالة األحرف لجميع الدوال السابقة‪.‬‬
‫‪4.1.1 More String Operators‬‬
‫القسم الثاني‪:‬‬
‫‪.1‬تنسيق السالسل النصية باستخدام )(‪ ،printf‬بما في ذلك تعيين دقة األرقام العشرية‪.‬‬
‫‪.2‬إزالة الفراغات ( )‪trimming‬من أطراف السالسل النصية باستعمال الدوال‪:‬‬
‫‪trim() .1‬‬
‫‪ltrim().2‬‬
‫‪rtrim().3‬‬

‫‪.3‬إضافة حواشي )‪ )paddings‬للنصوص باستعمال الدوال‪:‬‬


‫‪str_pad().1‬‬
‫‪str_pad_right.2‬‬
‫‪str_pad_left.3‬‬
‫‪str_pad_both.4‬‬

‫‪.4‬التفاف ( )‪wrapping‬النصوص عبر استعمال الدالة ‪wordwrap().‬‬


‫‪.5‬تنسيق األرقام باستخدام الدالة ‪number_format().‬‬ ‫‪11‬‬
‫‪.6‬الوقت والتاريخ‪.‬‬
4.1.2 Getting Length of a String
 PHP has a predefined function to get the length of a string. Strlen() displays the length of
any string.
 It is more commonly used in validating input fields where the user is limited to enter a
fixed length of characters.
 The length of a string is often used in loops or other functions, when it is important to
know when the string ends. (i.e. in a loop, we would want to stop the loop after the last
character in the string).

<?php
echo strlen(‘Welcome to Cloudways’); 20
?> 12
4.1.3 Searching for the First Occurrence of a String
 The strstr() function is a built-in function in PHP.
 It searches for the first occurrence of a string inside another string and displays the
portion of the latter starting from the first occurrence of the former in the latter (before if
specified). This function is case-sensitive.
<html>
<body>
<?php Syntax
echo strstr("Hello world!","world"); strstr(string,search,before_search)
?>
</body>
</html> world!
13
4.1.3 Searching for the First Occurrence of a String
 The stristr() function searches for the first occurrence of a string inside another
string.
 This function is binary-safe.
 This function is case-insensitive. For a case-sensitive search, use strstr() function.
<html>
<body>
<?php Syntax
echo stristr("Hello stristr(string,search,before_search)
world!","WORLD");
?>
</body> world!
</html> 14
4.1.4 Counting the number of times a substring occurs in a given string

 The substr_count() is a built-in function in PHP and is used to count the number of times
a substring occurs in a given string.
 The function also provides us with an option to search for the given substring in a given
range of the index.
 It is case sensitive, i.e., “abc” substring is not present in the string “Abcab”.

<html>
<body>
Syntax
<?php substr_count($string, $substring, $start, $length)
echo substr_count("Hello world. The world is
nice","world");
?>
</body> 2 15
</html>
4.1.4 Counting the number of times a substring occurs in a given string

<html>
<body>
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length 12
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the 2
string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
2
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice" 1
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
0
</body>
</html>
16
4.1.5 Counting of the NUMBER OF Words in a String
 Another function which enables display of the number of words in any
specific string is str_word_count(). This function is also useful in validation
of input fields.
Syntax
Str_word_count(string)

<?php
3
echo str_word_count(‘Welcome to Cloudways’);
?> 17
4.1.6 Finding Text Within a String
 Strpos() enables searching particular <?php
$mystring = 'abc';
text within a string. It works simply $findme = 'a';
by matching the specific text in a $pos = strpos($mystring, $findme);
if ($pos === false) {
string. If found, then it returns the echo "The string '$findme' was not found in
the string '$mystring'";
specific position. If not found at all,
} else {
then it will return “False”. Strops() echo "The string '$findme' was found in the
string '$mystring'";
is most commonly used in echo " and exists at position $pos";
validating input fields like email. }
?>
 Syntax
The string 'a' was found in the string 'abc' and exists at
18
Strpos(string,text); position 0
4.1.7 Replacing Text within a String
 The str_replace() replaces all occurrences of the search text within the
replacement string.
Syntax
Str_replace(string to be replaced,text,string);
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
echo str_replace("facts", "truth", $my_str);
?>

If the truth do not fit the theory, change the truth. 19


4.1.8 Converting Lowercase into Title Case
 ucwords() function converts the first character of each word in a string to
uppercase. Note: This function is binary-safe.
 Related functions: ucfirst() - converts the first character of a string to
uppercase.
<html> Syntax
<body>
<?php ucwords(string);
echo ucwords("hello world");
?> Hello World
</body>
</html> 20
4.1.9 Converting whole String to Lowercase
 Strtolower() is used to convert a string into lowercase.
Syntax
Strtolower(string);
<?php
echo strtolower("WELCOME TO CLOUDWAYS");
?>

welcome to cloudways

21
4.1.10 Comparing between Strings
 Strcmp(string1,string2) — Binary safe string comparison. Note that this
comparison is case sensitive.
Syntax
Strcmp(string1,string2);
<?php
$var1 = "Hello"; $var1 is not equal to $var2 in a case sensitive string comparison
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
22
?>
4.1.11 Displaying a part of String
<?php
 Displaying part of
echo substr('abcdef', 1); // bcdef
String. Through echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
substr() function you echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
can display or extract a
// Accessing single characters in a string
string from a particular // can also be achieved using "square brackets"
$string = 'abcdef';
position. echo $string[0]; // a
echo $string[3]; // d
 Syntax
echo $string[strlen($string)-1]; // f
substr(string,start,length); ?>
23
4.1.12 Removing Whitespace (Trimming)
 The trim() function removes whitespace and other predefined
characters from both sides of a string.
 Related functions: ltrim() - Removes whitespace or other predefined
characters from the left side of a string.
 rtrim() - Removes whitespace or other predefined characters from the
right side of a string.
 Syntax
trim(string,charlist) 24
4.1.12 Removing Whitespace (Trimming)
<?php
$str = " Hello World! ";
echo "Without trim: " . $str; Without trim: Hello World!
With trim: Hello World!
echo "<br>";
echo "With trim: " . trim($str);
?>

<?php
$str = "\n\n\nHello World!\n\n\n";
echo "Without trim: " . $str; Without trim: Hello World!
echo "<br>"; With trim: Hello World!
echo "With trim: " . trim($str);
?> 25
4.1.13 Padding a String to a New Length
 The str_pad() function is used to pad a string to a new length. It
returns the padded string.

 Syntax
str_pad(str, len, pad_str, pad_type)
 Parameters
 str − The string to pad
 len − The new string length
 pad_str − The string to use for padding
 pad_type − The side to pad the string.
26
4.1.13 Padding a String to a New Length
 The following are the possible values −
 STR_PAD_BOTH − Pad to both sides of the string. If not an even
number, the right side gets the extra padding
 STR_PAD_LEFT − Pad to the left side of the string
 STR_PAD_RIGHT − Pad to the right side of the string.
 Return
 The str_pad() function returns the padded string.

27
4.1.13 Padding a String to a New Length
<?php
$s = "Welcome"; $$$Welcome
echo str_pad($s,10,"$",STR_PAD_LEFT);
?>

<?php
$s = "Welcome"; Welcome$$$
echo str_pad($s,10,"$",STR_PAD_RIGHT);
?>

<?php
$s = "Welcome"; $Welcome$$
echo str_pad($s,10,"$",STR_PAD_BOTH);
?>
28
4.2 Web Concepts and PHP Form Handling
If you are already familiar with the terms TCP/IP, HTTP, Web servers, Web
clients, HTML, URL, Intranet, and Internet, and you know how information is
stored and transmitted over the Web, you don't need to read this section.
Storing, locating, and transmitting information on the Web

29
4.2 Web Concepts and PHP Form Handling
 This section demonstrated how the client browser can be redirected.
 One of the most powerful features of PHP is the way it handles HTML forms.
 The basic concept that is important to understand is that any form element will
automatically be available to your PHP scripts.
 There is nothing special about this form. It is a straight HTML form with no special tags
of any kind. When the user fills in this form and hits the submit button.

 Form data is submitted to the PHP file for processing using POST here.
 Other methods you may use instead of POST is GET and REQUEST.
 In a moment we will see differences between those three methods 30
4.2.1 GET vs POST vs REQUEST
 Both GET, POST and REQUEST are treated as $_GET, $_POST and $_REQUEST.
 All of these are superglobals, i.e. automatically global variables. So, they can be accessed
throughout a script, including within functions or methods, without declaring them explicitly as
global $variable;.
 $_GET is an associative array of variables passed to the current script via the URL parameters.
 $_POST is an associative array of variables passed to the current script via the HTTP POST
method.
 $_REQUEST is also an associative array. Since it contains the contents of $_GET.
 The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
31

 The error can be avoided by using the isset() function.


4.2.2 A Simple HTML Form with Post
The example below displays a simple HTML form When the user fills out the form above and clicks the
with two input fields and a submit button: submit button, the form data is sent for processing to
a PHP file named "welcome.php".
<!DOCTYPE HTML>
<html> The form data is sent with the HTTP POST method.
<body> To display the submitted data you could simply echo
<form action="welcome.php" method="post"> all the variables. The "welcome.php" looks like this:
Name: <input type="text" name="name"><br>
<html>
E-mail: <input type="text" name="email"><br>
<body>
<input type="submit">
</form>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo
</body>
$_POST["email"]; ?>
</html>
</body>
32
</html>
4.2.3 A Simple HTML Form with Get
The same result could also be achieved using the and "welcome_get.php" looks like this:
HTTP GET method: <html>
<body>
<!DOCTYPE HTML>
<html>
Welcome <?php echo $_GET["name"]; ?><br>
<body>
Your email address is: <?php echo
$_GET["email"]; ?>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
</body>
E-mail: <input type="text" name="email"><br>
</html>
<input type="submit">
</form>
The code above is quite simple. However,
</body> the most important thing is missing. You
</html> need to validate form data to protect
your script from malicious code.
33
4.2.4 A Simple HTML Form with Request
<!DOCTYPE html> PHP $_REQUEST is a PHP super
<html> global variable which is used to
<body> collect data after submitting an
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> HTML form.
Name: <input type="text" name="fname">
<input type="submit">
</form>
The example shows a form with an input field
<?php
and a submit button. When a user submits the
if ($_SERVER["REQUEST_METHOD"] == "POST") {
data by clicking on "Submit", the form data is
// collect value of input field
sent to the file specified in the action attribute
$name = htmlspecialchars($_REQUEST['fname']);
of the <form> tag.
if (empty($name)) {
In this example, we point to this file itself for
echo "Name is empty";
processing form data. If you wish to use
} else {
another PHP file to process form data, replace
echo $name;
that with the filename of your choice. Then, we
}
can use the super global variable $_REQUEST to
}
collect the value of the input field:
?>
</body> 34
</html>
4.2.5 Example A: Validate Form Data With PHP - 1
function test_input($data) {
<!DOCTYPE HTML> $data = trim($data);
<html> $data = stripslashes($data);
<head> $data = htmlspecialchars($data);
</head> return $data;
<body> }
?>
<?php <h2>PHP Form Validation Example</h2>
// define variables and set to empty values <form method="post" action="<?php echo
$name = $email = $gender = $comment = $website = ""; htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
if ($_SERVER["REQUEST_METHOD"] == "POST") { <br><br>
$name = test_input($_POST["name"]); E-mail: <input type="text" name="email">
$email = test_input($_POST["email"]); <br><br>
$website = test_input($_POST["website"]); Website: <input type="text" name="website">
$comment = test_input($_POST["comment"]); <br><br>
$gender = test_input($_POST["gender"]); Comment: <textarea name="comment" rows="5"
} cols="40"></textarea>
35
<br><br>
4.2.5 Example A: Validate Form Data With PHP - 2
Gender:
<input type="radio" name="gender" value="female">Female echo $comment;
<input type="radio" name="gender" value="male">Male echo "<br>";
<input type="radio" name="gender" value="other">Other echo $gender;
<br><br> ?>
<input type="submit" name="submit" value="Submit">
</form> </body>
</html>
<?php
echo "<h2>Your Input:</h2>"; Notice that at the start of the script, we check
echo $name; whether the form has been submitted using
echo "<br>"; $_SERVER["REQUEST_METHOD"]. If the
echo $email; REQUEST_METHOD is POST, then the form has
echo "<br>"; been submitted - and it should be validated. If it
echo $website; has not been submitted, skip the validation and
echo "<br>"; display a blank form.
However, in the example above, all input fields are
optional. The script works fine even if the user
36
does not enter any data.
4.2.6 Example B: Complete Form - 1
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required"; 37
4.2.6 Example B: Complete Form - 2
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
38
4.2.6 Example B: Complete Form - 3
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows
dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
} 39
4.2.6 Example B: Complete Form - 4
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

40
4.2.6 Example B: Complete Form - 5
<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" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></te
xtarea>
<br><br>
41
4.2.6 Example B: Complete Form - 6
Gender:
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="other") echo "checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email; 42
4.2.6 Example B: Complete Form - 7
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>"; In example B, to show the values in the input fields after the user hits
echo $gender; the submit button, we add a little PHP script inside the value attribute
?> of the following input fields: name, email, and website. In the
comment textarea field, we put the script between the <textarea> and
</body>
</textarea> tags. The little script outputs the value of the $name,
</html>
$email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For
this, we must manipulate the checked attribute (not the value attribute
for radio buttons):

43
44

You might also like