Unit - 4 PHP
Unit - 4 PHP
Unit - 4 PHP
<?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>";
?>
PHP The global Keyword PHP also stores all global variables in an
The global keyword is used to access a global array called $GLOBALS[index]. The index
variable from within a function. holds the name of the variable.
<?php <?php
$x = 5; $x = 5;
$y = 10; $y = 10;
myTest(); myTest();
echo $y; // outputs 15 echo $y; // outputs 15
?> ?>
Local Scope Variables
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it
can be used in expressions. echo can take multiple parameters (although such usage is
rare) while print can take one argument. echo is marginally faster than print
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
PHP Data Types
Variables can store data of different types, and different data types can
do different things.
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither
red, blue, nor green!";
}
?>
while (condition is true) { do {
code to be executed; code to be executed;
} } while (condition is true);
<?php <?php
$x = 1; $x = 1;
while($x <= 5) do {
{ echo "The number is: $x <br>";
echo "The number is: $x $x++;
<br>"; } while ($x <= 5);
$x++; ?>
}
?>
for (init counter; test counter;
increment counter) { foreach ($array as $value) {
code to be executed for each code to be executed;
iteration; }
}
<?php
<?php
$colors
for ($x = 0; $x <= 10; $x++) {
= array("red","green","blue",
echo "The number is: $x
"yellow");
<br>";
}
foreach ($colors as $value) {
?>
echo "$value <br>";
}
?>
PHP Functions
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from
within a script, to perform a specific task.
birthyear("Hege","1975");
<?php birthyear("Stale","1978");
function writeMsg() { birthyear("Kai Jim","1983");
echo "Hello world!"; ?>
}
writeMsg();
// call the function
?>
PHP is a Loosely Typed Language
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when
declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type
mismatches.
<?php declare(strict_types=1);
// strict requirement
function addNumbers(float $a, float $b) : float
{
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
PHP Arrays
In PHP, the array() function is used to create an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
or
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
<?php <?php
$cars $age
= array("Volvo", "BMW", "Toyota"); = array("Ben"=>"37", "Peter"=
sort($cars); >"35", "Joe"=>"43");
?> asort($age);
?>
PHP Strings
implode(separator,array) $arr = array('Hello','World!','Beautiful','Day!');
Returns a string from elements of an echo implode(" ",$arr);
array //Hello World! Beautiful Day!
str_split(string,length) $arr=str_split("Hello");
//length-optional for($x = 0; $x <count($arr); $x++) {
splits a string into an array. echo $arr[$x];
echo "<br>";
}
Both GET and POST are treated as $_GET and $_POST. These are
superglobals, which means that they are always accessible, regardless
of scope - and you can access them from any function, class or file
without having to do anything special.
$_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.
GET POST
Can be bookmarked Cannot be bookmarked
Parameters remain in browser history Parameters are not saved in browser history
When sending data, the GET method adds No restrictions
the data to the URL; and the length of a URL
is limited
GET is less secure compared to POST POST is a little safer than GET because the
because data sent is part of the URL parameters are not stored in browser
history or in web server logs
Never use GET when sending passwords or
other sensitive information!
Data is visible to everyone in the URL Data is not displayed in the URL
<html> welcome_get.php
<body>
<html>
<form action="welcome_get.php <body>
" method="get">
Name: <input type="text" name Welcome <?php echo $_GET["name"]; ?
="name"><br> ><br>
E- Your email address is: <?php echo
mail: <input type="text" name $_GET["email"]; ?>
="email"><br>
<input type="submit"> </body>
</form> </html>
</body>
</html>
PHP Regular Expressions
What is a Regular Expression?
• A regular expression is a sequence of characters that forms a search
pattern. When you search for data in a text, you can use this search
pattern to describe what you are searching for.
• A regular expression can be a single character, or a more complicated
pattern.
• Regular expressions can be used to perform all types of text search
and text replace operations.
Syntax
In PHP, regular expressions are strings composed of delimiters, a
pattern and optional modifiers.
$exp = "/welcome/i";
Regular Expression Functions
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string,
which may also be 0
<?php
$str = "The rain in SPAIN falls mainly on the
plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
Output: 4
Regular Expression Modifiers-Modifiers can change how a search is performed.
Modifier Description
i Performs a case-insensitive search
m Performs a multiline search
u Enables correct matching of UTF-8 encoded patterns
Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Metacharacters
Metacharacters are characters with a special meaning
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|
fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at the end
of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers Quantifiers define quantities
Quantifier Description
if(isset($_POST["submit-btn"]))
{
$cleandata=cleaninput($_POST);
$errormsg=validateinput($cleandata);
}
<form action="sample1.php" method="post">
<div>
<label> Enter name:</label>
<input type="text" name="usr">
<div style="color:red;"><?php echo $errormsg["usr"]; ?></div>
</div>
<div>
<label>Enter Email:</label>
<input type="text" name="email">
<div style="color:red;"><?php echo $errormsg["email"]; ?></div>
</div>
<div>
<label>Enter password:</label>
<input type="password" name="pwd">
<div style="color:red;"><?php echo $errormsg["pwd"]; ?></div>
</div>
</form>
function validateinput($cleandata)
{
$error=array();
foreach($cleandata as $key=>$value){
switch($key){
case "usr":
if(empty($value))
$error["usr"]="*Name cannot be empty";
break;
case "email":
if(!filter_var($value,FILTER_VALIDATE_EMAIL))
$error["email"]="*email is not valid";
break;
case "pwd":
$pattern="/\d+$/i";
if(preg_match($value,$pattern)==0)
$error["pwd"]="*Password should have atleast one number";
break;}}
return $error;
}
PHP- MYSQL database Connectivity
PHP 5 and later can work with a MySQL database using:
•MySQLi extension (the "i" stands for improved)
•PDO (PHP Data Objects)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Connecting with Database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
Creating Table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
Inserting data in the table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
Selecting data
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";}
Where clause
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not
set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Modify a Cookie Value
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>