0% found this document useful (0 votes)
11 views

chapter-9

This document covers PHP arrays and superglobals, detailing how arrays function as dynamic data structures that can store related elements and how to define, access, and manipulate them. It also explains superglobal arrays like $_GET and $_POST, which facilitate access to data sent by clients, and the $_SERVER array that contains server-related information. Additionally, it touches on file uploads using the $_FILES array and the necessary HTML and PHP configurations for handling file uploads.

Uploaded by

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

chapter-9

This document covers PHP arrays and superglobals, detailing how arrays function as dynamic data structures that can store related elements and how to define, access, and manipulate them. It also explains superglobal arrays like $_GET and $_POST, which facilitate access to data sent by clients, and the $_SERVER array that contains server-related information. Additionally, it touches on file uploads using the $_FILES array and the necessary HTML and PHP configurations for handling file uploads.

Uploaded by

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

PHP ARRAYS AND

SUPERGLOBALS

Chapter 9

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Textbook to be published by Pearson ©
Ed2015
in early
Pearson
2014
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
http://www.funwebdev.com
Objectives
1 Arrays
2 $_GET and
$_POST
Superglobal
arrays

3 $_SERVER
Array 4
5
7
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Section 1 of 5

ARRAYS
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Arrays
Background

An array is a data structure that


• Collects a number of related elements together in a
single variable.
• Allows the set to be Iterated
• Allows access of any element
Since PHP implements an array as a dynamic structure:
• Add to the array
• Remove from the array

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Key Value

In PHP an array is actually an ordered map, which


associates each value in the array with a key.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Keys

Array keys are the means by which you refer to s ingle


element in the array.
In most programming languages array keys are limited
to integers, start at 0, and go up by 1.
In PHP, array keys must be either integers or strings
and need not be sequential.
• Don’t mix key types i.e. “1” vs 1
• If you don’t explicitly define them they are 0,1,…

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Defining an array

The following declares an empty array named days:


$days = array();
You can also initialize it with a comma-delimited list of
values inside the ( ) braces using either of two
following syntaxes:
$days = array("Mon","Tue","Wed","Thu","Fri");
$days = ["Mon","Tue","Wed","Thu","Fri"]; // alternate

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Defining an array

You can also declare each subsequent element in the


array individually:
$days = array();
$days[0] = "Mon"; //set 0th key’s value to “Mon”
$days[1] = "Tue";
// also alternate approach
$daysB = array();
$daysB[] = "Mon"; //set the next sequential value to
“Mon”
$daysB[] = "Tue";
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Arrays
Access values

To access values in an array you refer to their key using the


square bracket notation.
echo "Value at index 1 is ". $days[1];

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Keys and Values

In PHP, you are also able to explicitly define the keys in


addition to the values.
This allows you to use keys other than the classic 0, 1,
2, . . . , n to define the indexes of an array.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Super Explicit
Array declaration with string keys, integer values

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Multidimensional Arrays
Creation

$month = array(
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri")
);
echo $month[0][3]; // outputs Thu

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Multidimensional Arrays
Access

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Multidimensional Arrays
Another example

$cart = array();

$cart[] = array("id" => 37, "title" => "Burial at Ornans", "quantity" => 1);

$cart[] = array("id" => 345, "title" => "The Death of Marat", "quantity" => 1);

$cart[] = array("id" => 63, "title" => "Starry Night", "quantity" => 1);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Iterating through an array

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Iterating through an array
Foreach loop is pretty nice

The challenge of using the classic loop structures is that when


you have nonsequential integer keys (i.e., an associative array),
you can’t write a simple loop that uses the $i++ construct. To
address the dynamic nature of such arrays, you have to use
iterators to move through such an array.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Adding to an array
To an array

An element can be added to an array simply by using a


key/index that hasn’t been used
$days[5] = "Sat";
A new element can be added to the end of any array

$days[ ] = "Sun";

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Adding to an array
And quickly printing

PHP is more than happy to let you “skip” an index


$days = array("Mon","Tue","Wed","Thu","Fri");
$days[7] = "Sat";
print_r($days);

Array ([0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri [7] => Sat)’

If we try referencing $days[6], it will return a NULL value

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Deleting from an array

You can explicitly delete array elements using the unset() function

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Deleting from an array

You can explicitly delete array elements using the unset() function.
array_values() reindexes the array numerically

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Checking for a value

Since array keys need not be sequential, and need not be integers,
you may run into a scenario where you want to check if a value has
been set for a particular key.
To check if a value exists for a key, you can therefore use the isset()
function, which returns true if a value has been set, and false otherwise

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Array Sorting
Sort it out

There are many built-in sort functions, which sort by key or by value.
To sort the $days array by its values you would simply use:
sort($days);
As the values are all strings, the resulting array would be:
Array ([0] => Fri [1] => Mon [2] => Sat [3] => Sun [4] => Thu [5] => Tue [6] => Wed)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


More array operations
Too many to go over in depth here…

• array_keys($someArray)
• array_values($someArray)
• array_rand($someArray, $num=1)
• array_reverse($someArray)
• array_walk($someArray, $callback, optionalParam)
• in_array($needle, $haystack)
• shuffle($someArray)
• …

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


array_keys($someArray): This method returns an
indexed array with the values being the keys of
$someArray.
For example, print_r(array_keys($days)) outputs
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


array_values($someArray): Complementing the above
array_keys() function, this function returns an indexed
array with the values being the values of $someArray.
For example, print_r(array_values($days)) outputs
Array ( [0] => Mon [1] => Tue [2] => Wed [3] => Thu [4]
=> Fri )

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


For example, print_r(array_rand($days,2)) might
output:
Array (3, 0)
array_reverse($someArray): This method returns
$someArray in reverse order. The passed $someArray
is left untouched.
For example, print_r(array_reverse($days)) outputs:
Array ( [0] => Fri [1] => Thu [2] => Wed [3] => Tue [4]
=> Mon )

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 2 of 5
$_GET AND $_POST SUPERGLOBAL ARRAYS

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


•Determine if any data sent
•Accessing Form Array Data
•Using Query Strings in
Hyperlinks
•Sanitizing Query Strings

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Superglobal Arrays

PHP uses special predefined associative arrays called


superglobal variables that allow the programmer to
easily access HTTP headers, query string parameters,
and other commonly needed information.
They are called superglobal because they are always in
scope, and always defined.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


$_GET and $_POST
Sound familiar?

The $_GET and $_POST arrays are the most important


superglobal variables in PHP since they allow the
programmer to access data sent by the client in a
query string.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
$_GET and $_POST
Sound familiar?

• Get requests parse query strings into the $_GET


array
• Post requests are parsed into the $POST array

This mechanism greatly simplifies accessing the data


posted by the user, since you need not parse the query
string or the POST request headers!

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Determine if any data sent

•a single file is often used to display a login form to the


user, and that same file also handles the processing of
the submitted form data
•In such cases you may want to know whether any
form data was submitted at all using either POST or
GET.
•In PHP, there are several techniques to accomplish
this task.
•First, you can determine if you are responding to a
POST or GET by checking the
$_SERVER['REQUEST_METHOD'] variable

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Determine if any data sent
Isset()

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Determine if any data sent

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Accessing Form Array Data

Sometimes in HTML forms you might have multiple


values associated with a single name;

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Accessing Form Array Data
HTML tweaks for arrays of data

Unfortunately, if the user selects more than one day and


submits the form, the $_GET['day'] value in the superglobal
array will only contain the last value from the list that was
selected.
To overcome this limitation, you must change the name
attribute for each checkbox from day to day[].
Monday <input type="checkbox" name="day[]" value="Monday" />

Tuesday <input type="checkbox" name="day[]" value="Tuesday" />

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Using Query String in
Links
Design idea

Imagine a web page in which we are displaying a list of


book links. One approach would be to have a separate
page for each book.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Using Query Strings in
links
Not a great setup

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Using Query Strings in
links
Use the query string to reduce code duplication

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Sanitizing Query Strings

Just because you are expecting a proper query string,


doesn’t mean that you are going to get a properly
constructed query string.

• distrust all user input


The process of checking user input for incorrect or
missing information is sometimes referred to as the
process of sanitizing user inputs.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Sanitation

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 3 of 5
$_SERVER ARRAY

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


•Server Information Keys
•Request Header Information Keys

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


$_SERVER

The $_SERVER associative array contains


• HTTP request headers (send by client)
• configuration options for PHP
To use the $_SERVER array, you simply refer to the
relevant case-sensitive keyname:
echo $_SERVER["SERVER_NAME"] . "<br/>";
echo $_SERVER["SERVER_SOFTWARE"] . "<br/>";
echo $_SERVER["REMOTE_ADDR"] . "<br/>";

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


$_SERVER

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


SERVER INFORMATION
KEYS
• SERVER_NAME contains the name of the site that
was requested
• SERVER_ADDR tells us the IP of the server
• DOCUMENT_ROOT tells us the location from which
you are currently running your script
• SCRIPT_NAME key that identifies the actual script
being executed

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Request Header Keys

• REQUEST_METHOD returns the request method


that was used to access the page: that is, GET,
HEAD, POST, PUT
• REMOTE_ADDR key returns the IP address of the
requestor
• HTTP_USER_AGENT contains the operating system
and browser that the client is using
• HTTP_REFERER contains the address of the page
that referred us to this one (if any) through a link

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


9.4 $_FILES Array

•HTML Required for File Uploads


•Handling the File Upload in PHP
•Checking for Errors
•File Size Restrictions
•Limiting the Type of File Upload
•Moving the File

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


9.4.1 HTML Required for File
Uploads

To allow users to upload files, there are some specific


things you must do:
■ First, you must ensure that the HTML form uses the
HTTP POST method
■ Second, you must add the
enctype="multipart/form-data" attribute to the HTML
form that is performing the upload so that the HTTP
request can submit multiple pieces of data
■ Finally you must include an input type of file in your
form.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
9.4.2 Handling the File Upload in
PHP

The corresponding PHP file responsible for handling


the upload will utilize the superglobal $_FILES array.
This array will contain a key=value pair for each file
uploaded in the post.
The key for each element will be the name attribute
from the HTML form

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


The values for each of the keys, in general, are described below.
■ name is a string containing the full file name used on the client
machine, including any file extension. It does not include the file path on
the client’s machine.
■ type defines the MIME type of the file. This value is provided by the
client
browser and is therefore not a reliable field.
■ tmp_name is the full path to the location on your server where the file
is being temporarily stored. The file will cease to exist upon termination
of the script, so it should be copied to another location if storage is
required.
■ error is an integer that encodes many possible errors and is set to
UPLOAD_ERR_OK (integer value 0) if the file was uploaded successfully.
■ size is an integer representing the size in bytes of the uploaded file.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
9.4.3 Checking for
Errors

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


9.4.4 File Size
Restrictions
•Some scripts limit the file size of each upload.
There are three main mechanisms for maintaining
uploaded file size restrictions: via HTML in the input
form, via JavaScript in the input form, and via PHP
coding.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
9.4.5 Limiting the Type of File
Upload

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


9.4.6 Moving the File

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Reading/Writing Files

There are two basic techniques for read/writing files in


PHP:
■ Stream access.
■ All-In-Memory access.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


In this technique, our code will read just a small
portion of the file at a time.
While this does require more careful programming, it
is the most memory-efficient approach when reading
very large files.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


In this technique, we can read the entire file into
memory (i.e., into a PHP variable).
While not appropriate for large files, it does make
processing of the file extremely easy.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


The function fopen() takes a file location or URL and
access mode as parameters.
The returned value is a stream resource, which you
can then read sequentially.
Some of the common modes are “r” for read, “rw” for
read and write, and “c,” which creates a new file for
writing.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


•Once the file is opened, you can read from it in several ways.
• To read a single line, use the fgets() function, which will
return false if there is no more data, and if it reads a line it
will advance the stream forward to the next one so you can
use the === check to see if you have reached the end of the
file.
• To read an arbitrary amount of data (typically for binary
files), use fread() and for reading a single character use
fgetsc().
•Finally, when finished processing the file you must close it
•To write data to a file, you can employ the fwrite()
functioning fclose().

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


In-Memory File Access

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


To read an entire file into a variable you can simply
use:
$fileAsString = file_get_contents(FILENAME);
To write the contents of a string $writeme to a file, you
use
file_put_contents(FILENAME, $writeme);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


01070,Picasso,The Actor,1904
01080,Picasso,Family of Saltimbanques,1905
02070,Matisse,The Red Madras Headdress,1907
05010,David,The Oath of the Horatii,1784

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
What You’ve Learned
1 Arrays
2 $_GET and
$_POST
Superglobal
arrays

3 $_SERVER
Array

7
Randy Connolly and Ricardo Hoar Fundamentals of Web Development

You might also like