Tuty
Tuty
Tuty
applications.[3] It was created by Taylor Otwell and intended for the development of web
applications following the model–view–controller (MVC) architectural pattern and based
on Symfony. Some of the features of Laravel include modular packaging system with a
dedicated dependency manager, different ways for accessing relational databases,
utilities that aid in application deployment and maintenance, and its orientation
toward syntactic sugar.[4][5]: 2, 5–9 [6][7]
The source code of Laravel is hosted on GitHub and licensed under the terms of MIT
License.[8]
History
[edit]
Taylor Otwell created Laravel as an attempt to provide a more advanced alternative to
the CodeIgniter framework, which did not provide certain features such as built-in
support for user authentication and authorization. Laravel's first beta release was made
available on June 9, 2011, followed by the Laravel 1 release later in the same month.
Laravel 1 included built-in support for
authentication, localisation, models, views, sessions, routing and other mechanisms, but
lacked support for controllers that prevented it from being a true MVC framework.[1]
Laravel 2 was released in September 2011, bringing various improvements from the
author and community. Major new features included the support for controllers, which
made Laravel 2 a fully MVC-compliant framework, built-in support for the inversion of
control (IoC) principle, and a templating system called Blade. As a downside, support for
third-party packages was removed in Laravel 2.[1]
Laravel 3 was released in February 2012 with a set of new features including
the cmd command-line interface (CLI) named Artisan, built-in support for more database
management systems, database migrations as a form of version control for database
layouts, support for handling events, and a packaging system called Bundles. An
increase of Laravel's userbase and popularity lined up with the release of Laravel 3.[1]
Laravel 4, codenamed Illuminate, was released in May 2013. It was made as a complete
rewrite of the Laravel framework, migrating its layout into a set of separate packages
distributed through Composer, which serves as an application-level package manager.
Such a layout improved the extensibility of Laravel 4, which was paired with its official
regular release schedule spanning six months between minor point releases. Other new
features in the Laravel 4 release include database seeding for the initial population of
databases, support for message queues, built-in support for sending different types of
email, and support for delayed deletion of database records called soft deletion.[1][9]: 18–19
Laravel 5 was released in February 2015 as a result of internal changes that ended up in
renumbering the then-future Laravel 4.3 release. New features in the Laravel 5 release
include support for scheduling periodically executed tasks through a package
called Scheduler, an abstraction layer called Flysystem that allows remote storage to be
used in the same way as local file systems, improved handling of package assets
through Elixir, and simplified externally handled authentication through the
optional Socialite package. Laravel 5 also introduced a new internal directory
tree structure for developed applications.[5]: 13–14 [10]
Lumen 5.0 is the initial release of the Lumen framework, a light derivative of Laravel
optimized for speed.[11] This initial release is based on the Laravel 5.x series of PHP
components, and following versions reflect the Laravel versions with which it shares
common infrastructure.[12] As of 2022, authors no longer recommend the use of Lumen
for gaining these advantages, and promote Laravel Octane instead.[13]
Laravel 5.1, released in June 2015, was the first release of Laravel to receive long-term
support (LTS). New LTS versions were planned for one every two years.[14]
Laravel 5.3 was released on August 23, 2016. The new features in 5.3 are focused on
improving developer speed by adding additional out of the box improvements for
common tasks.[15]
Laravel 5.4 was released on January 24, 2017, with many new features like Laravel
Dusk, Laravel Mix, Blade Components and Slots, Markdown Emails, Automatic Facades,
Route Improvements, Higher Order Messaging for Collections, and many others.[16]
Laravel 7 was released on March 3, 2020, with new features like Laravel Sanctum,
Custom Eloquent Casts, Blade Component Tags, Fluent String Operations and Route
Model Binding Improvements.[18]
Laravel 8 was released on September 8, 2020, with new features like Laravel Jetstream,
model factory classes, migration squashing, Tailwind CSS for pagination views and other
usability improvements.[19]
Laravel 11 was released on March 12, 2024. It was announced on the Laravel blog and
other social media, it was also discussed in detail at Laracon EU in Amsterdam on 5–6
February.[21] Along with Laravel 11, a first-party websocket server called Laravel Reverb
was released.
1. Origin of PHP
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used
to manage dynamic content, databases, session tracking, even build entire
ecommerce sites.
PHP supports a large number of major protocols such as POP3, IMAP, and
LDAP. PHP4 added support for Java and distributed object architectures
(COM and CORBA), making n-tier development a possibility for the first t.
The same PHP code runs unaltered on different Web servers and different
operation systems.
PHP runs on UNIX, Windows 98, Windows NT, and the Macintosh. PHP is
designed to integrate with the Apache Web Server.
Apache, another free technology, is the most popular Web server on the
Internet and comes with source code for UNIX and Windows. Commercial
flavors of Apache like Web Ten and Stronghold support PHP, too.
But PHP works with other Web servers, including Microsoft's Internet
Information Server. Scripts may be moved between server platforms without
alteration. PHP supports ISAPI to allow for the performance benefits of
tightly coupling with Microsoft Web servers.
• When you type a URL into your web browser’s address bar, you’re sending a
message to the web server at that URL, asking it to send you an HTML file.
The web server responds by sending the requested file. Your browser reads
the HTML file and displays the web page.
• You also request a file from the web server when you click a link in a web
page.
• In addition, the web server processes a file when you click a web page button
that submits a form. This process is essentially the same when PHP is
installed. You request a file, the web server happens to be running PHP, and
it sends HTML back to the browser, thanks to the programming in PHP.
• Often the extension is .php or .phtml, but any extension can be used. When
the web server gets a request for a file with the designated extension, it sends
the HTML statements as is, but PHP statements are processed by the PHP
software before they’re sent to the requester.
• When PHP language statements are processed, only the output, or anything
printed to the screen is sent by the web server to the web browser.
• The PHP language statements, those that don’t produce any output to the
screen, aren’t included in the output sent to the browser, so the PHP code is
not normally seen by the user.
• For instance, in this simple PHP statement, <?php is the PHP opening tag,
and ?> is the closing tag.
• <p>Hello World</p>
• That regular HTML statement is delivered to the user’s browser. The browser
interprets the statement as HTML code and displays a web page with one
paragraph — Hello World.
• The PHP statement isn’t delivered to the browser, so the user never sees any
PHP statements. PHP and the web server must work closely together.
• WAMP Server
• LAMP Server
• MAMP Server
• XAMPP Server
All these types of software automatic configure inside operating system after
installation it having PHP, My SQL, Apache and operating system base
configuration file, it doesn't need to configure manually.
Hardware Requirements
• If you would like to use a dedicated hosting server for running PHPKB
Knowledge Base Software or host it on a local server, you can use hardware
requirements and example specifications below for a reference.
• 1 GHz CPU
• 2 GB RAM
• 1 GB disk space
• Dual 2 GHz CPU
• 4 GB RAM
• 1 GB disk space
• Dual 2.6 GHz CPU
• 8 GB RAM
• 4 GB disk space
Manual Installation
We will install the PHP files to C:\php, so create that folder and extract the
contents of the ZIP file into it.
PHP can be installed anywhere on your system, but you will need to change
the paths referenced in the following steps.
"C:/php/ext"
Enable extensions.
This will depend on the libraries you want to use, but the following extensions
should be suitable for the majority of applications:
extension=curl extension=gd2
extension=mbstring
extension=mysql
extension=pdo_mysql
extension=xmlrpc
If you want to send emails using the PHP mail() function, enter the details of an
SMTP server (your ISP’s server should be suitable):
[mail function]
= mail.myisp.com
smtp_port = 25 ; For
Win32 only.
sendmail_from = my@emailaddress.com
To ensure Windows can find PHP, you need to change the path environment
variable.
Open Settings, type ‘environment variables’ into the search field and open
the result.
Select the “Advanced” tab, and click the “Environment Variables” button.
Scroll down the System variables list and click on “Path” followed by the
“Edit” button. Click “Edit text” and add ;C:\php to the end of the Variable
value line (remember the semicolon).
Whereas PHP4 have some OOPs concept added like class and object with
new functionality
PHP5 approximately all major oops functionality has been added along with
below thing
Type hinting which allows you to force the type of a specific argument
Finality : can now use the final keyword to indicate that a method cannot be
overridden by a
child. You can also declare an entire class as final which prevents it from
having any children at all. Interfaces & Abstract Classes Passed by
Reference :
6 .Strength of Php
Supports sessions. PHP can generate unique session IDs. The ID follows the
user during a single session on a web site. This simplifies creating shopping
cart applications and tracking user's behaviors.
Maintains source code security. The user does not see your source code as
they do with JavaScript.
Once the PHP interpreter finishes executing the PHP file, it’ll return an
output. The web server will take that output and send it back as a response to
the browser.
PHP script starts with the <?php and ends with the ?> tag.
The PHP delimiter <?php and ?> in the following example simply tells the
PHP engine to treat the enclosed code block as PHP code, rather than simple
HTML.
Syntax :
<?php
Comment Lines
A comment is simply text that is ignored by the PHP engine. The purpose of
comments is to make the code more readable.
It may help other developer (or you in the future when you edit the source
code) to understand what you were trying to do with the PHP.
To write a single-line comment either start the line with either two slashes (//)
or a hash symbol (#).
For example:
<?php
?>
However to write multi-line comments, start the comment with a slash followed by
an asterisk (/*) and end the comment with an asterisk followed by a slash (*/).
As a result the variables $color, $Color and $COLOR are treated as three different
variables.
<?php
?>
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand
side and the expression to be evaluated on the right.
PHP has a total of eight data types which we use to construct our variables –
Integers − are whole numbers, without a decimal point, like 4195. Doubles
− are floating-point numbers, like 3.14159 or 49.1.
Integers
$int_var = 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16)
format.
Decimal format is the default, octal integers are specified with a leading 0,
and hexadecimals have a leading 0x.
Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed.
<?php
$many = 2.2888800;
$few <br>");
?>
It produces the following browser output −
Boolean
if (TRUE)
NULL
$my_var = NULL;
$my_var = null;
A variable that has been assigned NULL has the following properties −
Strings
They are sequences of characters, like "PHP supports string operations". Following
are valid examples of string
var_dump() provides information about all the types contained within the
variable, as well as about the variable itself.
$testing = 5;
var_dump( $testing );
Output
int(5)
Example #1 var_dump()
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>
}
}
<?php
$b = 3.1; $c = true;
var_dump($b, $c);
?>
float(3.1) bool(true)
Function
is_array()
is_bool()
is_double()
is_int()
is_object()
is_null()
is_resource()
7.7 .Operators
For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and
$num is variable.
a. Arithmetic Operators
b. Assignment Operators
c. Bitwise Operators
d. Comparison Operators
e. Incrementing/Decrementing Operators
f. Logical Operators
g. String Operators
h. Array Operators
Arithmetic operators:
The PHP arithmetic operators are used to perform common arithmetic operations
such as addition, subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".
The bitwise operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
Comparison Operators
Comparison operators allow comparing two values, such as number or string.
Below the list of comparison operators are given:
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of
same data type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and
they are not of same data type
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal to $a >= $b Return TRUE if $a is greater than or equal $b
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value
of a variable.
The logical operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:
Array Operators
The array operators are used in case of array. Basically, these operators are used to
compare the values of arrays.
The variable thus singled-out is known as the dependent variable, while the
other variables are called independent variables.
Example:
• The string variables can contain alphanumeric characters. Strings are created
when;
• You declare variable and assign string characters to it You can directly use
them with echo statement.
8 .Control structures
Control structure allows you to control the flow of code execution in your
application.
if
else
elseif
switch
while
do-while
for
foreach
8.1. The If statement
The if construct allows you to execute a piece of code if the expression provided
along with it evaluates to true.
Example:
<?php $age =
50; if ($age >
30)
} ?>
Syntax
if (expression)
} else
{
Example
<?php $age =
50; if ($age <
30)
} else
{
?>
8.3. Multiple if, nested If Statement
We can consider the elseif statement as an extension to the if-else construct.
If you've got more than two choices to choose from, you can use the elseif
statement.
Syntax
if (expression1)
elseif (expression2)
elseif (expression3)
} else
Example
<?php
$age = 50;
} else
{
?>
In the case of the elseif statement, you have a set of different conditions, and
an appropriate action will be executed based on a condition.
On the other hand, if you want to compare a variable with different values,
you can use the switch statement.
<?php
$favourite_site = 'Code';
switch ($favourite_site) {
case 'Business':
} ?>
8.5 ? Operators
This is called the Ternary Operator, and it's common to several languages,
including PHP, Javascript, Python, Ruby...
if ($condition) {
$x = $trueVal;
} else {
$x = $falseVal;
} error
Unit - II
ARRAY
3. Casting array
4. Associative Array
8. Examining array
9. Joining Array
13. Functions
❖ $theVar = array();
❖ Now, $theVar is an array. However, it’s an empty array waiting for you to
come along and fill it.
❖ It’s still a good idea to explicitly define an array because it helps you
remember the element is an array, and there are a few special cases (such as
passing an array into a function) where the definition really matters.
❖ An array is a container, so it’s a lot more fun if you put something in it.
❖ You can refer to an array element by adding an index (an integer)
representing which element of the array you’re talking about.
2. Multidimensional Arrays
Example
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
?>
</body>
</html> Output:
3.Casting arrays
The meaning of type casting is to use the value of a variable with different
data type.
In other word typecasting is a way to utilize one data type variable into the
different data type.
For example:
<?php
$i =1; var_dump($i); //$i is
integer
?>
In above example, you can see that variable $i type is getting changed
on the different type of value assignment.
So due to this flexible nature of the PHP, we do not need to type cast variable
always.
But Sometimes when we need extra security in the variable we cast type.
For example, if we are taking some integer input from user then we should type
cast.
<?php
$string_var = "string value for php type";
$int_var = (int)$string_var; var_dump($int_var);
?>
We can cast following data type variable in PHP
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)
PHP type Casting to Integer
Using (int) or (integer) keyword we can cast/convert any data type value to the
integer. If we need to take integer casting then we can also use intval() function.
If we will convert boolean to an integer then False will output 0 and true will output
1. For example
<?php
$bool_false = false;
$int_val = (int) $bool_false ; var_dump($int_val);
//Output will be 0
$bool_true = true;
$int_val = (int) $bool_true ; var_dump($int_val);
//Output will be 1
?>
If we will convert resource data type to an integer then it will return unique
resource ID. For example <?
?>
Llll
4. Associative Array
❖ Associative array will have their index as string so that you can establish a
❖ Instead, we could use the employees names as the keys in our associative
Example:
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; echo
"Salary of qadir is ". $salaries['qadir']. "<br />"; echo "Salary of zara is ".
$salaries['zara']. "<br />"
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low"; echo "Salary of mohammad is ".
$salaries['mohammad'] . "<br />"; echo "Salary of qadir is ".
$salaries['qadir']. "<br />"; echo "Salary of zara is ".
$salaries['zara']. "<br />";
?>
</body>
</html>
<?php
$customerArray = array('customerName'=>'John Smith',
'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');
echo $customerArray['customerName'];
?>
The result will be the customer name "John Smith" appearing in the browser
window.
• One such mechanism is to use the foreach loop. The foreach loop works
much like a for or while loop and allows you to iterate through each array
element. There are two ways to use foreach. The first assigns the value of
the current element to a specified variable which can then be accessed in the
body of the loop
through both the keys and the values using the following syntax:
For example:
$customerArray = array('customerName'=>'John Smith',
'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');
}
This will result in the following output:
Key = customerName
Value = John Smith
Key = customerAddress
Value = 1 The Street
Key = accountNumber
Value = 123456789
8.Examining array
➢ Array creation is pretty simple. First, you need to create a variable and then
tell PHP that you want that variable to be an array:
➢ $theVar = array();
➢ Now, $theVar is an array. However, it’s an empty array waiting for you to
come along and fill it.
➢ Technically, you can skip the variable creation step. It’s still a good idea to
explicitly define an array because it helps you remember the element is an
array, and there are a few special cases (such as passing an array into a
function) where
9.Joining array
array_merge($arr1, $arr2)
If you want to combine two different arrays into a single array, you
can do so using this function.
It doesn't matter whether the arrays to be combined are of same
type(indexed, associative etc) or different types, using this function we can combine
them into one single array.
?>
Array (
[Suzuki] => Baleno
[Skoda] => Fabia
[Hyundai] => i20
[Tata] => Tigor
[0] => Vinod
[1] => Javed
[2] => Navjot
[3] => Samuel
)
10.Sorting array
❖ Similarly array items can be sorted in descending order using the rsort
function.
➢ To sort by key use ksort and krsort (reverse sort). To sort by value use the
asort and arsort functions.
➢ The syntax and options for these functions are as outlined for the sort and
rsort functions.
➢ Below we have a list of some commonly used array functions in PHP:
➢ sizeof($arr)
➢ This function returns the size of the array or the number of data elements
stored in the array.
➢ It is just like count($arr) method, that we used in previous tutorials while
traversing the array.
Example
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador"); echo
"Size of the array is: ". sizeof($lamborghinis);
?>
Size of the array is: 3 is_array($arr)
To check whether the provided data is in form of an array, we can use the is_array()
function. It returns True if the variable is an array and returns False otherwise.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// using ternary operator echo
is_array($lamborghinis) ? 'Array' : 'not an Array';
$mycar = "Urus";
// using ternary operator echo
is_array($mycar) ? 'Array' : 'not an Array';
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// new concept car by lamborghini
$concept = "estoque"; echo in_array($concept, $lamborghinis) ? 'Added to
the Lineup' : 'Not yet!'
?> print_r($arr)
Although this is not an array function, but it deserves a special mention here, as we
can use this function to print the array in the most descriptive way possible. This
function prints the complete representation of the array, along with all the keys and
values.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador"); print_r($lamborghinis);
?>
Array (
[0] => "Urus"
[1] => "Huracan"
[2] => "Aventador"
)
array_merge($arr1, $arr2)
If you want to combine two different arrays into a single array, you can do so using
this function. It doesn't matter whether the arrays to be combined are of same
type(indexed, associative etc) or different types, using this function we can combine
them into one single array.
Let's take an example where we will merge an indexed array and an associative
array.
<?php
$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
?>
Array (
[Suzuki] => Baleno
[Skoda] => Fabia
[Hyundai] => i20
[Tata] => Tigor
[0] => Vinod
[1] => Javed
[2] => Navjot
[3] => Samuel
)
12.Loops
12.1While loop
• They are used to execute a block of code a repeatedly until the set condition
gets satisfied
• You can use a while loop to read records returned from a database query.
• Types of while loops
• Do… while - executes the block of code at least once before evaluating the
condition
• While… - checks the condition first. If it evaluates to true, the block of code
is executed as long as the condition is true. If it evaluates to false, the
execution of the while loop is terminated.
While loop
It has the following syntax
<?php while (condition)
{ block of code to be
executed;
}
?>
HERE,
“while(…){…}” is the while loop block code
The flow chart shown below illustrates how the while… loop works
PHP Loop and Control Structures
Practical example
$i++;
} ?>
Output:
1
2
3
4
5
12.2 Do While
The difference between While… loop and Do… while loop is do… while is
executed at-least once before the condition is evaluated. Let’s now look at
the basic syntax of a do… while loop
<?php do{ block of code to
be executed
} ?>
while(condition);
HERE,
“block of code…” is the code that is executed at least once by the do… while loop
How it works
The flow chart shown below illustrates how the while… loop works
PHP Loop and Control Structures
We are now going to modify the while… loop example and implement it using the
do… while loop and set the counter initial value to 9.
} while($i <
9);
?>
The above code outputs:
9
12.3 For Loop
The above code outputs “21 is greater than 7” For loops For... loops
execute the block of code a specifiednumber of times. There are basically two
types of for loops; for for… each.
Let’s now look at them separately. For loop It has the following basic syntax
<?php
for (initialize; condition; increment){
//code to be executed
}
?>
HERE,
“condition” the condition that is evaluated for each php execution. If it evaluates to
true then execution of the for... loop is terminated. If it evaluates to false, the
execution of the for... loop continues.
<?php
foreach($array_variable as $array_values){ block
of code to be executed
}
?>
HERE,
“foreach(…){…}” is the foreach php loop block code
“block of code…” is the piece of code that operates on the array values
How it works The flowchart shown below illustrates how the for… each… loop
works
The code below uses for… each loop to read and print the elements of an array.
<?php
$animals_list = array("Lion","Wolf","Dog","Leopard","Tiger");
foreach($animals_list as $array_values){ echo $array_values .
"<br>";
} ?>
Output:
Lion
Wolf
Dog
Leopard
Tiger
13.Function in php
➢ You already have seen many functions like fopen() and fread() etc.
➢ They are built-in functions but PHP gives you option to create your own
functions as well.
14.Library function
:</font></h3>';
print_r(Array_slice($a,2)); echo'<br><h3><font
color="dodgerblue">Array Splicing in a()
:</font></h3>'; print_r(Array_splice($a,2));
echo'<br><h3><font color="chocolate">Array Poping from a():</font></h3>';
echo'<b>Before :</b>'; print_r($a);
Array_pop($a); echo'<br><b>After :</b>'; print_r($a);
echo'<br><h3><font color="lime">Array Pushing into b():</font></h3>';
echo'<b>Before :</b>'; print_r($b);
$i=Array_sum($b); print_r($i);
echo"</td></tr></table>";
?>
</body></html>
14.2.String function
<html>
<body bgcolor="green">
<?php echo'<table align="center" bgcolor="white"><tr><td>';
echo'<h1><u><font color="crimson" face="cooper black">Date & Time
Function</font></u></h1><br>'; echo'<b>Current Date, i.e.
16-12-31</b><br>'; echo date("y-m-d"); echo'<br><br><b>Current
Month, i.e. 08 </b><br>'; echo date("m"); echo'<br><br><b>Current
Month Name, i.e. Jan </b><br>'; echo date("M");
echo'<br><br><b>Current Timestamp</b><br>'; echo time();
Following example creates a function called write Message() and then calls
it just after creating it.
Note that while creating a function its name should start with keyword
function and all the PHP code should be put inside { and } braces as shown in the
following example below
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */ function
writeMessage() { echo "You are really a nice person,
Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php function addFunction($num1,
$num2) {
addFunction(10, 20);
?>
</body>
</html>
Following example takes two integer parameters and add them together
and then returns their sum to the calling program. Note that return keyword is used
to return a value from a function.
Example:
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
}
$return_value = addFunction(10, 20);
</body>
</html>
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body> <?php
function sayHello() {
echo "Hello<br />";
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
This will display following result −
Hello
Following example takes two integer parameters and add them together and then
returns their sum to the calling program. Note that return keyword is used to return
a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
}
$return_value = addFunction(10, 20);
</body>
</html>
This will display following result −
Following function prints NULL in case use does not pass any
value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php function printMe($param =
NULL) { print $param;
printMe("This is test");
printMe();
?>
</body>
</html>
Following function prints NULL in case use does not pass any value to this
function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php function printMe($param =
NULL) { print $param;
printMe("This is test");
printMe();
?>
</body>
</html>
This is test
❖ This function may be called from anywhere within the program any number
of times.
Syntax
//define a function function
myfunction($arg1, $arg2, ... $argn)
{ statement
1;
statement2;
..
..
return $val;
}
//call function
$ret=myfunction($arg1, $arg2, ... $argn);
Function may be defined with optional but any number of arguments. However,
same number of arguments must be provided while calling. Function's body can
contain any valid PHP code i.e. conditionals, loops etc. (even other functions or
classes may be defined inside a function). After executing statements in the block,
program control goes back to the location from which it was invoked irrespective of
presence of last statement of function block as return. An expression in front of
return statement returns its value to calling environment.
} add(10,20);
add("Hello", "World");
?>
Output
This will produce following result. −
30
15.6 Passing Arguments to a function by Reference
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php function
addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
?>
</body>
</html>
This will display following result −
Original Value is 10
Original Value is 16
Unit-III
Working with the file system
9. Validation
▪ 9.1 Server side validation and client side validation
▪ 9.2 Working with Regular Expressions
1. Creating and deleting files
File handling is needed for any application. For some tasks to be
done file needs to be processed.
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen()
contains name of the file which is to be opened and second parameter tells about
mode in which file needs to be opened, e.g.,
<?php
$file = fopen(“demo.txt”,'w');
?>
“w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
“a” – File is opened for write only. File pointer points to end of file. Existing data in
file is preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if
file already exists then contents of file is erased.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data
in file is preserved. If file is not there then new file is created.
Deleting Files
To delete a file, you use the unlink() function. You need to pass the file name that
you want to delete to the unlink() function. The function returns true on success or
false on failure
<?php
}else{
1) fread() –– After file is opened using fopen() the contents of data are read
using fread(). It takes two arguments. One is file pointer and another is file size in
bytes, e.g.,
<?php
$filename = "demo.txt";
?>
2) fwrite() – New file can be created or text can be appended to an existing file
using fwrite() function. Arguments for fwrite() function are file pointer and text
that is to written to file. It can contain optional third argument where length of text
to written is specified, e.g.,
<?php
fwrite($file, $text);
?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs
to be closed, e.g.,
<?php
?>
Notice that copy(), rename() and unlink() functions raise warning-level errors if the
file cannot be found therefore it is good practice to check the file exists using the
file_exists() function before copying, renaming or deleting.
<?php
?>
Syntax:
file_exists($path)
Parameters: The file_exists() function in PHP accepts only one parameter $path. It
specifies the path of the file or directory you want to check.
The file_exists() function returns False if the path specified points to non-existent
files.
For files larger than 2gb, some of the filesystem functions may give unexpected
results since PHP’s integer type is signed and many platforms use 32bit integers.
Examples:
Output : 1
not exists";
}
Output : 1
Program 1:
<?php
?>
Output:
Syntax:
filesize($filename)
Parameters: The filesize() function in PHP accepts only one parameter $filename.
It specifies the filename of the file whose size you want to check.
Return Value: It returns the size of a file in bytes on success and False on failure.
Program 1:
<?php
?>
Output:
256
Program 2:
<?php
?> Output:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen()
contains name of the file which is to be opened and second parameter tells about
mode in which file needs to be opened, e.g.,
<?php
$file = fopen(“demo.txt”,'w');
?>
“w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
“a” – File is opened for write only. File pointer points to end of file. Existing data in
file is preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if
file already exists then contents of file is erased.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data
in file is preserved. If file is not there then new file is created.
Deleting Files
To delete a file, you use the unlink() function. You need to pass the file name that
you want to delete to the unlink() function. The function returns true on success or
false on failure
<?php
}else{
echo sprintf("An error occurred deleting the file %s",$fn);
}
1) fread() –– After file is opened using fopen() the contents of data are read
using fread(). It takes two arguments. One is file pointer and another is file size in
bytes, e.g.,
<?php
$filename = "demo.txt";
?>
2) fwrite() – New file can be created or text can be appended to an existing file
using fwrite() function. Arguments for fwrite() function are file pointer and text
that is to written to file. It can contain optional third argument where length of text
to written is specified, e.g.,
<?php
fwrite($file, $text);
?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs
to be closed, e.g.,
<?php
?>
Notice that copy(), rename() and unlink() functions raise warning-level errors if the
file cannot be found therefore it is good practice to check the file exists using the
file_exists() function before copying, renaming or deleting. 7. Writing data to
the Files and reading characters
The first parameter of fwrite() contains the name of the file to write to
and the second parameter is the string to be written.
The example below writes a couple of names into a new file called
"newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile); ?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file
we sent the string $txt that first contained "John Doe" and second contained "Jane
Doe". After we finished writing, we closed the file using the fclose() function.
John Doe
Jane Doe
8. Forms
We can create and use forms in PHP. To get form data, we need to
use PHP superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from get
request, we need to use $_GET, for post request $_POST.
Get request is the default form request. The data passed through get
request is visible on the URL browser so it is not secured. You can send limited
amount of data through get request.
Let's see a simple example to receive data from get request in PHP.
form1.html
</form>
File: welcome.php
<?php
?>
Post request is widely used to submit form that have large amount of data such as
file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is
secured. You can send large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
</table>
</form>
File: login.php
<?php
?>
Output: php
form
➢ $_REQUEST
➢ $_POST
➢ $_GET
➢ $_FILES
➢ $_ENV
➢ $_COOKIE
➢ $_SESSION
This chapter will explain some of the superglobals, and the rest will be explained in
later chapters.
PHP $GLOBALS
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75; $y = 25;
function addition() {
} addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it
is also accessible from outside the function!
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers,
paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example <?php
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside
$_SERVER:
Element/Code Description
PHP $_REQUEST
The example below shows a form with an input field and a submit button. When a
user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to this
file itself for processing form data. If you wish to use another PHP file to process
form data, replace that with the filename of your choice. Then, we can use the super
global variable $_REQUEST to collect the value of the input field:
Example
<html>
<body>
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) { echo
"Name is empty";
} else
{ echo
$name;
?>
</body>
</html>
PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables.
The example below shows a form with an input field and a submit button. When a
user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to the
file itself for processing form data. If you wish to use another PHP file to process
form data, replace that with the filename of your choice. Then, we can use the super
global variable $_POST to collect the value of the input field:
Example
<html>
<body>
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
} else
{ echo
$name;
?>
</body>
</html>
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form
with method="get".
<html>
<body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are
sent to "test_get.php", and you can then access their values in "test_get.php" with
$_GET.
Example
<html>
<body> <?php
?>
</body>
</html>
This is not assured that every web server will provide similar information; rather
some servers may include or exclude some information which are not listed here.
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['HTTP_USER_AGENT'];
1:<html>
2: <head>
3: <title>Listing 9.2 A simple HTML form</title>
4: </head>
5: <body>
6: <form action="listing9.3.php">
7: <input type="text" name="user"> 8:
<br>
9: <textarea name="address" rows="5" cols="40">
10: </textarea>
11: <br>
12: <input type="submit" value="hit it!">
13: </form>
14: </body>
15: </html>
➢ We define a form that contains a text field with the name "user" on line 7, a
text area with the name "address" on line 9, and a submit button on line
12.
➢ It is beyond the remit of this book to cover HTML in detail.
➢ If you find the HTML in these examples hard going, take a look at Sams
Teach Yourself HTML in 24 Hours or one of the numerous online HTML
tutorials.
➢ Listing 9.3 creates the code that receives our users' input.
1: <html>
2: <head>
3: <title>Listing 9.3 Reading input from the form in Listing 9.2</title> 4:
</head>
5: <body>
6: <?php
7: print "Welcome <b>$user</b><P>\n\n";
8: print "Your address is:<P>\n\n<b>$address</b>";
9: ?>
10: </body>
11: </html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
First of all, don’t worry if you haven’t seen this kind of mixed PHP and HTML
code before, as we’ll discuss it in detail throughout this article. The above example
outputs following in your browser:
<?php echo "Hello World" ?>
So as you can see, by default, PHP tags in your .html document are not detected,
and they're just considered plain-text, outputting without parsing.
That's because the server is usually configured to run PHP only for files with the
.php extension.
If you want to run your HTML files as PHP, you can tell the server to run
your .html files as PHP files, but it's a much better idea to put your mixed PHP and
HTML code into a file with the .php extension.
When it comes to integrating PHP code with HTML content, you need to enclose
the PHP code with the PHP start tag <?php and the PHP end tag ?>. The code
wrapped between these two tags is considered to be PHP code, and thus it'll be
executed on the server side before the requested file is sent to the client browser.
<!DOCTYPE html>
</head>
<body>
</body>
</html
➢ Hidden fields are great for passing additional information from the form to
the server.
<?php//from w w w . j av a2s .c om
$num_to_guess = 42;
$message = "";
$message = "Welcome!";
} else {
$num_tries ++;
?>
<html>
<body>
print $num_tries?>" /> Type your guess here: <input type="text" name="guess"
value="<?php print $guess?>" />
</form>
</body>
</html>
The header() function is an inbuilt function in PHP which is used to send the raw
HTTP (Hyper Text Transfer Protocol) header to the client.
Program
<?php
// Redirect browser
Note: The die() or exit() function after header is mandatory. If die() or exit() is not
put after after the header(‘Location: ….’) then script may continue resulting in
unexpected behavior. For example, result in content being disclosed that actually
wanted to prevent with the redirect (HTTP 301).
Example:
<html>
<head>
<title>window.location function</title>
</head>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"URL: " + window.location.href +"</br>";
document.getElementById("demo").innerHTML =
document.getElementById("demo").innerHTML +
"Hostname: " + window.location.hostname + "</br>";
document.getElementById("demo").innerHTML =
document.getElementById("demo").innerHTML +
"Protocal: " + window.location.protocol + "</br>";
</script>
</body>
</html>
Output:
URL: https://ide.geeksforgeeks.org/tryit.php
❖ The user opens the page containing a HTML form featuring a text files, a
browse button and a submit button.
❖ The user clicks the browse button and selects a file to upload from the local
PC.
❖ The full path to the selected file appears in the text filed then the user clicks
the submit button.
❖ As usual when writing files it is necessary for both temporary and final
locations to have permissions set that enable file writing. If either is set to be
read-only then process will fail.
The following HTM code below creates an uploader form. This form is having
method attribute set to post and enctype attribute is set to multipart/form-data
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
?>
<html>
<body>
<input type="submit"/>
</form>
</body>
</html>
Upload Form
There is one global PHP variable called $_FILES. This variable is an associate
double dimension array and keeps all the information related to uploaded file. So if
the value assigned to the input's name attribute in uploading form was file, then
PHP would create following five variables −
Example
Below example should allow upload images and gives back result as uploaded file
information.
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
if(empty($errors)==true) { move_uploaded_file($file_tmp,"images/".
$file_name); echo "Success";
}else{ print_r($e
rrors);
?>
<html>
<body>
<ul>
</ul>
</form
</body>
</html>
Upload Script
9. Validation
9.1 client side and server side validation
Validation means check the input submitted by the user. There are
two types of validation are available in PHP. They are as follows
Server Side Validation − After submitted by data, The data has sent to a server and
perform validation checks in server machine.
Valid URL
$website = input($_POST["site"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z09+&@#\/%=~_|]/i",$website)) {
}
Above syntax will verify whether a given URL is valid or not. It should allow some
keywords as https, ftp, www, a-z, 0-9,..etc..
Valid Email
$email = input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
Above syntax will verify whether given Email address is well-formed or not.if it is
not, it will show an error message.
Example
<html>
<head>
<style>
</style>
</head>
<body>
<?php
// define variables and set to empty values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
}else {
$name = test_input($_POST["name"]);
if (empty($_POST["email"])) {
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed if (!
filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (empty($_POST["website"])) {
$website = "";
}else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
}else {
$comment = test_input($_POST["comment"]);
if (empty($_POST["gender"])) {
}else {
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
?>
<table>
<tr>
<td>Name:</td>
</td>
</tr>
<tr>
<td>E-mail: </td>
</tr>
<tr>
<td>Time:</td>
</td>
</tr>
<tr>
<td>Classes:</td>
</tr>
<tr>
<td>Gender:</td>
<td>
</td>
</tr>
<td>
</td>
</table>
</form> <?
php
echo $email;
echo "<br>";
echo $website;
echo "<br>" echo
$comment; echo
"<br>";
echo $gender;
?>
</body>
</html>
❖ They are basically used in programming world algorithms for matching some
loosely defined patterns to achieve some relevant tasks
❖ . Some times regexes are understood as a mini programming language with a
pattern notation which allows the users to parse text strings.
❖ This is the same with other applications also, which have their own support
of regexes having various syntaxes. Many available modern languages and
tools apply regexes on very large files and strings.
❖ Let us look into some of the advantages and uses of regular expressions in
our applications.
❖ It offers a powerful tool for analyzing, searching a pattern and modifying the
text data.
❖ It helps in parsing text files looking for a defined sequence of characters for
further analysis or data manipulation.
❖ With the help of in-built regexes functions, easy and simple solutions are
provided for identifying patterns.
❖ It helps in identifying specific template tags and replacing those data with the
actual data as per the requirement.
❖ Regexes are very useful for creation of HTML template system recognizing
tags.
❖ Regexes are mostly used for browser detection, spam filteration, checking
password strength and form validations.
❖ We cannot cover everything under this topic, but let us look into some of the
major regular expression concepts. The following table shows some regular
expressions and the corresponding string which matches the regular
expression patterns
[abc] a, b, or c
Note: Complex search patterns can be created by applying some basic regular
expression rules. Even many arithmetic operators like +, ^, – are used by regular
expressions for creating little complex patterns.
Operators in Regular Expression: Let us look into some of the operators in PHP
regular expressions.
Operator Description ^ It
denotes the start of string.
– (dash) It finds for character range within the given item range for example [a-
z] means a through z.
{n} It denotes exactly n times of preceding character or item range for example
n{2}.
{n, } It denotes atleast n times of preceding character or item range for example
n{2, }.
{n, m} It denotes atleast n but not more than m times for example n{2, 4}
means 2 to 4 of n.
\ It denotes the escape character.
Special Character Classes in Regular Expressions: Let us look into some of the
special characters used in regular expressions
preg_match_all() This function searches for all the occurrences of string pattern
against the string. This function is very useful for search and replace.
ereg_replace() This function searches for specific string pattern and replace the
original string with the replacement string, if found.
eregi_replace() The function behaves like ereg_replace() provided the search for
pattern is not case sensitive.
preg_replace() This function behaves like ereg_replace() function provided the
regular expressions can be used in the pattern and replacement strings.
preg_split() The function behaves like the PHP split() function. It splits the string
by regular expressions as its paramaters.
preg_grep() This function searches all elements which matches the regular
expression pattern and returns the output array.
preg_quote() This function takes string and quotes in front of every character
which matches the regular expression.
ereg() This function searches for a string which is specified by a pattern and returns
true if found, otherwise returns false.
eregi() This function behaves like ereg() function provided the search is not
case sensitive.
Example 1:
<?php
if(preg_match($regex, $nameString))
{ echo("Name string matching with"
} else
{
Output:
2. Creating an object:
6. Class inheritance
7. Abstract Classes and methods
8. Object serialization
16. Fetch data from table acquiring the values, Joins query
17. COOKIES
DEFINE A CLASS
Class:
Syntax :
<? Php
Class MyClass
{
// Class properties and methods go here
}
?>
2. Creating an Object:
Syntax:
<?Php
Class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj); ?>
<?php class
demo
{
private $a= "hello javatpoint";
public function display()
{
echo $this->a;
}
}
$obj = new demo();
$obj->display();
?>
Example:
Class Car {
Example
<?Php class
Example
{
public function __construct()
{
echo "Hello javatpoint";
}
}
$obj = new Example();
$obj = new Example(); ?>
Output:
DESTRUCTOR
Example
<?php class
demo
{
public function demo()
{
echo "constructor1...";
}
}
class MyClass {
const requiredMargin = 1.7;
function __construct($incomingValue) {
// Statements here run every time
// an instance of the class // is
created.
}
}
Access modifier
To set the access rights for class methods and variables we use access
modifiers which are nothing but PHP keywords.
We can even assign some of these access modifiers to the class itself to make
the class behave in a special way.
Following are the PHP keywords which are used as access modifiers along
with their meaning:
1. public: When we define class members as public, then they are accessible
from anywhere, even from outside of the class scope.
4. abstract: This keyword is only used for PHP classes and its member
functions.
5. final: The class methods defined as final, can not be changed or overriden
by any subclass.
6. Class inheritance
The child class will inherit all the public and protected properties and methods
from the parent class.
In addition, it can have its own properties and methods.
Example:
<?php
class Fruit { public $name; public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() { echo "The fruit is {$this->name} and
the color is {$this->color}.";
}
}
8.Object serialization
Following functions:
➢ When the object is serialized, the content is placed with some type of a
specifier followed by a colon, then followed with the actual data followed
by a semi-colon.
➢ When we serialize an object it stores the class name and all its
properties. It doesn’t store methods of the class. Hence to unserialize the
serialized object the class should be present in the script before
unserializing it.
Now let us see how the object is serialized and unserialized using the function
serialize() and unserialize() in the following code shown below:
<?php class
Worker
{
private $id;
protected $name;
protected $dept;
//calling the function display() of the Worker class using object $work1 echo
"*Object Unserialised:<br>";
$work1->display();
?>
❖ In the above code, a class Worker is defined and its object $work is
created and values are passed in the constructor.
❖ Then the object is serialized using the serialize() function, the object
$work is passed as a parameter in the funciton .
❖ $serialized=serialize($work);
❖ Then to show that the object has been unserialized, its display() method
is called using the $work1 object.
serialize_unserialize_output
Syntax
Parameters
10. Exception
➢ An exception is an unexcepted outcome of a program, which can be
handled by the program itself.
➢ Basically, an exception disrupts the normal flow of the program.
➢ But it is different from an error because an exception can be handled,
whereas an error cannot be handled by the program itself.
• MySQLi (object-oriented)
• MySQLi (procedural)
• PDO
// Create connection
$conn = new mysqli($servername, $username, $password);
// Create connection
$conn = mysqli_connect($servername, $username, $password);
The connection will be closed automatically when the script ends. To close the
connection before, use the following:
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB"; if
($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else { echo "Error creating database: " . $conn-
>error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection if (!$conn) { die("Connection
failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB"; if
(mysqli_query($conn, $sql)) { echo
"Database created successfully";
} else { echo "Error creating database: " .
mysqli_error($conn);
}
mysqli_close($conn); ?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql); echo "Database
created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
A database table has its own unique name and consists of columns
and rows.
The data type specifies what type of data the column can hold.
For a complete reference of all the available data types, go to our Data Types
reference.
After the data type, you can specify other optional attributes for each column:
• NOT NULL - Each row must contain a value for that column, null values
are not allowed
• DEFAULT value - Set a default value that is added when no other value is
passed
• UNSIGNED - Used for number types, limits the stored data to positive
numbers and zero
• AUTO INCREMENT - MySQL automatically increases the value of the
field by 1 each time a new record is added
• PRIMARY KEY - Used to uniquely identify the rows in a table. The
column with PRIMARY KEY setting is often an ID number, and is often
used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its
value must be unique for each record in the table.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection if (!$conn) { die("Connection
failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else { echo "Error creating table: " .
mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
After a database and a table have been created, we can start adding data in
them.
The INSERT INTO statement is used to add new records to a MySQL table:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection if
($conn->connect_error) {
die("Connection failed: " .
$conn->connect_error);
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection if (!$conn) { die("Connection
failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql); echo "New record
created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
16. Fetch data from table acquiring the values, Joins query
Example
Enter password:*******
Database changed
+----+---------+
| id | book |
+----+---------+
| 1 | java |
| 2 | java |
| 3 | html |
| 4 | c++ |
| 5 | Android |
+----+---------+
5 rows in set (0.00 sec)
+----+-------+
| id | name |
+----+-------+
| 1 | sai |
| 2 | johar |
| 3 | raghu |
| 4 | ram |
+----+-------+
mysql>
Now we can write a SQL query to join these two tables. This query will select
all the names from table tutorials_inf and will pickup corresponding number
of tutorials fromtutorials_bks
+----+-------+----+
| id | name | id |
+----+-------+----+
| 1 | sai | 1 |
| 2 | johar | 2 |
| 3 | raghu | 3 |
| 4 | ram | 4 |
+----+-------+----+ 4 rows
You can use any of the above-mentioned SQL query in PHP script. You only
need to pass SQL query into PHP function mysqli_query() and then you will
fetch results in usual way.
Example
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'TUTORIALS';
mysqli_error()); }
$row['name'] . "</td>";
echo "</tr>";
echo "</table>";
mysqli_free_result($result);
} else {
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
mysqli_close($conn);
?>
successfully
id name id
1 sai 1
2 johar 2
3 raghu 3
4 ram 4
A MySQLi left join is different from a simple join. A MySQLi LEFT JOIN gives
extra consideration to the table that is on the left.
If I do a LEFT JOIN, I get all the records that match in the same way and IN
ADDITION I get an extra record for each unmatched record in the left table of
the join - thus ensuring (in my example) that every name gets a mention −
Example
Enter password:*******
mysql> use TUTORIALS;
Database change
17.COOKIES :
Cookies are usually set in an HTTP header (although JavaScript can also set a
cookie directly on a browser).
A PHP script that sets a cookie might send headers that look something like
this −
HTTP/1.1 200 OK
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date,
a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to
the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information
until the expiry date.
If the user points the browser at any page that matches the path and domain
of the cookie, it will resend the cookie to the server.
The browser's headers might look something like this −
GET / HTTP/1.0
Connection: Keep-Alive
Host: zink.demon.co.uk:1126
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental
variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names
and values.
Path − This specifies the directories for which the cookie is valid. A
single forward slash character permits the cookie to be valid for all
directories.
Domain − This can be used to specify the domain name in very large
domains and must contain at least two periods to be valid. All cookies
are only valid for the host and domain which created them.
Security − This can be set to 1 to specify that the cookie should only be
sent by secure transmission using HTTPS otherwise set to 0 which
mean cookie can be sent by regular HTTP.
Following example will create two cookies name and age these cookies will
be expired after one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0); setcookie("age",
"36", time()+3600, "/", "", 0);
?> <html>
<head>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
Officially, to delete a cookie you should call setcookie() with the name
argument only but this does not always work well, however, and should not
be relied on.
It is safest to set the cookie with a date that has already expired –
<?php
setcookie( "name", "", time()- 60, "/","", 0); setcookie( "age", "", time()- 60,
"/","", 0);
?>
<html>
<head>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
Example:
<!DOCTYPE html>
<?php
$cookie_name = "gfg";
$cookie_value = "GeeksforGeeks";
<html>
<body>
<?php if(!isset($_COOKIE[$cookie_name]))
{ echo "Cookie named '" . $cookie_name . "' is not
set!";
}
else
?>
</body>
</html>
Output:
Deleting Cookie:
Syntax:
Example:
<!DOCTYPE html>
<?php
?>
<html>
?>
</body>
</html>
Output:
Parameters :
lifetime
path
Path on the domain where the cookie will work. Use a single slash ('/') for all
paths on the domain.
domain
secure
only.
If set to TRUE then PHP will attempt to send the httponly flag when setting the
session cookie.
options
✓ An associative array which may have any of the keys lifetime, path,
domain, secure, httponly and samesite.
✓ The values have the same meaning as described for the parameters with
the same name.
✓ The value of the samesite element should be either Lax or Strict.
✓ If any of the allowed options are not given, their default values are the
same as the default values of the explicit parameters.
✓ If the samesite element is omitted, no SameSite cookie attribute is set.
Return Values
➢ This query string can be passed from one page to another by appending
it to the address of the page.
➢ You can pass more than one query string by inserting the & sign
between the query strings.
➢ A query string can contain two things: the query string ID and its value.
The query string passed across the web pages is stored in $_REQUEST,
$_GET, or $_POST variable.
➢ Whether you passed the query string by using GET or POST method, it is
stored in $_REQUEST variable. If you want to access the query string
you can use these variables.
➢ You should note that whether the query string is passed by the GET or
POST method it can be accessed by using the $_REQUEST variable.
➢ If you want to use $_GET variable to access the query string the form
method need to be GET. Also you can use $_POST variable to get the
query string if the form method is POST.
Login.php:
<html>
<head>
<title>Login form</title>
</head>
<body>
<form action="welcome.php" method=”get”>
<table>
<tr>
<td>User name:</td><td> <input type="text" name="username" ></td>
</tr>
<tr>
<td>E-mail: </td><td><input type="text" name="email" ></td>
</tr>
<tr>
<td><input type="submit" name="sub" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Search
English
(PHP 5, PHP 7)
Description ¶
Parameters ¶ query_data
numeric_prefix
If numeric indices are used in the base array and this parameter is
provided, it will be prepended to the numeric index for elements in the
base array only.
This is meant to allow for legal variable names when the data is decoded
by PHP or another CGI application later on.
arg_separator
enc_type
By default, PHP_QUERY_RFC1738.
Return Values ¶
Examples ¶
$data = array(
);
?>
foo=bar&baz=boom&cow=milk&php=hypertext+process
or
<?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' => 'hypertext
processor');
echo http_build_query($data) . "\n"; echo
http_build_query($data, 'myvar_');
?>
0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk
&php=hypertext+processor
Unit -V
SESSION
1. What Is a Session
2. Starting a Session?
4. Destroying a Session
5. Passing Session Id
8. E-mail
9. File Upload
1. What Is a Session
▪ For example, when you access a web page, the server is just
responsible for providing the contents of the requested
page.
2. Starting a Session
➢ Whenever you want to deal with session variables, you need to make
sure that a session is already started.
➢ This is the method that you'll see most often, where a session is started
by the session_start function.
<?php
?>
By default, it’s set to 0, and you can set it to 1 to enable the auto startup
functionality.
session.auto_start = 1
On the other hand, if you don’t have access to the php.ini file, and you're
using the Apache web server, you could also set this variable using
the .htaccess file.
<?php
$_SESSION['logged_in_user_id'] = '1';
$_SESSION['logged_in_user_name'] = 'Tutsplus';
$_SESSION['logged_in_user_id']; echo
$_SESSION['logged_in_user_name'];
?>
❖ When you store the data in a session using the $_SESSION super-global,
it’s eventually stored in a corresponding session file on the server which
was created when the session was started.
5. Destroying a Session
Having said that, it doesn't unset global variables associated with session or
unset the session cookie.
So if you're using the session_destroy function to log out a user, you must
unset the $_SESSION variable and unset the session cookie as well .
<?php
unset($_SESSION); if
(ini_get("session.use_cookies"))
{ $params =
session_get_cookie_params();
session_destroy();
?>
5. Passing Session Id
If you want to get a session id, you can use the session_id function, as shown in
the following snippet.
<?php
session_start(); echo
session_id();
?>
The session_id function is interesting in that it can also take one argument—a
session id.
If you want to replace the system-generated session id with your own, you can
supply it to the first argument of the session_id function.
<?php session_id(YOUR_SESSION_ID);
session_start();
?>
6. Encoding and Decoding Session variables
❖ In PHP, session encodes and decode operations are automatically
performed while storing session data into memory and reading stored
session, respectively.
❖ This serialization will not return the same format like PHP serialize()
Example:
<?php session_start();
$_SESSION["product_code"] = "2222";
$_SESSION['product_code'] = "2000";
$_SESSION["logged_in"] = "no"; //
session_decode($enc_session);
?>
Output:
product_code|s:4:"2222";logged_in|s:3:"yes";
Array (
[logged_in] => no
Array(
7. Disk Access,I/O
PHP | disk_free_space( ) Function
Syntax:
Examples:
Input : disk_free_space("D:");
Output : 10969328844
Input : disk_free_space("C:");
Output : 10969327231
8. E- mail?
❖ PHP mail is the built in PHP function that is used to send emails from
PHP scripts.
❖ Email address
❖ Subject
❖ Message
❖ CC or BC email addresses
❖ Let users contact you via email by providing a contact us form on the
website that emails the provided content.
❖ You can use it to send password reset links to users who forget their
passwords
?>
HERE,
It’s used when you want to send a copy to an interested person i.e. a complaint
email sent to a company can also be sent as CC to the complaints board.
It is similar to CC. The email addresses included in the BCC section will not be
shown to the other recipients.
✓ PHP allows you to upload single and multiple files through few lines of
code only.
✓ A PHP file upload feature allows you to upload binary and text files both.
Moreover, you can have the full control over the file to be uploaded
through PHP authentication and file operation functions.
File: uploadform.html
</form>
File: uploader.php
<?php
$target_path = "e:/";
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
again!";
?>
➢ Using PHP you can create web page to download file easily using built-in
readfile() function.
➢ The readfile() function reads a file and writes it to the output buffer.
Example
<?php
$file_url = 'http://www.your_remote_server.com/f.txt'; header('Content-
8");
?>
readfile($file_url); ?>
➢ Most of these variables are provided by the shell under which PHP
parser is running.
➢ This array also includes CGI variables in case whether PHP is running as
a server module orCGI processor.
getenv
Following script displays values of all available environment variables.
<?php $arr=getenv();
echo "$key=>$val";
?>
Syntax: rand()
Note
If the min and max value is not specified, default is 0 and getrandmax()
respectively.
Example rand() will return a random integer between 0 and
range [15,35].
<?php
$randomNumber = rand();
print_r($randomNumber);
print_r("\n");
$randomNumber = rand(15,35);
print_r($randomNumber);
?>
It does this by updating only part of a web page rather than the whole
page.
This means that it is possible to update parts of a web page, without reloading
the whole page.
All modern browsers (Chrome, Firefox, IE7+, Edge, Safari Opera) have a
builtin XMLHttpRequest object.
XMLHttpRequest Methods
• abort()
Cancels the current request.
• getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
• getResponseHeader( headerName )
Returns the value of the specified HTTP header.
• open( method, URL )
• open( method, URL, async )
• open( method, URL, async, userName )
• open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD".
Other HTTP methods such as "PUT" and "DELETE" (primarily used in
REST applications) may be possible.
The "async" parameter specifies whether the request should be handled
asynchronously or not.
"true" means that the script processing carries on after the send()
method without waiting for a response, and "false" means that the
script waits for a response before continuing script processing.
• send( content )
Sends the request.
• setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Properties
• onreadystatechange
An event handler for an event that fires at every state change.
• readyState
The readyState property defines the current state of the
XMLHttpRequest object.
State Description
The following table provides a list of the possible values for the
readyState property −
➢ Ajax uses XHTML for content, CSS for presentation, along with
➢ With AJAX, when you hit submit, JavaScript will make a request to the
server, interpret the results, and update the current screen. In the
purest sense, the user would never know that anything was even
transmitted to the server.
➢ XML is commonly used as the format for receiving server data, although
any format, including plain text, can be used.
➢ AJAX is a web browser technology independent of web server software.
➢ A user can continue to use the application while the client program
requests information from the server in the background.