[go: up one dir, main page]

0% found this document useful (0 votes)
5 views24 pages

php

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

PHP Introduction

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.

PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

What is PHP?

PHP is an acronym for "PHP: Hypertext Preprocessor"

PHP is a widely-used, open source scripting language

PHP scripts are executed on the server

PHP is free to download and use

What is a PHP File?

PHP files can contain text, HTML, CSS, JavaScript, and PHP code

PHP code is executed on the server, and the result is returned to the browser as plain HTML

PHP files have extension ".php"

What Can PHP Do?

PHP can generate dynamic page content

PHP can create, open, read, write, delete, and close files on the server

PHP can collect form data

PHP can send and receive cookies

PHP can add, delete, modify data in your database

PHP can be used to control user-access

PHP can encrypt data

With PHP you are not limited to output HTML. You can output images or PDF files. You can also output any
text, such as XHTML and XML.]

How to insert PHP code in HTML document using include or require keyword ?

Inserting PHP code in an HTML document involves embedding PHP scripts within HTML files. This is done
using PHP tags (`<?php … ?>`). Common methods include using include or require statements to
incorporate external PHP files, allowing dynamic content within the HTML structure.

We can insert any PHP file into the HTML code by using two keywords that are ‘Include’ and ‘Require’.

Table of Content

PHP include() function

PHP require() function


Difference between the include() function & require() function

PHP include() function:

This function is used to copy all the contents of a file called within the function, text wise into a file from
which it is called. This happens before the server executes the code.

Syntax:

include 'php filename';

Example 1: Consider a PHP file name ‘natural.php’ which contains the following code.

natural.php

<?php

$i = 1;

echo "the first 10 natural numbers are:";

for($i = 1; $i <= 10; $i++) {

echo $i;

?>

Output:

Example: Insert the above code into an HTML document by using the include keyword, as shown below.

PHP

<!DOCTYPE html>

<html>

<head>

<title>inserting PHP code into html</title>

</head>

<body>

<h2>Natural numbers</h2>

<?php include 'natural.php'?>

</body>

</html>
PHP require() function:

The require() function performs same as the include() function. It also takes the file that is required and
copies the whole code into the file from where the require() function is called.

Syntax:

require 'php filename'

Example 2: We can insert the PHP code into HTML Document by directly writing in the body tag of the
HTML document.

PHP

<!DOCTYPE html>

<html>

<head>

<title>inserting php code into html </title>

</head>

<body>

<h2>natural numbers</h2>

<?php

$i = 1;

echo"the first 10 natural numbers are:";

for($i = 1; $i <= 10; $i++) {

echo $i;

?>

</body>

</html>

Output:

natural numbers

the first 10 natural numbers are:12345678910

Example: To insert the above code into an HTML document by using the ‘require’ keyword as shown
below.

PHP
<!DOCTYPE html>

<html>

<head>

<title>inserting PHP code into html</title>

</head>

<body>

<h2>Natural numbers</h2>

<?php require 'natural.php'?>

</body>

</html>

Output:

Natural numbers

the first 10 natural numbers are:12345678910

Difference between the include() function & require() function:

Include() Function Require() Function


1. Includes a file and continues script execution 1. Stops script execution and generates a fatal error if
even if the file is not found or fails to include. the file is not found or fails to include.
2. Commonly used for optional files or modules. 2. Typically used for essential files or modules critical
for script functionality.
3. Failure to include a file results in a warning, but 3. Failure to include a file results in a fatal error,
script execution continues. halting script execution.
4. Suitable for integrating non-essential 4. Ideal for integrating essential components like
components like optional templates or modules. configuration files or libraries.
5. Less strict error handling, allowing script 5. More strict error handling, ensuring script
execution to proceed even if an included file is execution halts if a required file is missing or fails to
missing. include.
How to embed PHP code in an HTML page ?

We can use PHP in HTML code by simply adding a PHP tag without doing any extra work.

Example 1: First open the file in any editor and then write HTML code according to requirement. If we have
to add PHP code then we can add by simply adding <?php ….. ?> tags in between and add your PHP code
accordingly.

PHP

<!DOCTYPE html>
<html>

<head>

<title>PHP</title>

</head>

<body>

<h1>

<?php

echo "hii GeeksforGeeks "

?>

</h1>

</body>

</html>

Output:

Example : In this, we use PHP code in HTML document using the post method where we can pass value
in HTML form and receive in the PHP post method.

PHP

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$str = $_POST['fname'];

if (empty($str))
{
echo "String is empty";
}
else
{
?>
<h1>
<?php echo $str ?>
</h1>
<?php
}
}
?>
</body>
</html>
Output:

PHP Variable Scope

The scope of a variable is defined as its range in the program under which it can be accessed. In other
words, "The scope of a variable is the portion of the program within which it is defined and can be
accessed."

PHP has three types of variable scopes:

Local variable

Global variable

Static variable

Local variable

The variables that are declared within a function are called local variables for that function. These local
variables have their scope only in that particular function in which they are declared. This means that these
variables cannot be accessed outside the function, as they have local scope.

A variable declaration outside the function with the same name is completely different from the variable
declared inside the function. Let's understand the local variables with the help of an example:

File: local_variable1.php

<?php

function local_var()

$num = 45; //local variable


echo "Local variable declared inside the function is: ". $num;

local_var();

?>

Output:

Local variable declared inside the function is: 45

File: local_variable2.php

<?php

function mytest()

$lang = "PHP";

echo "Web development language: " .$lang;

mytest();

//using $lang (local variable) outside the function will generate an error

echo $lang;

?>

Output:

Web development language: PHP

Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28

Global variable

The global variables are the variables that are declared outside the function. These variables can be
accessed anywhere in the program. To access the global variable within a function, use the GLOBAL
keyword before the variable. However, these variables can be directly accessed or used outside the
function without any keyword. Therefore there is no need to use any keyword to access a global variable
outside the function.

Let's understand the global variables with the help of an example:

Example:

File: global_variable1.php

<?php
$name = "Sanaya Sharma"; //Global Variable

function global_var()

global $name;

echo "Variable inside the function: ". $name;

echo "</br>";

global_var();

echo "Variable outside the function: ". $name;

?>

Output:

Variable inside the function: Sanaya Sharma

Variable outside the function: Sanaya Sharma

Static variable

It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before
the variable to define a variable, and this variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:

Example:

File: static_variable.php

<?php

function static_var()

static $num1 = 3; //static variable

$num2 = 6; //Non-static variable

//increment in non-static variable

$num1++;

//increment in static variable

$num2++;
echo "Static: " .$num1 ."</br>";

echo "Non-static: " .$num2 ."</br>";

//first function call

static_var();

//second function call

static_var();

?>

Output:

Static: 4

Non-static: 7

Static: 5

Non-static: 7

You have to notice that $num1 regularly increments after each function call, whereas $num2 does
not. This is why because $num1 is not a static variable, so it freed its memory after the execution
of each function call.

PHP Variable functions

Introduction

If name of a variable has parentheses (with or without parameters in it) in front of it,
PHP parser tries to find a function whose name corresponds to value of the variable
and executes it. Such a function is called variable function. This feature is useful in
implementing callbacks, function tables etc.

Variable functions can not be built eith language constructs such as include, require,
echo etc. One can find a workaround though, using function wrappers.

Variable function example

In following example, value of a variable matches with function of name. The function
is thus called by putting parentheses in front of variable

Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Example

Live Demo

<?php

function hello(){

echo "Hello World";

$var="Hello";

$var();

?>

Output

This will produce following result. −

Hello World

Here is another example of variable function with arguments

Example

Live Demo

<?php

function add($x, $y){

echo $x+$y;

$var="add";

$var(10,20);

?>

Output

This will produce following result. −

30

In following example, name of function to called is input by user


Example

<?php

function add($x, $y){

echo $x+$y;

function sub($x, $y){

echo $x-$y;

$var=readline("enter name of function: ");

$var(10,20);

?>

Output

This will produce following result. −

enter name of function: add

30

Variable method example

Concept of variable function can be extended to method in a class

Example

<?php

class myclass{

function welcome($name){

echo "Welcome $name";

$obj=new myclass();

$f="welcome";

$obj->$f("Amar");

?>

Output
This will produce following result. −

Welcome Amar

A static method can be also called by variable method technique

Example

<?php

class myclass{

static function welcome($name){

echo "Welcome $name";

$f="welcome";

myclass::$f("Amar");

?>

Output

This will now throw exception as follows −

Welcome Amar

What is Anonymous Function in PHP ?

Anonymous Function, also known as closures, are functions in PHP that do not have a specific name and
can be defined inline wherever they are needed. They are useful for situations where a small, one-time
function is required, such as callbacks for array functions, event handling, or arguments to other functions.

Syntax:

$anonymousFunction = function($arg1, $arg2, ...) {


// Function body
};

Important Points

Anonymous functions are declared using the function keyword followed by the list of parameters and the
function body.

They can capture variables from the surrounding scope using the use keyword.
Anonymous functions can be assigned to variables, passed as arguments to other functions, or returned
from other functions.

Usage

Inline Definition: Anonymous functions can be defined directly within the code, eliminating the need for
named function declarations.

Flexibility: They can be used as callbacks or event handlers where a small, reusable function is required.

Closure Scope: Anonymous functions can access variables from the enclosing scope using the use keyword,
allowing for the encapsulation of data.

Example:

// Define and use an anonymous function


$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);

How to read each character of a string in PHP ?

A string is a sequence of characters. It may contain integers or even special symbols. Every character in a
string is stored at a unique position represented by a unique index value.

Here are some approaches to read each character of a string in PHP

Using str_split() method – The str_split() method

Using str_split() method – The str_split() method is used to split the specified string variable into an array
of values, each of which is mapped to an index value beginning with 0. This method converts the input
string into an array.

str_split(str)

PHP foreach loop iteration can then be done over the array values, each of which element belongs to a
character of the string. The values are then printed with a space in between each.

Example:

PHP

<?php

// Declaring string variable

$str = "Hi!GFG User.";


echo("Original string : ");

echo($str . "</br>");

$array = str_split($str);

echo("Characters : ");

foreach($array as $val){

echo($val . " ");

?>

Output:

Original string : Hi!GFG User.


Characters : H i ! G F G U s e r .

Cleaning a string

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)

Parameter Values

Parameter Description
string Required. Specifies the string to check
charlist Optional. Specifies which characters to remove from the string. If
omitted, all of the following characters are removed:
"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space
Example

Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

Example

Remove whitespaces from both sides of a string:

<?php
$str = "\n Hello World! \n ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>

In PHP, encoding and escaping are two important concepts that help manage how data is represented and
transmitted, especially when dealing with different formats or when outputting data to prevent issues such
as security vulnerabilities.

Encoding

Encoding refers to the process of converting data from one format to another. In PHP, this often involves
converting characters into a specific format that can be safely transmitted or stored. Common encoding
types include:

URL Encoding: Converts characters into a format that can be transmitted over the internet. For example,
spaces are encoded as %20. PHP provides functions php

[math]encoded = urlencode("Hello World!"); // "Hello+World%21"

```

- **HTML Encoding**: Converts special characters into HTML entities to prevent issues in web pages. For
example, `<` becomes `&lt;` and `>` becomes `&gt;`. PHP offers the `htmlspecialchars()` function for this
purpose.

```php

$html_encoded = htmlspecialchars("<div>Hello</div>"); // "&lt;div&gt;Hello&lt;/div&gt;"


```

- **Base64 Encoding**: Converts binary data into a textual format using a specific set of characters. This is
often used for embedding binary data in text formats. PHP provides `base64_encode()` and
`base64_decode()` for this.

```php

$base64 = base64_encode("Hello World!"); // "SGVsbG8gV29ybGQh"

```

### Escaping

**Escaping** is a technique used to prevent special characters from being interpreted in a way that could
lead to errors or security vulnerabilities, particularly in contexts like SQL queries, HTML output, or
JavaScript code.

- **String Escaping**: In PHP, you can escape special characters in strings using a backslash (`\`). For
example, to include a quote inside a string, you would escape it:

```php

$string = "He said, \"Hello!\""; // "He said, "Hello!""

```

- **SQL Escaping**: When working with databases, it’s crucial to escape user input to prevent SQL
injection attacks. PHP offers the `mysqli_real_escape_string()` function to sanitize input before using it in
SQL queries.

```php

$conn = new mysqli("localhost", "user", "pass", "database");

$user_input = $conn->real_escape_string([/math]input);

like urlencode() and urldecode() to perform this encoding.


HTML Escaping: Similar to HTML encoding, escaping in HTML prevents certain characters from being
interpreted as HTML. For example, using &amp; as &amp;amp; ensures that it displays correctly in a
browser.

Summary

Encoding transforms data into a specific format for safe transmission or storage.

Escaping protects against misinterpretation of special characters in various contexts (e.g., SQL, HTML).

Both are essential for maintaining security and integrity in web applications.

String comparison

PHP == Operator:

The comparison operator called Equal Operator is the double equal sign “==”. This operator
accepts two inputs to compare and returns a true value if both of the values are the same (It
compares the only value of the variable, not data types) and returns a false value if both of the
values are not the same.

This should always be kept in mind that the present equality operator == is different from the
assignment operator =. The assignment operator assigns the variable on the left to have a new
value as the variable on right, while the equal operator == tests for equality and returns true or
false as per the comparison results.

Example: This example describes the string comparison using the == operator.

<?php

// Declaration of strings

$name1 = "Geeks";

$name2 = "Geeks";

// Use == operator

if ($name1 == $name2) {

echo 'Both strings are equal';

else {
echo 'Both strings are not equal';

?>

Output:

Both the strings are equal

PHP strcmp() Function:

The strcmp() is an inbuilt function in PHP that is used to compare two strings. This function is
case-sensitive which points that capital and small cases will be treated differently, during
comparison. This function compares two strings and tells whether the first string is greater or
smaller or equals the second string. This function is binary-safe string comparison.

Syntax:

strcmp( $string1, $string2 )

Parameters: This function accepts two parameters as mentioned above and described below:

$string1: This parameter refers to the first string to be used in the comparison. It is a mandatory
parameter.

$string2: This parameter refers to the second string to be used in the comparison. It is a
mandatory parameter.

Return Values: The function returns a random integer value depending on the condition of the
match, which is given by:

Returns 0 if the strings are equal.

Returns a negative value (< 0), if $string2 is greater than $string1.

Returns a positive value (> 0) if $string1 is greater than $string2.

Example: This example illustrates the string comparison using the strcmp() function.

<?php

// Declaration of strings

$name1 = "Geeks";

$name2 = "geeks";

// Use strcmp() function

if (strcmp($name1, $name2) !== 0) {


echo 'Both strings are not equal';

else {

echo 'Both strings are equal';

?>

Output:

Both strings are not equal

Manipulating string:

More functions

Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you want
to remove this space.

Example

The trim() removes any whitespace from the beginning or the end:

$x = " Hello World! ";

echo trim($x);

Try it Yourself »

Learn more in our trim() Function Reference.

Convert String into Array

The PHP explode() function splits a string into an array.

The first parameter of the explode() function represents the "separator". The
"separator" specifies where to split the string.

Note: The separator is required.

Example

Split the string into an array. Use the space character as separator:

$x = "Hello World!";

$y = explode(" ", $x);


//Use the print_r() function to display the result:

print_r($y);

/*

Result:

Array ( [0] => Hello [1] => World! )

*/

PHP Regular Expressions

Regular expressions are commonly known as regex. These are nothing more than a pattern or a
sequence of characters, which describe a special search pattern as text string.

Regular expression allows you to search a specific string inside another string. Even we can
replace one string by another string and also split a string into multiple chunks. They use
arithmetic operators (+, -, ^) to create complex expressions.

By default, regular expressions are case sensitive.

Advantage and uses of Regular Expression

Regular expression is used almost everywhere in current application programming. Below some
advantages and uses of regular expressions are given:

Regular expression helps the programmers to validate text string.

It offers a powerful tool to analyze and search a pattern as well as to modify the text string.

By using regexes functions, simple and easy solutions are provided to identify the patterns.

Regexes are helpful for creating the HTML template system recognizing tags.

Regexes are widely used for browser detection, form validation, spam filtration, and password
strength checking.

It is helpful in user input validation testing like email address, mobile number, and IP address.

It helps in highlighting the special keywords in file based upon the search result or input.
Operator Description
^ It indicates the start of string.
$ It indicates the end of the string.
. It donates any single character.
() It shows a group of expressions.
[] It finds a range of characters, e.g., [abc]
means a, b, or c.
[^] It finds the characters which are not in
range, e.g., [^xyz] means NOT x, y, or z.
- It finds the range between the elements, e.g.,
[a-z] means a through z.
| It is a logical OR operator, which is used
between the elements. E.g., a|b, which means
either a OR b.
? It indicates zero or one of preceding character
or element range.
* It indicates zero or more of preceding
character or element range.
+ It indicates zero or more of preceding
character or element range.
{n} It denotes at least n times of preceding
character range. For example - n{3}
{n, } It denotes at least n, but it should not be more
than m times, e.g., n{2,5} means 2 to 5 of n.
{n, m} It indicates at least n, but it should not be
more than m times. For example - n{3,6}
means 3 to 6 of n.
\ It denotes the escape character.
Metacharacters allow us to create more complex patterns.

You can create complex search patterns by applying some basic rules of regular expressions.
Many arithmetic operators (+, -, ^) are also used by regular expressions to create complex
patterns.

Operators in Regular Expression

Special character class in Regular Expression

Special Character Description


\n It indicates a new line.
\r It indicates a carriage return.
\t It represents a tab.
\v It represents a vertical tab.
\f It represents a form feed.
\xxx It represents an octal character.
\xxh It denotes hexadecimal character hh.
PHP offers two sets of regular expression functions:

POSIX Regular Expression

PERL Style Regular Expression

POSIX Regular Expression


The structure of POSIX regular expression is similar to the typical arithmetic expression: several
operators/elements are combined together to form more complex expressions.

The simplest regular expression is one that matches a single character inside the string. For
example - "g" inside the toggle or cage string. Let's introduce some concepts being used in
POSIX regular expression:

Brackets

Brackets [] have a special meaning when they are used in regular expressions. These are used to
find the range of characters inside it.

Expression Description
[0-9] It matches any decimal digit 0 to 9.
[a-z] It matches any lowercase character from a to
z.
[A-Z] It matches any uppercase character from A to
Z.
[a-Z] It matches any character from lowercase a to
uppercase Z.
The above ranges are commonly used. You can use the range values according to your need, like
[0-6] to match any decimal digit from 0 to 6.

Quantifiers

A special character can represent the position of bracketed character sequences and single characters.
Every special character has a specific meaning. The given symbols +, *, ?, $, and {int range} flags all follow a
character sequence.

Expression Description
p+ It matches any string that contains atleast one p.
p* It matches any string that contains one or more
p's.
p? It matches any string that has zero or one p's.
p{N} It matches any string that has a sequence of N p's.
p{2,3} It matches any string that has a sequence of two
or three p's.
p{2, } It matches any string that contains atleast two p's.
p$ It matches any string that contains p at the end of
it.
^p It matches any string that has p at the start of it.
PHP Regexp POSIX Function

PHP provides seven functions to search strings using POSIX-style regular expression -

Function Description
ereg() It searches a string pattern inside another string
and returns true if the pattern matches otherwise
return false.
ereg_replace() It searches a string pattern inside the other string
and replaces the matching text with the
replacement string.
eregi() It searches for a pattern inside the other string
and returns the length of matched string if found
otherwise returns false. It is a case
insensitive function.
eregi_replace() This function works same
as ereg_replace() function. The only difference is
that the search for pattern of this function is case
insensitive.
split() The split() function divide the string into array.
spliti() It is similar to split() function as it also divides a
string into array by regular expression.
Sql_regcase() It creates a regular expression for case insensitive
match and returns a valid regular expression that
will match string.
Note: Note that the above functions were deprecated in PHP 5.3.0 and removed in PHP 7.0.0.

Metacharacters

A metacharacter is an alphabetical character followed by a backslash that gives a special meaning to the
combination.

For example - '\d' metacharacter can be used search large money sums: /([\d]+)000/. Here /d will search
the string of numerical character.

Below is the list of metacharacters that can be used in PERL Style Regular Expressions -

Character Description
. Matches a single character
\s It matches a whitespace character like space,
newline, tab.
\S Non-whitespace character
\d It matches any digit from 0 to 9.
\D Matches a non-digit character.
\w Matches for a word character such as - a-z, A-Z, 0-
9, _
\W Matches a non-word character.
[aeiou] It matches any single character in the given set.
[^aeiou] It matches any single character except the given
set.
(foo|baz|bar) Matches any of the alternatives specified.
Modifiers

There are several modifiers available, which makes the work much easier with a regular expression. For
example - case-sensitivity or searching in multiple lines, etc.

Below is the list of modifiers used in PERL Style Regular Expressions -

Character Description
i Makes case insensitive search
m It specifies that if a string has a carriage return or
newline characters, the $ and ^ operator will
match against a newline boundary rather than a
string boundary.
o Evaluates the expression only once
s It allows the use of .(dot) to match a newline
character
x This modifier allows us to use whitespace in
expression for clarity.
g It globally searches all matches.
cg It allows the search to continue even after the
global match fails.
PHP Regexp POSIX Function

PHP currently provides seven functions to search strings using POSIX-style regular expression -

Function Description
preg_match() This function searches the pattern
inside the string and returns true if
the pattern exists otherwise
returns false.
preg_match_all() This function matches all the
occurrences of pattern in the string.
preg_replace() The preg_replace() function is similar
to the ereg_replace() function, except
that the regular expressions can be
used in search and replace.
preg_split() This function exactly works like split()
function except the condition is that it
accepts regular expression as an input
parameter for pattern. Mainly it
divides the string by a regular
expression.
preg_grep() The preg_grep() function finds all the
elements of input_array and returns
the array elements matched with
regexp (relational expression) pattern.
preg_quote() Quote the regular expression
characters.

You might also like