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

What Is PHP: Rasmus Lerdorf in 1994 PHP 7.4.0 28 November

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It supports dynamic content management, session tracking, and is compatible with various databases, making it a popular choice for developers. PHP features include fast execution, ease of use, and a large supportive community, with capabilities for handling arrays, loops, and variable scopes.

Uploaded by

ihhridoy000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views24 pages

What Is PHP: Rasmus Lerdorf in 1994 PHP 7.4.0 28 November

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It supports dynamic content management, session tracking, and is compatible with various databases, making it a popular choice for developers. PHP features include fast execution, ease of use, and a large supportive community, with capabilities for handling arrays, loops, and variable scopes.

Uploaded by

ihhridoy000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

What is PHP

PHP is an open-source, interpreted, and object-oriented scripting language


that can be executed at the server-side. PHP is well suited for web
development. Therefore, it is used to develop web applications (an
application that executes on the server and generates the dynamic page.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market
in 1995. PHP 7.4.0 is the latest version of PHP, which was released on 28
November. Some important points need to be noticed about PHP are as
followed:

40.6M
795
How to find Nth Highest Salary in SQL

o PHP stands for Hypertext Preprocessor.


o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the
dynamic content of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic
web applications with MySQL database.

o It handles dynamic content, database as well as session tracking for


the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP,
and many more.
o Using PHP language, you can control the user to access some pages of
your website.
o As PHP is easy to install and set up, this is the main reason why PHP is
the best language to learn.
o PHP can handle the forms, such as - collect the data from users using
forms, save it into the database, and return useful information to the
user. For example - Registration form.

PHP Features
PHP is very popular language because of its simplicity and open source.
There are some important features of PHP given below:

Performance:

PHP script is executed much faster than those scripts which are written in
other languages such as JSP and ASP. PHP uses its own memory, so the
server workload and loading time is automatically reduced, which results in
faster processing speed and better performance.

Open Source:

PHP source code and software are freely available on the web. You can
develop all the versions of PHP according to your requirement without paying
any cost. All its components are free to download and use.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding


with it.

Embedded:

PHP code can be easily embedded within HTML tags and script.

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in other OS also.
Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or


warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains
on its value.

Web servers Support:

PHP is compatible with almost all local servers used today like Apache,
Netscape, Microsoft IIS, etc.

Security:

PHP is a secure language to develop the website. It consists of multiple


layers of security to prevent threads and malicious attacks.

Control:

Different programming languages require long script or code, whereas PHP


can do the same work in a few lines of code. It has maximum control over
the websites like you can make changes easily whenever you want.

A Helpful PHP Community:

It has a large community of developers who regularly updates


documentation, tutorials, online help, and FAQs. Learning PHP from the
communities is one of the significant benefits.

PHP echo and print Statements


We frequently use the echo statement to display the output. There are two
basic ways to get the output in PHP:

o echo
o print
echo and print are language constructs, and they never behave like a
function. Therefore, there is no requirement for parentheses. However, both
the statements can be used with or without parentheses. We can use these
statements to output variables or strings.

Difference between echo and print


echo
o echo is a statement, which is used to display the output.
o echo can be used with or without parentheses.
o echo does not return any value.
o We can pass multiple strings separated by comma (,) in echo.
o echo is faster than print statement.

print
o print is also a statement, used as an alternative to echo at many times to
display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than echo statement.

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).

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)
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be
referenced/used.

PHP has three different variable scopes:

 local
 global
 static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:

Example
Variable with global scope:

<?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>";


?>

A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:

Example
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

You can have local variables with the same name in different functions, because
local variables are only recognized by the function in which they are declared.

PHP The global Keyword


The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example
<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index].


The index holds the name of the variable. This array is also accessible from
within functions and can be used to update global variables directly.

The example above can be rewritten like this:


Example
<?php
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted. We
need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type
the variable is.
PHP automatically associates a data type to the variable, depending on its
value. Since the data types are not set in a strict sense, you can do things like
adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the data
type expected when declaring a function, and by enabling the strict
requirement, it will throw a "Fatal Error" on a type mismatch.

PHP Loops
Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost equal
code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a
certain condition is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is


true
 do...while - loops through a block of code once, and then repeats the loop
as long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

PHP foreach Loop


The foreach loop - Loops through a block of code for each element in an
array.

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.

Examples
The following example will output the values of the given array ($colors):

Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the
values by referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use
a for loop, like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use
a foreach loop, like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage
for most people.

The dimension of an array indicates the number of indices you need to


select an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).

First, take a look at the following table:

Name Stock Sold

Volvo 22 18
BMW 15 13

Saab 5 2

Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.

To get access to the elements of the $cars array we must point to the two
indices (row and column):

Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0]
[2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1]
[2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2]
[2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3]
[2].".<br>";
?>

We can also put a for loop inside another for loop to get the elements of the
$cars array (we still have to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

Compare GET vs. POST


The following table compares the two HTTP methods: GET and POST.

GET POST

BACK Harmless Data will be re-


button/Reload submitted (the
browser should
alert the user
that the data
are about to be
re-submitted)

Bookmarked Can be bookmarked Cannot be


bookmarked

Cached Can be cached Not cached

Encoding type application/x-www-form-urlencoded application/x-


www-form-
urlencoded or
multipart/form-
data. Use
multipart
encoding for
binary data

History Parameters remain in browser history Parameters are


not saved in
browser history

Restrictions on data Yes, when sending data, the GET method adds the data to the URL; No restrictions
length and the length of a URL is limited (maximum URL length is 2048
characters)

Restrictions on data Only ASCII characters allowed No restrictions.


type Binary data is
also allowed

Security GET is less secure compared to POST because data sent is part of the POST is a little
URL safer than GET
because the
Never use GET when sending passwords or other sensitive parameters are
information! not stored in
browser history
or in web
server logs

Visibility Data is visible to everyone in the URL Data is not


displayed in the
URL
PHP print_r() function
PHP print_r() is a built-in function that displays information about a variable
in a human-readable way. It shows the information stored in a variable,
which is easily understandable to the user.

There are two more functions similar to print_r() which are var_export(), and
var_dump(). They display the private and protected properties of objects.

Syntax
1. print_r (mixed $var_name, boolean $return_output)

PHP include
PHP include is used to include a file on the basis of given path. You may use
a relative or absolute path of the file.

Syntax

There are two syntaxes available for include:

1. include 'filename ';


2. Or
3. include ('filename');

PHP require
PHP require is similar to include, which is also used to include files. The only
difference is that it stops the execution of script if the file is not found
whereas include doesn't.

Syntax

There are two syntaxes available for require

1. require 'filename';
2. Or
3. require ('filename');
include only generates a warning, i.e., E_WARNING, and continue the
execution of the script.
require generates a fatal error, i.e., E_COMPILE_ERROR, and stop the
execution of the script.

PHP Call By Value


PHP allows you to call function by value and reference both. In case of PHP
call by value, actual value is not modified if it is modified inside the function.

Let's understand the concept of call by value by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is
concatenated with 'Call By Value' string. But, printing $str variable results
'Hello' only. It is because changes are done in the local variable $str2 only. It
doesn't reflect to $str variable.

1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

PHP Call By Reference


In case of PHP call by reference, actual value is modified if it is modified
inside the function. In such case, you need to use & (ampersand) symbol
with formal arguments. The & represents reference of the variable.

Let's understand the concept of call by reference by the help of examples.

Example 1
In this example, variable $str is passed to the adder function where it is
concatenated with 'Call By Reference' string. Here, printing $str variable
results 'This is Call By Reference'. It is because changes are done in the
actual variable $str.
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'This is ';
7. adder($str);
8. echo $str;
9. ?>

PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It
is used to recognize the user.

Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such
way, cookie can be received at the server side.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe".
The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie
is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:

Example
<?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


To modify a cookie, just set (again) the cookie using the setcookie() function:

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:

Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are
enabled. First, try to create a test cookie with the setcookie() function, then
count the $_COOKIE array variable:

Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

</body>
</html>

PHP Session
PHP session is used to store and pass information from one page to another
temporarily (until user close the website).

PHP session technique is widely used in shopping websites where we need to


store and pass cart information e.g. username, product code, product name,
product price etc from one page to another.

PHP session creates unique user id for each browser to recognize the user
and avoid conflict between multiple browsers.

Start a PHP Session


A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start
a new PHP session and set some session variables:

Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we
will access the session information we set on the first page
("demo_session1.php").

Notice that session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning of each
page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION
variable:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Modify a PHP Session Variable


To change a session variable, just overwrite it:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session


To remove all global session variables and destroy the session,
use session_unset() and session_destroy():

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

bsolute vs. Relative Path: Comparison Chart

extract() function
The extract() function imports variables into the local symbol table from an
array.

This function uses array keys as variable names and values as variable values.
For each element it will create a variable in the current symbol table.

This function returns the number of variables extracted on success.

Syntax
extract(array, extract_rules, prefix)

Example
Assign the values "Cat", "Dog" and "Horse" to the variables $a, $b and $c:

<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>

You might also like