In: Computer Science
Provide examples of PHP common functions - echo, print, filter_input, isset, empty, is_numeric, include, include_once, header, htmlspecialchars, nl2br, strops(), explode(), implode(), count()
• Remember the return values of filter_input()
• Remember syntax of introduced control statements, such as if, for, foreach, while, switch, break, continue, etc.
• Conceptual questions, such as
− Six data types in PHP
− Rules for variable names
− The equality operators, such as == and ===
− differences between get and post methods
− differences between include() and header()
− MVC pattern
− Goals of testing and debugging
− Three types of errors
− Two types of cookies
− Variable substitution (interpolation)
− Array, $_SESSION, $_COOKIE, prepared statement
echo(), print()
<!DOCTYPE html>
<html>
<body>
<?php
echo "echo example";
echo "Hello world!<br>";
print "print Example<br>";
print "Hello world!<br>";
?>
</body>
</html>
Output:
echo example
Hello world!
print example
Hello world!
filter_input()
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)
=== false) {
echo("Email is valid");
} else {
echo("Email is not valid");
}
INPUT_GET - Filter Type
"email" - Variable name to be filtered.
FILTER_VALIDATE_EMAIL - Filter type
RETURNS - false on failure and value of the variable on success,
NULL if the variable is not set.
isset() , empty()
<?php
$var1 = 0;
// True because $var1 is set
if (isset($var1)) {
echo "Variable 'var1' is set.<br>";
}
// True because $var1 is empty
if (empty($var1 )) {
echo "Variable 'var1 ' is
empty.<br>";
}
$var2 = null;
// False because $var2 is NULL
if (isset($var2)) {
echo "Variable 'var2' is set.";
}
?>
is_numeric()
<?php
$a = 32;
echo "a is " . is_numeric($a) . "<br>";
// RETURNS TRUE if variable is a number or a numeric string, FALSE otherwise
// Output : a is 1
?>
include , include_once
include 'filename';
Including of one php file into another we use include
include_once 'filename';
Including of one php file into another we use include_once but if the file is already included it will not include again.
header()
The header() function sends a raw HTTP header to a client.
<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
htmlspecialchars()
Convert the predefined characters "<" (less than) and ">" (greater than) to HTML entities:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
// output : This is some <b>bold</b> text.
nl2br()
Insert line breaks where newlines (\n) occur in the string:
<?php
echo nl2br("One line.\nAnother line.");
?>
Output
One line.
Another line.
strops()
Find the position of the first occurrence of "php" inside the string:
<?php
echo strpos("I love php, I love php too!","php");
?>
Output : 7
explode()
Break a string into an array:
<?php
$str = ""Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
implode()
Join array elements with a string:
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
Output : Hello World! Beautiful Day!
count()
Return the number of elements in an array:
<?php
$cars=array("car1","car2","car3");
echo count($cars);
?>
Output: 3
control statements
if
if (condition) {
code to be executed if condition is true;
}
for
for (init counter; test counter; increment counter)
{
code to be executed for each iteration;
}
foreach
foreach ($array as $value) {
code to be executed;
}
while
while (condition is true) {
code to be executed;
}
switch
switch (n) {
case label1:
code to be executed if
n=label1;
break;
case label2:
code to be executed if
n=label2;
break;
...
default:
code to be executed if n is different from all
labels;
}
break
<?php
for ($x = 0; $x < 3; $x++) {
if ($x == 1) {
break;
}
echo "The number is: $x <br>";
}
?>
Output:
The number is: 0
continue
<?php
for ($x = 0; $x < 3; $x++) {
if ($x == 1) {
continue;
}
echo "The number is: $x <br>";
}
?>
output
The number is: 0
The number is: 1
The number is: 2
PHP supports the following data types:
Rules for PHP variables:
$
sign, followed by the
name of the variable$age
and
$AGE
are two different variablesEquality Operators
$x == $y Returns true if $x is equal to $y
$x === $y Returns true if $x is equal to $y, and they are of the
same type
differences between get and post methods
GET
GET is used to request data from a specified resource.
GET requests can be cached
GET requests remain in the browser history
GET requests have length restrictions
POST
POST is used to send data to a server to create/update a
resource.
POST requests are never cached
POST requests do not remain in the browser history
POST requests have no restrictions on data length
differences between include() and header()
Header forwards the user to a new page, so PHP reinitializes, it's like a HTML meta redirection, but faster.
Include just includes the file where you call it, and it
executes it as PHP, just like if the code from homepage.php was
written where you write <?php include('homepage.php');
?>
MVC pattern
MVC stands for "Model view And Controller".
The main aim of MVC Architecture is to separate the Business logic
& Application data from the USER interface.
Model: Database operation such as fetch data or update data etc.
View: End-user GUI through which user can interact with system, i.e., HTML, CSS.
Controller: Contain Business logic and provide a link between model and view.
Goals of testing and debugging
Debugging:
Fixing Bugs
Analysis During Development
Supporting Deployed Applications
Testing:
1. Always Identifying the bugs as early as possible.
2. Preventing the bugs in a project and product.
3. Check whether the customer requirements criterion is met or not.
4. And finally main goal of testing to measure the quality of the product and project.
Three types of errors
1. Syntax Errors
2. Logic Errors.
3. Compilation Errors
Two types of cookies
Session cookies: these are temporary cookies that expire at the end of a browser session; that is, when you leave the site. Session cookies allow the website to recognize you as you navigate between pages during a single browser session and allow you to use the website most efficiently. For example, session cookies enable a website to remember that a user has placed items in an online shopping basket
Persistent cookies: in contrast to session cookies, persistent cookies are stored on your equipment between browsing sessions until expiry or deletion. They therefore enable the website to "recognize" you on your return remember your preferences and tailor services to you.
Variable substitution
Variable substitution provides a convenient way to output
variables embedded in string literals. When PHP parses
double-quoted strings, variable names are identified when a
$
character is found and the value of the variable is
substituted.
$cm = 127; $inch = $cm / 2.54; // prints "127 centimeters = 50 inches" echo "$cm centimeters = $inch inches";
Array
An array stores multiple values in one single variable:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] .
".";
?>
</body>
</html>
OUTPUT: I like Volvo, BMW and Toyota.
$_SESSION
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
$_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.
setcookie(name, value, expire, path, domain, secure, httponly);
Prepared Statement
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this: