Question

In: Computer Science

Provide examples of PHP common functions - echo, print, filter_input, isset, empty, is_numeric, include, include_once, header,...

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

Solutions

Expert Solution

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 &lt;b&gt;bold&lt;/b&gt; 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:

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • 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

Equality 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:

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
  2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
  3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values

Related Solutions

Can you provide with examples of these PHP common functions - echo, print, filter_input, isset, empty,...
Can you provide with examples of these PHP common functions - echo, print, filter_input, isset, empty, is_numeric, include, include_once, header, htmlspecialchars, nl2br, strops(), explode(), implode(), count()
**C++ program** Please provide a header file(bubble_sort.h) and a program file(bubble_sort.cpp). Also include notes to explain...
**C++ program** Please provide a header file(bubble_sort.h) and a program file(bubble_sort.cpp). Also include notes to explain code and output screenshots. Please use Bubble Sort code provided. Write a program for sorting a list of integers in ascending order using the bubble sort algorithm. Requirements Implement the following functions: Implement a function called readData int readData( int *arr) arr is a pointer for storing the integers. The function returns the number of integers. The function readData reads the list of integers...
Provide two examples of social institutions that are prevalent in American society and explain their functions.
Provide two examples of social institutions that are prevalent in American society and explain their functions.
List, explain, and provide examples of 5 common errors in human inquiry.
List, explain, and provide examples of 5 common errors in human inquiry.
Discuss and provide examples of at least four derivative securities. Be sure to include the pros...
Discuss and provide examples of at least four derivative securities. Be sure to include the pros and cons of each one.
what are the major functions of management ? provide specific examples to support your main point.
what are the major functions of management ? provide specific examples to support your main point.
What are endocrine disrupters and what are their functions in our body? Provide some examples. How...
What are endocrine disrupters and what are their functions in our body? Provide some examples. How does concentration of glucose effect insulin secretion?
Compare and contrast a free trade area and a common market. Provide examples. Be specific with...
Compare and contrast a free trade area and a common market. Provide examples. Be specific with your examples. Also describe the necessary terms.
What is a solid solution and what are the common types encountered in metals? Provide examples...
What is a solid solution and what are the common types encountered in metals? Provide examples of common engineering alloys for each type (e.g. steel). Explain how a solid solution can help raise the strength of a metal. List some of the other methods of strengthening metals.
What types of information can the visual display of data provide to researchers? Include examples to...
What types of information can the visual display of data provide to researchers? Include examples to support your response.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT