0% found this document useful (0 votes)
7 views19 pages

Serialization

The document explains serialization in PHP, detailing the use of the serialize() and unserialize() functions to convert complex arrays into strings and back. It also covers JSON encoding and decoding as an alternative method for data serialization, emphasizing its compatibility with various programming languages. Additionally, the document outlines core web techniques in PHP, including server-side scripting, form handling, database interaction, and security best practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

Serialization

The document explains serialization in PHP, detailing the use of the serialize() and unserialize() functions to convert complex arrays into strings and back. It also covers JSON encoding and decoding as an alternative method for data serialization, emphasizing its compatibility with various programming languages. Additionally, the document outlines core web techniques in PHP, including server-side scripting, form handling, database interaction, and security best practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Serialization:

Most often we need to store a complex array in the database or in a file


from PHP. Some of us might have surely searched for some built-in
function to accomplish this task. Complex arrays are arrays with elements
of more than one data-types or array. But, we already have a handy
solution to handle this situation. We don't have to write our own function to
convert the complex array to a formatted string. There are two popular
methods of serializing variables.
 serialize()
 unserialize()
We can serialize any data in PHP using the serialize() function. The
serialize() function accepts a single parameter which is the data we want
to serialize and returns a serialized string. Below program illustrate this:

<?php
// a complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);

// convert to a string
$string = serialize($myvar);

// printing the serialized data


echo $string;

?>
Output:
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:
0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
From the above code, we have a variable with serialized data, $string .
We can unserialize the value of the variable using 𝒖𝒏𝒔𝒆𝒓𝒊𝒂𝒍𝒊𝒛𝒆() function
to get back to the original value of the complex array, $myvar. Below
program illustrate both serialize() and unserialize() functions:

<?php

// a complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);

// serialize the above data


$string = serialize($myvar);

// unserializing the data in $string


$newvar = unserialize($string);

// printing the unserialized data


print_r($newvar);

?>
Output:
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)

[3] => apple


)
This was the native PHP serialization method. However, since JSON has
become so popular in recent years, they decided to add support for it in
PHP 5.2. Now you can use
the json_encode() and json_decode() functions as well for serializing
and unserializing data in PHP respectively. Since the JSON format is text
only, it can be easily sent to and from a server and can be used as a data
format by any programming language.

Lets have a look how to use json_encode() in PHP:


<?php

// a complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);

// serializing data
$string = json_encode($myvar);

// printing the serialized data


echo $string;

?>
Output:
["hello",42,[1,"two"],"apple"]
We can decode the data encoded in above program using the
json_decode() function to get the original complex array. Below program
illustrate this:
<?php

// a complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);

// serializing data
$string = json_encode($myvar);

// decoding the above encoded string


$newvar = json_decode($string);
// printing the decoded data
print_r($newvar);

?>
Output:
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)

[3] => apple


)
Note: JSON encoding and decoding is more compact, and best of all,
compatible with javascript and many other languages. However, for
complex objects, some information may be lost.
Web Techniques:

Web techniques in PHP refer to the methods used to create dynamic, interactive,
and secure web applications on the server side. These techniques manage client-
server communication, handle data, and generate dynamic HTML content.

Core Web Techniques in PHP


 Server-Side Scripting: PHP code is executed on the web server (e.g., Apache,
Nginx) before the result (plain HTML, JSON, etc.) is sent to the client's browser. This
is the foundation of dynamic content generation.

 Form Handling: PHP processes data submitted through HTML forms using the
superglobal arrays $_GET and $_POST . This allows the collection and processing of
user input, including file uploads via $_FILES .

 Database Interaction: PHP provides robust support for interacting with various
databases like MySQL, PostgreSQL, and SQLite. This is essential for storing and
retrieving dynamic data using extensions like PDO (PHP Data Objects) or MySQLi
for secure, prepared statements.
 Session and Cookie Management: Since HTTP is a stateless protocol, PHP uses
cookies (stored on the client side via setcookie() and accessed by $_COOKIE )
and sessions (data stored securely on the server side, tracked by a session ID
cookie using session_start() and $_SESSION ) to maintain user state and track
activity across multiple pages.

 Browser Redirection: The header() function is used to send raw HTTP headers
to the browser, which can redirect the user to a different URL (e.g., after a form
submission or login).

Advanced Techniques & Best Practices


 Security: Safeguarding applications is critical. Techniques include using prepared
statements to prevent SQL injection, filtering and sanitizing user input, hashing
passwords, and implementing protection against cross-site scripting (XSS) and
cross-site request forgery (CSRF).

 Error Handling and Debugging: Implementing effective error reporting using


functions like set_error_handler() and utilizing debugging tools like Xdebug helps
maintain application stability.

 Object-Oriented Programming (OOP): Modern PHP supports full OOP features


including classes, objects, inheritance, interfaces, and traits, which promotes
modular, reusable, and maintainable code, especially in large-scale applications and
frameworks like Laravel and Symfony.

 Performance Optimization: Techniques to enhance speed and efficiency include


caching mechanisms (like opcode caching, e.g., APCu, or data caching with
Memcached/Redis), database indexing, and lazy loading of resources.

 Web Services and APIs: PHP can be used to build and consume RESTful APIs
using libraries like cURL and data formats such as JSON or XML, enabling
communication between different software components.

 Dependency Management: Tools like Composer are used to manage project


dependencies and external libraries efficiently.
 PHP is a server-side scripting language that is used to create dynamic webpages. It is
one of the most popular programming languages for web development. This chapter
aims to let you get familiarized with certain important concepts of web application
development using PHP.
 A web-based application is a collection of webpages. A webpage is mainly created
with HTML tags. HTML consists of different HTML tags which are required to
define the appearance of page elements like text, image, table, etc. Hence, HTML
essentially creates a static webpage.
 A Web application is hosted on a HTTP server with PHP module installed. The
browser acts as a http client, to establish communication with the server, following
HTTP protocol.

How to Add Dynamic Content on a Webpage?

To add dynamic content in a webpage, there are two


possibilities.
JavaScript is a client-side scripting language, that can
access the HTML document object model and render
dynamic content on the client browser. JavaScript code
can be embedded in HTML page.
The browser may collect data from the user in the form
of HTML form elements and send it to a HTTP server
for processing. PHP is a widely used Server-side
processing language. PHP script can also be embedded
inside HTML page.

Example

In the following script, JavaScript code embedded in


HTML renders the current date as per the client
browser, and the PHP code displays the current date as
per the server, where this script is hosted.

<!DOCTYPE html>

<html>

<body>

<script type="text/JavaScript"> [Link]("Client's date


:"+Date()+"\n");

</script>

<?php date_default_timezone_set("Asia/Calcutta"); echo


"server's date is " . date("Y-m-d") . "\n"; echo "The time is
" . date("h:i:sa"); ?>

</body>

</html>

PHP can intercept and process the data from HTML forms. This
allows you to collect information from your users. The
next chapter discusses PHP form handling.
PHP can be used to interact with databases such as MySQL
and PostgreSQL. This allows you to store and retrieve
data from your database, and dynamically populate the
web pages or to power the web applications. PHP
includes mysql, mysqli and PDO extensions for
database handling.

PHP can handle the data received from the client with HTTP
GET as well as POST methods. We shall discuss in
detail, how PHP handles GET/POST methods in one of
the latter chapters.

HTTP is a stateless protocol. However, it allows Sessions


and cookies to be maintained on server and client
respectively. PHP can be used to create and manage
sessions and cookies. Sessions allow you to track
individual users as they navigate your website, while
cookies allow you to store information on the user's
computer for later use. In of the subsequent chapters,
we shall learn how PHP handles sessions and cookies.

PHP can be used to upload files to your web server. This allows
you to create web applications that allow users to
upload files, such as images, videos, or documents.

You can use PHP to create a login page for your website. When
the user enters their username and password, PHP can
check the database to see if the user is valid. If the
user is valid, PHP can log the user in and redirect them
to the main page of your website.

Server Information:
PHP - $_SERVER

The $_SERVER is a superglobal in PHP. It includes


information about HTTP headers, path, script location,
and other things. It is an associative array that
contains information about the execution environment
and server.

The majority of these details are filled in by the web


server and each server may have different entries.
When running PHP scripts from the command line,
some of these entries might not be available.

PHP also generates additional objects using request


headers. The header name, which is in uppercase and
has underscores instead of hyphens, is followed by the
term "HTTP_" for these items.

Key Points about the $_SERVER

$_SERVER is a superglobal in PHP. It holds information


regarding HTTP headers, path and script location, etc.

 $_SERVER is an associative array and it holds all the


server and execution environment related information.
 Most of the entries in this associative array are
populated by the web server. The entries may change
from one web server to other, as servers may omit
some, or provide others.
 For a PHP script running on the command line, most of
these entries will not be available or have any meaning.
 PHP will also create additional elements with values from
request headers. These entries will be named "HTTP_"
followed by the header name, capitalized and with
underscores instead of hyphens.
 For example, the "Accept-Language" header would be
available as $_SERVER['HTTP_ACCEPT_LANGUAGE'].
 PHP versions prior to 5.4.0 had $HTTP_SERVER_VARS
which contained the same information but it has now
been removed.
Server Variables

The following table lists some of the important server


variables of the $_SERVER array followed by the
description of their values.

[Link] Server Variables & Description

1 PHP_SELF
Stores filename of currently executing script.

SERVER_ADDR
2 This property of array returns the IP address of the server under which th
script is executing.

SERVER_NAME
3 Name of server host under which the current script is executing. In case o
running locally, localhost is returned.

QUERY_STRING
A query string is the string of key value pairs separated by the "&" symbo
4 appended to the URL after the "?" symbol.
For example, [Link] URL returns
query string

REQUEST_METHOD
HTTP request method used for accessing a URL, such as POST, GET, PO
5 or DELETE.
In the above query string example, a URL attached to query string with th
symbol requests the page with GET method

DOCUMENT_ROOT
Returns the name of the directory on the server that is configured as the d
6 root.
On XAMPP apache server, it returns htdocs as the name of document ro
c:/xampp/htdocs
7 REMOTE_ADDR
IP address of the machine from where the user is viewing the current pag

SERVER_PORT
8 Port number on which the web server is listening to the incoming request
is 80

9 SCRIPT_FILENAME
The absolute path to the currently executing script.

10 HTTP_HOST
The contents of the Host header from the current request.

11 SCRIPT_NAME
Contains the path of the current script relative to the document root.

12 REQUEST_URI
The URI that was given to access the page, including the query string.

13 HTTPS
Set to 'on' if the request was made over HTTPS, otherwise not set.

14 SERVER_PROTOCOL
The name and version of the information protocol used, like HTTP/1.1 or

15 GATEWAY_INTERFACE
The version of the CGI specification that the server uses, like CGI/1.1.

Example

The following script invoked from document root of


XAMPP server lists all the server variables –

<?php

foreach ($_SERVER as $k=>$v)

echo $k . "=>" . $v . "\n";

?>
Processing Forms:
Form handling is the process of collecting and processing
information that users submit through HTML forms. In PHP, we
use special tools called $_POST and $_GET to gather the data
from the form. Which tool to use depends on how the form
sends the data—either through the POST method (more
secure, hidden in the background) or the GET method (data is
visible in the URL).
 Collecting Data: Retrieving form data using PHP.
 Validating Data: Ensuring that the input meets expected
formats.
 Sanitizing Data: Cleaning up the data to prevent malicious
content.
 Processing Data: Using the data for its intended purpose
(e.g., saving to a database, sending an email, etc.).
 Returning a Response: Displaying feedback to the user or
redirecting them to another page.
Form Attributes
 action: The action attribute specifies the URL where the
form data will be sent when the form is submitted.
<form method="post" action="process_form.php">
 method: The method attribute specifies the HTTP method
(GET or POST) to use when sending form data.
<form method="post" action="process_form.php">
 name: The name attribute is crucial in PHP form handling,
as it is used to refer to the data submitted by the form fields.
$username = $_POST['username']; // Accessing
the form data
 target: The target attribute specifies where to display the
response after submitting the form. It determines where the
resulting page (or response) will appear once the form is
submitted.
<form method="post" action="process_form.php"
target="_blank">
<input type="text" name="username"
required>
<input type="submit" value="Submit">
</form>
 enctype: The enctype (encoding type) attribute defines how
the form data should be encoded when submitted to the
server. This is particularly important when submitting forms
that include file uploads.
Form Elements
Form processing contains a set of controls through which the
client and server can communicate and share information. The
controls used in forms are:
 Input Field: Input field is the most common form element,
allowing users to input a single line of text, such as their
name, address, or any other simple text information.
<input type="text" name="fullname" required>
 Password Input Field: The password input field hides the
text entered, making it suitable for secure data entry like
passwords.
<input type="password" name="password"
required>
 Checkboxes: Checkboxes allow users to select multiple
options from a set of choices. They are often used for lists of
features or permissions.
<input type="checkbox" name="subscribe"
value="yes"> Subscribe to newsletter
 Radio Buttons: Radio buttons allow the user to choose only
one option from a set of predefined options. This is useful for
binary choices, such as gender selection.
<input type="radio" name="gender"
value="female"> Female
<input type="radio" name="gender" value="male">
Male
 Textarea: The textarea element allows users to input
multiple lines of text, making it useful for longer messages,
feedback, or comments.
<textarea name="message" rows="5" cols="40"
required></textarea>
Creating a Simple Form
<html>
<body>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<table>
<tr>
<td>Full Name:</td>
<td><input type="text"
name="fullname"></td>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="email"
name="user_email"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text"
name="user_age"></td>
</tr>
<tr>
<td>Feedback:</td>
<td><textarea
name="user_feedback" rows="4"
cols="40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type="radio"
name="user_gender" value="female">Female
<input type="radio"
name="user_gender" value="male">Male
</td>
</tr>
<tr>
<td colspan="2"><input
type="submit" name="submit"
value="Submit"></td>
</tr>
</table>
</form>

<?php
$fullname = $user_email = $user_gender
= $user_feedback = $user_age = "";

// Check if the form was submitted


if ($_SERVER["REQUEST_METHOD"] ==
"POST") {
// Only process the POST data if
the form is submitted
if (isset($_POST['fullname'])) {
$fullname =
htmlspecialchars($_POST['fullname']);
}
if (isset($_POST['user_email'])) {
$user_email =
htmlspecialchars($_POST['user_email']);
}
if (isset($_POST['user_age'])) {
// Corrected variable to user_age
$user_age =
htmlspecialchars($_POST['user_age']);
}
if (isset($_POST['user_feedback']))
{
$user_feedback =
htmlspecialchars($_POST['user_feedback']);
}
if (isset($_POST['user_gender'])) {
$user_gender =
htmlspecialchars($_POST['user_gender']);
}
}

// Display the submitted details


echo "<h2>Details Submitted:</h2>";
echo "Full Name: " . $fullname .
"<br>";
echo "Email: " . $user_email . "<br>";
echo "Age: " . $user_age . "<br>";
echo "Feedback: " . $user_feedback .
"<br>";
echo "Gender: " . $user_gender;
?>
</body>
</html>
The Form Element

The HTML code of the form looks like this:

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">

When the form is submitted, the form data is sent with


method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that


returns the filename of the currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data
to the page itself, instead of jumping to a different page. This
way, the user will get error messages on the same page as the
form.

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters


into HTML entities. This means that it will replace HTML
characters like < and > with &lt; and &gt;. This prevents
attackers from exploiting the code by injecting HTML or
Javascript code (Cross-site Scripting attacks) in forms.

Warning!

The $_SERVER["PHP_SELF"] variable can be used by hackers!

If PHP_SELF is used in your page then a user can enter a


slash / and then some Cross Site Scripting (XSS) commands to
execute.

Cross-site scripting (XSS) is a type of computer security


vulnerability typically found in Web applications. XSS
enables attackers to inject client-side script into Web pages
viewed by other users.

Assume we have the following form in a page named


"test_form.php":

<form method="post" action="<?php echo


$_SERVER["PHP_SELF"];?>">
Now, if a user enters the normal URL in the address bar like
"[Link] the above code will
be translated to:

<form method="post" action="test_form.php">

So far, so good.

However, consider that a user enters the following URL in the


address bar:

[Link]
t%3Ealert('hacked')%3C/script%3E

In this case, the above code will be translated to:

<form method="post"
action="test_form.php/"><script>alert('hacked')</sc
ript>

This code adds a script tag and an alert command. And when
the page loads, the JavaScript code will be executed (the user
will see an alert box). This is just a simple and harmless example
how the PHP_SELF variable can be exploited.

Be aware of that any JavaScript code can be added inside the


<script> tag! A hacker can redirect the user to a file on
another server, and that file can hold malicious code that can
alter the global variables or submit the form to another address
to save the user data, for example.

How To Avoid $_SERVER["PHP_SELF"] Exploits?


$_SERVER["PHP_SELF"] exploits can be avoided by using
the htmlspecialchars() function.

The form code should look like this:

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">

The htmlspecialchars() function converts special characters


to HTML entities. Now if the user tries to exploit the PHP_SELF
variable, it will result in the following output:

<form method="post"
action="test_form.php/&quot;&gt;&lt;script&gt;alert
('hacked')&lt;/script&gt;">

The exploit attempt fails, and no harm is done!

You might also like