0% found this document useful (0 votes)
4 views28 pages

Server Linking

Chapter 23 discusses server-side and client-side scripting, focusing on PHP and JavaScript. PHP, created in 1994, is a server-side language that processes code on the server before sending results to the user, while JavaScript is a client-side language that runs in the user's browser. The chapter also highlights the differences between the two languages, including their syntax and use cases, as well as best practices for integrating JavaScript into web development.

Uploaded by

bappherhjr11
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)
4 views28 pages

Server Linking

Chapter 23 discusses server-side and client-side scripting, focusing on PHP and JavaScript. PHP, created in 1994, is a server-side language that processes code on the server before sending results to the user, while JavaScript is a client-side language that runs in the user's browser. The chapter also highlights the differences between the two languages, including their syntax and use cases, as well as best practices for integrating JavaScript into web development.

Uploaded by

bappherhjr11
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
You are on page 1/ 28

Chapter 23

Server-Side and
Client-Side Scripting

HTTP Scripting
Database
Server Language

Operating System (Linux,


Windows, Mac)

Hardware
PHP
Created in 1994 at the hands of Rasmus Lerdorf, PHP began as a set of CGI scripts
developed to track views of his resume online. Rasmus continued adding scripts to his
collection so he could do more with his websites. Over time, some friends began to use it
as well. By June of 1995, enough of a framework was in place that Rasmus decided to make
PHP public. As others embraced it, and began to submit their own work, PHP grew. By
version 3 it was decided that the time had come for a more professional name. In homage
to its original name of Personal Home Page, the PHP acronym was kept, but was changed
to a recursive representation of “hypertext preprocessor.” PHP was now an independent
language, with object-oriented capabilities, high extensibility, and had a growing following.
As the community grew, the core team of Rasmus, Andi Gutmans and Zeev Suraski
continued their work. Gutmans and Suraski rewrote the core of the engine, and dubbed
version 4 Zend, a blend of Gutmans and Suraski’s first names. Now with dozens of devel-
opers and even more contributors, PHP has grown to version 5, and is installed on tens
of millions of servers around the world. It continues to rank as one of the top ten web
development languages.
With strong semblance to languages like C++ and Perl, the goal was to create a language
that allowed fast development of dynamic pages. It is a server-side language, which means

149
The Missing Link: An Introduction to Web Development and Programming Chapter 23

it runs on the server before anything is sent to the user’s computer. This is in contrast to
client-side languages, where the code is sent to the user’s computer to be processed locally
with languages like JavaScript.
Some advantages to server-side languages are that the code is hidden from the user,
and secures what is taking place in the background. It also reduces the work load that the
user’s computer is burdened with. This, however, also means the server must be powerful
enough to support the number of users requesting pages, as it must bear the brunt of the
computation.
PHP is a parsing engine, which means it examines the php file, performs any php related
tasks it finds, and passes the result to the web server. This makes it an interpreted language,
as the output and script are run on demand, as opposed to a compiled language where the
code is transformed and saved into a runnable form.

JavaScript
JavaScript is a client-side script, meaning the browser processes the code instead of the
web server. Client-side scripts are commonly used when we want to validate data before
sending it to the web server, adjusting the interface in response to user feedback, and for
implementing other advanced features. Since JavaScript is part of the browser, it can be
run without a web server present. If the computer is slow or busy, the performance of our
code may be reduced. If JavaScript is disabled (less of a concern today than just a few years
ago) then our script will not run. This being said, this is less of an issue now, and JavaScript
can reduce the number of communications to a server, reducing transmission time and
improving performance.
JavaScript will be our client-side scripting example. As JavaScript can be handled within
the browser, we can capitalize on it to validate user data, react to user actions that affect ap-
pearance, and interact with the user’s computer, without requiring the involvement of their
internet connection or our server. Like CSS, JavaScript is not a fully formed language that
can stand on its own. Like PHP and Java, JavaScript is an object-oriented language that is
multi-platform. Unlike Java (but still like PHP) it is a loose, typed language.
There is a common misconception that Java and JavaScript are the same thing. Review
some of the larger differences between them below if you are already familiar with Java.
Table 7 Java vs JavaScript

JavaScript Java

Object-oriented. No distinction between types Class-based. Objects are divided into classes
of objects. Inheritance is through the prototype and instances with all inheritance through the
mechanism, and properties and methods can be class hierarchy. Classes and instances cannot
added to any object dynamically. have properties or methods added dynamically.

Variable data types are not declared (dynamic Variable data types must be declared (static
typing). typing).

Cannot automatically write to hard disk. Cannot automatically write to hard disk.

150
The Missing Link: An Introduction to Web Development and Programming Chapter 23

Writing JavaScript code is a lot like writing PHP. Both languages use many of the same
concepts and can look very similar in terms of code. Since we will have covered many of
the foundational concepts JavaScript uses in the PHP section, we will focus on differences
between JavaScript and PHP. We will look at examples that highlight how JavaScript can
be integrated with other languages, like responding to event driven actions to modify our
pages in real time. Bear in mind that the power of the language can be used to perform
many of the same tasks we have examined already in PHP.
A best practice for using JavaScript in your site is to create your entire site without
it, and then add it where it can improve the user experience (a process called progressive
enhancement). This will help ensure that your site will still operate (albeit maybe not as
attractively) if JavaScript is not present.

151
Chapter 24

Creating PHP Files

Like the HTML and CSS files we have already created, PHP also uses a special file format
to identify its contents. When you want to use PHP in a file, even if it was already .htm or
.html, you will need to set (or create) the file format as .php.
If you do not have access to a server with PHP, you can follow along this section of the
text by using http://writecodeonline.com/php/ to try the examples and write your own
code.

ADDITIONAL NOTES

Technically, you could insert PHP code into HTML files (or other formats) and
have it run, by changing settings on your server for how it serves and interacts
with the file extension in question. You could also do the same with HTML in a
text file, or other combinations. The drawback is this could also affect other files
on your server, and makes your site less portable to other servers.

Long, Short Tags


As you begin to work with PHP, you will undoubtedly see code examples that begin with
<?php or <?, while both will end with ?>. These are tags, just like in HTML, and are used to
mark the start and end of a section of code that contains PHP (we could even use <script
language=‘php’></script>). PHP can be interspersed, or cohabitate, in a web page among
HTML and other languages like JavaScript. The difference between the two opening tags
is that <?php is longhand writing, while <? Is considered shorthand. By default, all PHP
capable servers will recognize longhand while shorthand is an option that must be enabled.
For best support of your code, and to better recognize what language is being used, always
use longhand when writing your code.

152
Chapter 25

PHP Errors

Before starting, an understanding of errors will help you quickly recognize where problems
exist (and if they are truly problems) in your code, which will lend to faster debugging and
understanding where to look for problems.
To start with, we can tell PHP what kind of errors we want to know about before we
even run a script. While the full list of supported reporting levels (see Table 8 PHP Errors)
covers a variety of concerns, there are a few (notices, errors, and warnings) that cover what
we will run into most often.

Notices
Notice: Undefined index: message in /home/example.php on line 9
Notices, technically, are not errors. They will notify us of things that we may have in-
tended or wanted, but that PHP can do without. For example, using a variable on a page
without declaring it first will generate a notice. PHP will create the variable as soon as it is
called, even if we did not declare it, without creating a formal error (other languages would
consider this an error worthy of breaking execution). By notifying us but still continuing, if
we had already declared or used the variable elsewhere, this notice would indicate a spelling
error or mistyped variable name.

Warnings
Warning: main(): Failed opening 'noFileHere.php' for inclusion
on line 2
Warnings still will not stop our script from running, but indicate that something has
gone wrong during execution of a script. Attempting to use include() on a file that does not
exist would create a warning.

Errors
PHP Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFF-
ERED_QUERY' in database.inc on line 43

153
The Missing Link: An Introduction to Web Development and Programming Chapter 25

Finally, errors are unrecoverable (execution will stop). Typical causes of errors are parsing
errors like missing semi-colons, function, or class definitions, or other problems the engine
does not know how to resolve. If we used require() on a file instead of include, an error
would be triggered instead.
Most errors that we will receive are parsing errors. They are typically problems caused by
what we wrote in our code, like missing brackets, semi-colons, or typos. When we receive
an error, the compiler will tell us what problem it discovered and where. Keep in mind that
we are being told where an error was found not necessary where the source of the problem
exists. For example, a missing semi colon or bracket may have occurred several lines before
it created a problems for the compiler.
The other category of errors we will run into are logical. These are errors caused by how
we wrote our code, and can be much more frustrating. Logical errors are usually discovered
when the script does not behave as expected. The source can be mistakes in what code we
run in different parts of an if/then statement or even an error in math used in a function
that gives us the wrong solution.
Resolving errors can be something of an art form. With parse errors, the engine can
guide you to the area to help you begin looking for the source of the error. Logical errors
can usually be resolved by adding extra, temporary outputs to follow the value of a variable
or trace execution of logic statements through a script. This technique can help you find
where what happens differs from what you expect. Unit testing your functions will go a long
way toward preventing many of these issues, as does iterative programming.
To dictate what errors we do and do not wish to see in our script output, we will use the
error_reporting() function. By passing one or more of the constants below, we control what
is reported. For example, maybe we want information on warnings and errors, but do not
care about notices. To do this, we can call error_reporting(E_WARNING | E_ERROR).
The pipe symbol ( | )works as an or in this case. If we want to see everything except notices
we can use E_ALL but leave out notices with the carrot ( ^ ) character to indicate an ex-
ception with error_reporting(E_ALL ^ E_NOTICE). It is good practice to set your error
reporting level close to the top of your script, so you can easily find it and change settings:
<?php
error_reporting(E_WARNING | E_ERROR);
//This next line will trigger a notice that the variable does
not exist, but we will not see it
echo $test;
?>
<?php
error_reporting(E_ALL);
//This time we will see the notice
echo $test;
?>
Notice: Undefined variable: test on line 3
You may be wondering why we would selectively show or hide errors; when we are
developing our code, the system errors we will need to see in order to debug are different
from what we would want end users to see for a system in production. Revealing, verbatim,
the system generated error message is not only confusing to non-programmers but can

154
The Missing Link: An Introduction to Web Development and Programming Chapter 25

expose sensitive information to those with malicious intent. Instead, we would provide a
message we chose in the error’s place. Take a look at the full list of error reporting levels:
Table 8 PHP Errors
Constant Description
E_ERROR Fatal run-time errors. These indicate errors that cannot be recovered from, such as a memory alloca-
tion problem. Execution of the script is halted.

E_WARNING Run-time warnings (non-fatal errors). Execution of the script is not halted.
E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser.
E_NOTICE Run-time notices. Indicate that the script encountered something that could indicate an error, but
could also happen in the normal course of running a script.
E_CORE_ERROR Fatal errors that occur during PHP’s initial startup. This is like an E_ERROR, except it is generated
by the core of PHP.
E_CORE_WARNING Warnings (non-fatal errors) that occur during PHP’s initial startup. This is like an E_WARNING,
except it is generated by the core of PHP.
E_COMPILE_ERROR Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting
Engine.
E_COMPILE_ Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by
WARNING the Zend Scripting Engine.
E_USER_ERROR User-generated error message. This is like an E_ERROR, except it is generated in PHP code by
using the PHP function trigger_error().
E_USER_WARNING User-generated warning message. This is like an E_WARNING, except it is generated in PHP code
by using the PHP function trigger_error().
E_USER_NOTICE User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by
using the PHP function trigger_error().
E_STRICT Enable to have PHP suggest changes to your code which will ensure the best interoperability and
forward compatibility of your code.
E_RECOVERABLE_ Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the
ERROR Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_
handler()), the application aborts as it was an E_ERROR.

E_DEPRECATED Run-time notices. Enable this to receive warnings about code that will not work in future versions.

E_USER_DEPRECATED User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP
code by using the PHP function trigger_error().
E_ALL All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.
Adapted from php.net, Creative Commons 3.0 Attribution Unported

155
Chapter 26

PHP Output

Print, Echo
PHP allows for two methods of sending output to the screen. One is called print, the other
echo. While they provide the same functionality, echo is a construct (it will be treated as a
command), where print is an expression (it will be evaluated and will return a value). When
we use print or echo in PHP, both can be used as constructs (called without parenthesis
after them, as if they are a command) or as a function (called with parenthesis like a function
call). Print will return a 1 as a result when it is used, while echo will not return anything.
Ultimately, the differences between print and echo are negligible. Debates over which
to use range from consistency of verbiage, speed of processing (print technically takes four
operating commands to echo’s three as it has one more step of returning the 1), and obscure
examples of where one might win out over the other.
For our examination here, use what you like. In extreme examples, a high volume of
echos will be faster than a high volume of print statements, but there are far more impor-
tant places to consider refining code for speed than any gains you might find here.
To send output to the screen, we can start with the famous example of Hello, World!
<?php echo "Hello, World!"; ?>
We can also wrap the string in parenthesis as we discussed above if you feel it makes
things more clear:
<?php echo ("Hello, World!"); ?>
Congratulations, you have just created your first PHP web page!
We can get a little more in depth before moving on with another example. When func-
tions return something to us, we usually save that value and then take action on it. We can
also send the output directly to the screen if we know it is formatted how we want to view
it. The phpinfo() function for example gives us access to all the details about our server. If
we use it without requesting a specific piece of information, it defaults to returning a full
web page with all the details about our server. We can see this by using the following:
<?php echo phpinfo(); ?>
This screen shot is just a portion of the entire response, which is usually several pages
long. Keep this function in mind, as it is a convenient way of finding the settings of your
server without digging into your config files.

156
The Missing Link: An Introduction to Web Development and Programming Chapter 26

LEARN MORE
Keywords, search terms: Troubleshooting php, common programming errors

Common Programming Mistakes: http://www.dummies.com/how-to/content/troubleshooting-


a-php-script.html

Debugging with Print and Eclipse: http://www.ibm.com/developerworks/library/os-debug/

157
Chapter 27

Data Storage

Variables
Variables are created and used when our script runs in order to create references to (store
copies of ) pieces of information that are needed for a short span of time, or are expected to
change value as the script runs. They contain a reference to a place in the server’s memory
where the value is stored, not the actual content. This tells the parser where to look to
find the information we want. PHP is a loosely typed language, which means we do not
have to tell the computer what type of information we are going to keep in a variable. In
strictly typed languages, we would have to specify if the variable was going to be an integer,
string, float, or other option supported by the language in use. Trying to store a different
type of information than declared in a variable would result in an error. PHP will not give
us an error or check this by default. This eliminates the need to declare variables, but this
can result in some confusing bugs in your code. Those of you with experience in a strictly
typed language like C++ will be happy to note that although not required, PHP will allow
declarations, and will then give errors upon their misuse.
Variables in PHP must start with a dollar sign ($), and can be followed by an underscore
(_) or letter (a through z, both upper and lower case). Variables cannot start with a number,
but may contain numbers after an underscore or at least one letter; they also cannot contain
a space, as spaces are used to determine where commands, variables, and other elements
start and end. See the table below for examples:
Table 9 PHP Variable Naming
GOOD BAD
$_first $1st
$LastName $(first)name
$standard_tax_rate $first name
$last4SSN $final$

158
The Missing Link: An Introduction to Web Development and Programming Chapter 27

• Booleans Can have a value of 0 or 1


• Integers Whole numbers (1, 3, 20, etc.)
• Floating point numbers Decimal values (1.33, 34.2325)
• Strings Contain any number of characters
• Arrays Structured lists of information
• Objects Collections of related variables and functions
• Resources Special variables that hold reference points to things like files
• NULL An empty (unused or unset) variable
• Callbacks A mechanism to reference a function declared elsewhere

In the scope of this text we will cover most of these items with exception to callbacks,
and with only a cursory examination of objects. If you plan to focus on application develop-
ment, this would be a good area to continue studying. For most web development, there is
little call for robust object-oriented programming.
To create a variable in PHP, we first give the name we wish to use, followed by what we
want to assign to the variable. In PHP, the equal sign (=) is used to assign what is on the
right hand side to what is on the left hand side (we will see how to check login statements
later on). To create a variable called ourString with the value of Hello World, we would
enter the following:
$ourString = 'Hello World';
We can now refer to $ourString in one or more places of our code in order to access the
string Hello World and use it or modify it.
You might notice the semi-colon (;) at the end of the line. Semi-colons are used to tell
the interpreter where a statement ends, and where the next one begins. They are easy to
forget! If you see a syntax error, you will want to look at the line before the error to see if a
semi-colon is missing.
PHP also maintains some variables of its own, called predefined variables. These start
with underscores, and will hold certain types of values for us (avoiding the use of under-
scores at the start of your variables will help avoid colliding with these reserved variables).
Several of these variables ($_GET, $_POST and $_FILES) will hold items a user has
typed or submitted using forms. $_COOKIE and $_SESSION are used to hold informa-
tion throughout a user’s visit, and $_ENV holds information about the server.

Incrementing Methods
Until now, we have been using the equal sign strictly for assigning strings to variables.
We can also use some short hand methods of modifying numerical variables within our
code. For example, adding 1 to the variable $counter can be done with:
$counter = $counter + 1;
But we can shorten that by using the “plus equal”:
$counter +=1;
Or if we only need to add 1, the “plus plus”:
$counter++;

159
The Missing Link: An Introduction to Web Development and Programming Chapter 27

In these example, each one would add 1 to the counter. In the first two examples, we
could add more than one, or perform a calculation to be added. We can also perform the
opposite calculation, in that we can subtract and assign a given number as well by using -=
or --. Where and how you choose to embrace these is up to you, but you should be familiar
with each form in order to fully understand any code you are examining.

Strings
In our first echo examples, we printed a string to the screen. Strings are a type of variable
that hold, as seems obvious, strings of words. Full sentences can be stored in one variable
name, or can be built by combining other variables. Manipulating strings in PHP can be
done through a number of functions, which can complete tasks like finding and replacing
words, breaking strings apart, capitalizing one or all words, and a number of other useful
tasks.
Strings can be used to create output that the user reads, generate part or all of the
HTML code for a page to display, and even commands that can be passed to other lan-
guages to direct their operation.

Single, Double Quotes


Until now, when we have used strings, they have been double quoted. PHP actually
lets us use both single and double quotes when defining our strings to support different
functions. There is an important difference between the two that we need to keep in mind.
Single quoted strings are treated by the interpreter as plain text, meaning the output to
the screen will be exactly what is in quotes. Double quoted strings will be examined by
the interpreter for anything that can be processed by PHP, which means items like special
characters and variables will be replaced with what they represent before the output is
sent to the screen. For example, if we set a variable named string to Hello and use it in our
output, single quotes will ignore it while double quotes will process it:
$string = "Hello"; // The quotes we use here do not matter for
this example
echo "$string there";
echo '$string there';
Hello there
$string there

Escaping
Escape characters are symbols with special, secondary meaning when coupled with the
language’s escaping method. We can indicate that we want a new line in a text file by using
\n. In this example, n is not “just an n,” it represents that we want a newline because it is
preceded by a backslash, PHP’s escaping character. In PHP, escape characters are com-
monly used in double-quoted strings, so we can include special characters (single quoted
string will ignore this, just like other PHP commands, variables, and the like).
A helpful way to think about the escape character is that it “reverses” the character or
symbol that comes after it. If it precedes a letter, then it is supposed to do something, not

160
The Missing Link: An Introduction to Web Development and Programming Chapter 27

display the letter. If it precedes a symbol, the symbol has a special value in PHP, but we
actually want to see the character.
Table 10 Character Escaping

\” Print the double quote, not use it as a string opening or closing marker
\’ Print the single quote, not use it as a string opening or closing marker
\n Print a new line character (for text or output files, not on the screen)
\t Print a tab character
\r Print a carriage return (for text or output files, not on the screen)
\$ Print the next character as a dollar sign, not as part of a variable
\\ Print the next character as a backslash, not an escape character
Writing $string = “I want to spend $5.00”; would result in a name error. Instead, we
can use $string= “I want to spend \$5.00”; to achieve the output we are looking for. If we
wanted to use the backslash, we could write a folder location as $address = “c:\\www\\
ourfolder\\sometext.txt”;. While we could more easily do this with single quotes as $ad-
dress = ‘c:\www\ourfolder\sometext.txt’; we would need to append any variables we wanted
to reference into the string that is single quoted.

Constants
Sometimes we need to store a piece of information, but we do not want it to change
while our script is running. To do this, we can create a constant—essentially, a variable that
we are not allowed to change. Creating a constant is done by calling the define function,
and passing a string of our constant’s name and its contents:
define("OURCONSTANT", "Our constant value");
You will notice we do not have a dollar sign in front of our constant name. In fact, to use
it, we can just echo the name:
echo OURCONSTANT;
Our example here has the constant name all uppercase. This is a practice many people
use to help distinguish between variables and constants. There are also some predefined
constants in PHP that can be useful to us, such as PHP_VERSION and PHP_OS. The
former will give us the version number for PHP, and the latter will give us details on the
operating system the server is running on. Since constants do not have a leading dollar sign,
we cannot embed them in a string, but instead need to concatenate them if we want to use
them with other output:
echo " This server runs on " . PHP_OS;
Concatenation is the act of connecting several items into one variable or output. A
period is used as we did above to denote where those pieces start and end. If we wanted to
add more to our statement, we can keep adding periods like this:
echo "This server runs on ". PHP_OS . " and use PHP version ".
PHP_VERSION;

161
The Missing Link: An Introduction to Web Development and Programming Chapter 27

Arrays
Arrays are a much dreaded topic to many programmers, and almost as frustrating as a
missing terminating character. For the uninitiated, an array is a method of storing multiple
values under one variable name as a linked list of information. This allows us to keep related
values together, and to establish relationships between data. Typically, array information is
stored in one of two different formats, either numeric or associative. In numerical format,
each element in the list (or, each piece of information) is found by referring to its place in
line. Depending on your programming language, counting may start at 1 or 0. In our case,
by default, PHP starts with 0. In order to take a look at an array, we should follow best
practices and declare our variable as an empty one to begin with. We can do this with:
$ourFirstArray = array();
Now the system will know that we intend to use this variable as an array. If we try to
echo or print our array, we would see the following output:
Array
In order to see the contents of an array, we need to refer to an actual position or view the
entire contents. Since we have not added anything yet, we will move along for now.
Here we will create a new array, but one in which we already know what we want the
first few values to be. We will set up the cast of Family Guy as an array called theGriffins.
$theGriffins = array("Peter","Lois","Stewie","Chris","Brian");
Now we can take a look at some output. If we wanted to see what the first element of
the array held, we could:
echo $theGriffins[0];
which would give us:
Peter
Or, to take a quick look at the entire array, we can use the built in function print_r, which
means print recursively, and will output each value for us in a preformatted manner:
print_r($theGriffins);
Array(
0: Peter
1: Lois
2: Stewie
3: Chris
4: Brian
)
Now, something seems amiss. Is someone missing? Oh yes, Meg. Let’s add her to our
array. To add a new element to the end of an array, we do not need to worry about knowing
how long it is, or what number to assign to the new element. With PHP we can simply
append [] to our variable name, adding Meg as a new element at the end of our array:
$theGriffins[]='Meg';
Now if we run print_r, we would see:
Array(
0: Peter
1: Lois

162
The Missing Link: An Introduction to Web Development and Programming Chapter 27

2: Stewie
3: Chris
4: Brian
5: Meg
)
Perhaps we want to make things a little more formal, and use full first names. In this
case, we need to update a few things. First, we should change Stewie to Stewart. Since we
have the reference right above this text we can see that Stewie is at position 2 (item 3) in
the array. So let us set that position to his full name:
$theGriffins[2]='Stewart';
Your print $theGriffins[2]; should now give you Stewart instead of Stewie! By placing
the item’s position number in the brackets of our array variable, we are specifying that we
want to see the information that is stored in that spot. Perhaps you have forgotten where
in the array you stored a particular value. Most languages supporting arrays will already
have built in functions for common tasks such as this. In PHP, we can use the array_search
function. In this case, we pass the values as a “needle in a haystack” pair, giving the function
first what we are looking for, and then the array in which we hope to find it:
echo array_search("Meg", $theGriffins);
will give us:
4
Note that close matches would be ignored. The interpreter does not know that Pete and
Peter, or Meg and Megan represent the same common name. For these types of searches,
we would need much more complex algorithms.
In order to update the Meg value to Megan, we will combine our techniques:
$location = array_search("Meg", $theGriffins);
$theGriffins[$location] = 'Megan';
We could, for the sake of brevity, take advantage of the inner first nature of the PHP
interpreter and combine our statements:
$theGriffins[array_search("Meg", $theGriffins)]='Megan';
Now that we are a bit more comfortable with numbered arrays, we will take a look at
associative. In this approach, we provide the reference in which we want a position in the
array to be named. For instance, perhaps we want to give short descriptions of each char-
acter so someone unfamiliar with the show is better able to recognize them. To distinguish
details by character, we will use their names in place of numbers. Our initial array from
before with names and descriptions could look as follows:
$theGriffins = array("Peter"=>"The fat guy", "Lois=>"The red
head", "Stewie"=>"The baby", "Chris"=>"The awkward boy",
"Brian"=>"The Dog");
Now that our array is associative, we pass the identifying piece of information we are
looking for. This is done as a key and value pair, where the key is the associative word you
can reference and the values is still what is stored. You will notice we used => in our declara-
tion this time, which identifies what comes before the => as the key, and what follows as the
value. So to find out what we know about Lois:
print $theGriffins['lois'];
gives us:

163
The Missing Link: An Introduction to Web Development and Programming Chapter 27

The red head


Note that we need to put the associative key in quotes (single or double) when using
print or echo.

Reading Get, Post


Earlier we discussed how to set a form to use Get or Post to transmit data to be pro-
cessed. To access these pieces of information, PHP has two built in arrays that store what
is transmitted under $_POST and $_GET. These are reserved variables that are always
available in your code whether or not any information was sent in that manner (in which
case, the variable will simply be an empty array). When we want to see the value of a form
element sent using Get with a field name of firstName, we would use:
print $_GET['firstName'];
If it was sent using post, all we would change is the variable name:
print $_POST['firstName'];
To save changes to the variable, we can place the results of the desired change to a
local variable we create, or assign them back to the array position in our GET or POST
array. The only way of keeping the changed material for use on another page, though, is to
resubmit the data to the page. I recommend using local variables so this is easier to keep
in mind.
Note that when you use GET or POST variables inside of a double quoted string, the
single quote characters are not needed in the array element request and will create an error.
For example:
print "My first name is $_POST[firstName]";
We can also easily see everything that was sent by using the print_r function or var_dump
like this:
print_r($_GET);
Now that we are interacting with data that is not under our control (given to us by the
user, or another outside source) we have to keep in mind that what they send us cannot
be trusted. If the user gave us a value we did not expect, or if someone is attempting to be
malicious, we would be interacting with data that could cause errors or introduce security
problems in our site. We address this through validation and sanitization (see Integration
Examples), which are techniques that help us address potential problems with data we did
not create.

Cookies and Sessions


Cookies and sessions are mechanisms we can use to store and use information from any
page on our site. These approaches allow us to do this without having to pass information
between pages using forms or special links as we have up to this point. Cookies achieve this
by storing very small files on the user’s computer. They are typically used to hold onto infor-
mation that identifies the user, whether or not they are logged in, or other information the
user needs to achieve their full experience with the site. Cookies can be set to expire after

164
The Missing Link: An Introduction to Web Development and Programming Chapter 27

a fixed amount of time, or “forever,” by setting an expiration date far after the computer or
user is likely to still be around.
Sessions allow the same storing of information, but achieve it by storing the informa-
tion on the server (instead of your computer) for a fixed amount of time (usually up to 15
minutes unless the user stays active). This means sessions will still work even when the
user’s security settings block cookies. The use of cookies can be disabled a number of ways
such as the use of security software, browser settings, and ad blockers. For this reason it can
be useful to use both in your site, allowing as much functional use as possible even when
cookies are denied, but still capitalizing on their longer persistence when they are available.
To create a cookie, we need to call the setcookie() function and pass it some variables.
At a minimum, we need to give our cookie a name and a value for it to store. The name is
how we will refer to it, and the value is what we want stored, just like any other variable
we would create. Additionally, we can provide setcookie() with an expiration time, a path,
a domain, and a secure flag.
The time, if passed, must be the number of seconds after creation that the cookie is con-
sidered valid for. We can achieve this by passing the time() function, which defaults to the
current time, and adding seconds to it. For example, passing time()+60 means the current
time plus 60 seconds. If we want to make it 15 minutes, we can pass the math along instead
of doing it ourselves by passing time()+60*15. 60 seconds, 15 times, is 15 minutes. One
whole day (60 seconds, 60 times = 1 hour. 24 hours in a day) would be time()+60*60*24.
By default, our cookie will be considered valid on all pages within the folder we are in
when we create it. We can specify another folder (and its subfolders) by placing it in the
path option. The same holds true for domain, where we can specify that a cookie is only
good in certain parts of our site like an admin subdomain.
Finally, we can pass a true or false (false is the default) for secure. When set to true, the
cookie can only be used on an https connection to our site.
We can pass the values we want in the following order:
setcookie(name, value, expire, path, domain, secure);
A simple example setting user=12345 for a day in our admin section of our site could
look like the following:
<?php setcookie("user","12345",time()+60*60*24,,admin.oursite.
com); ?>
From any page in the admin.oursite.com portion of our domain, we can now use $_
COOKIE[“user”] to get the value 12345. If we want to store other values, we can pass an
array to our cookie, or create other cookies for other values. To change a value in our cookie,
we simply use setcookie and give the same name with our new value:
<?php setcookie("user","23456"); ?>
Finally, if we want to get rid of our cookie early (i.e. our user logs out) then we simply
set the cookie to a time in the past, and the user’s computer will immediately get rid of it
as it is expired:
<?php setcookie("users","",time()-60*60); ?>
In this example we set our cookie to an hour ago.

165
The Missing Link: An Introduction to Web Development and Programming Chapter 27

A session works much the same way, and can be created by calling session_start(); at the
top of our page. We can then set, update, and delete variables from the session like any other
array by using the reserved array $_SESSION[]. To add our user again, we would type:
<?php session_start(); $_SESSION["user"]="12345"; ?> <html>
rest of page here...
It is important to remember that session_start() must be before the opening of any
content, thus above the <html> tag. Once on a different page, we would call session_start()
at the top again to declare that session values are allowed to be used on that page. Once we
have done that, we can continue to use $_SESSION[] values anywhere on that page. If the
user is inactive (does not leave the page or, click any links, or otherwise trigger an action to
the server) for 15 minutes (the default value) the session is automatically destroyed.
We can manually remove items from our session by calling unset(), for example:
<?php session_start(); unset($_SESSION['User']; ?>
Or we can jump right to ending the entire session by using the session_destroy function:
<?php session_destroy(); ?>
This will remove the entire $_SESSION[] array from memory. Create or modify an-
other PHP page in your collection (in the same folder and site as the current example).
In this second page, you will be able to call the same values out of your cookie or session
(as long as you include session_start() in this file as well) without passing any information
directly between the pages.

LEARN MORE
Keywords, search terms: Variables, strings, arrays, cookies, session, data persistence

Sorting Arrays: http://php.net/manual/en/array.sorting.php

All string functions: http://php.net/manual/en/ref.strings.php

PHP Sessions: http://www.sitepoint.com/php-sessions/

Evolving Toward a Persistence Layer: http://net.tutsplus.com/tutorials/php/​


evolving-toward-​a-persistence-layer/

166
Chapter 28

Data Manipulation

Comparison Operators
PHP supports many of the mathematical comparisons common to programming languages,
such as equivalence and relative value comparison. The symbols used however may be dif-
ferent than what you are used to. In the chart below we will look at how to represent each
comparison test, and under what condition we can expect the test to come back as true.
Table 11 Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.

$a === $b Identical TRUE if $a is equal to $b, and they are of the same
type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.

$a <> $b Not equal TRUE if $a is not equal to $b.

$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the
same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.

$a > $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal TRUE if $a is less than or equal to $b.


to
$a >= $b Greater than or TRUE if $a is greater than or equal to $b.
equal to
These tests will come in handy as we move into logic structures. The results of these
comparisons can help us determine a course of action like what is displayed to the user, how
we modify or create data, or respond to user input. Pay close attention to the difference be-
tween the equal (==) and identical (===) tests. Equal means the comparison of each side is
considered the same. For example, 1 and True are considered equal, because PHP will treat
a 1 as both an integer and a binary representation of true. If we want to ensure elements are

167
The Missing Link: An Introduction to Web Development and Programming Chapter 28

the same in both value and type, we would use strictly equal. This test returns a false in our
example, as 1 and true are not both integers of the value 1. Also, do not forget at least the
second =, as just one will be treated as assignment, not a logical test!

Order of Operations
PHP follows the traditional order of operations used in mathematics, as found below.
An associativity of “left” means the parser will read left to right across the equation. “Right”
means it will move right to left (i.e.: assign the equation to the element on the left of the
= sign). Precedence takes place from the top down, meaning the operators higher in this
list will be evaluated before those beneath them. Just as in mathematics, parenthesis will
interrupt this list by treating the contents of each set of parenthesis (from the inner most
out) as a statement by itself. The portion of the table in yellow highlights the operators most
used for development below application level.

ADDITIONAL NOTES

Take Note! While using the words “and” and “or” in your logic statements, PHP
will not give you an error, as they are in the order of precedence below. Take note
that they are below the = sign—this will affect your logic equations. The vast
majority of the time you will want to use “&&” and “||”, as they will be evaluated
before assignment.

Table 12 Operator Precedence


Associativity Operators
non-associative clone new
left [
non-associative ++ —
right ~—(int) (float) (string) (array) (object) (bool) @
non-associative instance of
right !
left */%
left +—.
left << >>
non-associative < <= > >= <>
non-associative == != === !==
left &
left ^
left |
left &&
left ||
left ?:

168
The Missing Link: An Introduction to Web Development and Programming Chapter 28

right = += -= *= /= .= %= &= |= ^= <<= >>= =>


left and
left xor
left or
left ,
Let us look at a few examples to demonstrate precedence in PHP:
echo 3 * 4 + 3 + 2; 17 Multiplication takes precedence and
all are evaluated left to right

echo 3 * (4 + 3 + 2);
27 Parenthesis take precedence so addi-
tion is evaluated before multiplication
Given: $this = true; $that=false
$result = $this && $that $result = false true and
false is false

$result = $this and $that


$result = true $this
(true) is assigned before
$this and $that is evaluated

Manipulating Data Streams


Data streams are long strings of characters specially formatted to convey information
between systems. They typically focus on the ability to quickly convey all the information
in as readable a format as possible, resulting in a compressed syntax to identify the informa-
tion and its meaning. Two of the most popular methods of streaming data today are JSON
and XML.
Data streams do not have to be raw, or complete, records of an entire system. They are
frequently used to transmit responses between the back-end system (server or database)
and the system that generates content the viewer sees (browser and/or scripting language).

JSON
An acronym for JavaScript Object Notation, JSON delimits objects with nested brackets
and quoted values, denoting key and value pairs with colons. This is a very short, concise
method of delivering data, but the recipient will need to get the meaning of the information
elsewhere like documentation, and the string is not easily human readable. It is useful when
the volume of data is high, and speed is important.
If we asked our system to give us the family members from Family Guy, we might get
the following:
{"Griffins":{"Peter":"Father", "Lois":"Mother", "Stewie":"Son",
"Chris":"Son", "Meg":"Daughter", "Brian":"Dog"} }
If we asked for the Griffins and Quagmire, we might get:

169
The Missing Link: An Introduction to Web Development and Programming Chapter 28

{"Griffins":
{"Peter":"Father", "Lois":"Mother", "Stewie":"Son",
"Chris":"Son", "Meg":"Daughter", "Brian":"Dog"},
{"Quagmire":"Neighbor"}
}

XML
An abbreviation of eXtensible Markup Language, XML wraps pieces of information in
tags, similar to HTML, but the names of the tags are user-defined. Grouping of informa-
tion is done by nesting the tags within each other. Using our Family Guy example above,
our XML response would be as follows:
<Response>
<Griffin>
<Peter >father</Peter>
<Lois>mother</Lois>
<Stewie>son</Stewie>
<Chris>son</Chris>
<Meg>daughter</Meg>
<Brian>dog</Brian>
</Griffin>
<Quagmire>
<Glen>neighbor</Glen >
</Quagmire>
</Response>

USEFUL FEATURE
You can test validate JSON and XML strings that you create or receive by copying
and pasting them into validation sites like jsonlint.com and xmlvalidation.com.
They can help you identify problem areas in your strings to make sure your data
is stored correctly.

Take note that I specify that this is how your code might look in these examples. The
actual output’s format would vary based on how the developers decides to create the re-
sponse string, and also based on any options available to the user as to how they want the
information organized. For example, we might want character ages instead of relationships
like father or daughter, or the developer might group the results by gender and put first and
last names as the value pairs.
It is important to note that when you actually interact with data streams they will not
look as they do above, but will be long strings without the spacing and line breaks, as this
reduces the size of the string. The formatting you see above is often referred to as the “pretty
print” format, which adds extra spacing and formatting to make it more human readable.
We can create both XML and JSON in PHP. You can do this by creating the exact string
necessary to format it, or we can use functions in PHP to help us along. The SimpleXML
package allows us to create, navigate, and edit XML content, while the json_encode and
json_decode functions allow us an easy means to convert JSON to and from arrays.

170
The Missing Link: An Introduction to Web Development and Programming Chapter 28

For brevity, we will consider examples of receiving data in these two formats. While con-
verting JSON into, an out of, arrays is easily done with json_encode() and json_decode(),
creating data by hand in these formats would necessitate a much deeper look at both XML
and JSON. Your journey there can begin with the Learn More section. I would recommend
you explore at least one format in depth, as you will come into contact with these formats
when you interact with APIs. Current trending has JSON getting more attention in new
development, but there are plenty of already built XML systems in place, and plenty more
that offer both.
An easy way to interact with XML or JSON data in PHP is to convert it into arrays
that we can more easily traverse. When we are working with XML we can use the
SimpleXML package integrated in PHP to read our string or file using $data = simplexml_
load_string($ourXML); or $data = simplexml_load_file(“ourXmlFile.xml”);. We can open
JSON files to string or receive them from another source, and decode them using $data =
json_decode($ourJson). Just like we did with arrays we created earlier, we can see our data
by using print_r($data);.
$ourJson =
'{"Griffins":{"Peter":"Father",
Array ( [Griffins] => Array (
"Lois":"Mother", "Stewie":"Son",
[Peter] => Father [Lois] =>
"Chris":"Son", "Meg":"Daughter",
Mother [Stewie] => Son [Chris]
"Brian":"Dog"}, }';
=> Son [Meg] => Daughter
$familyGuy =
[Brian] => Dog ) )
json_decode($ourJson,1);
print_r($familyGuy);
Be sure to place the 1 as our second option in our json_decode() call, as it instructs the
function to return the data as an array instead of objects. The same transfer to array for

171
The Missing Link: An Introduction to Web Development and Programming Chapter 28

XML becomes a little more complicated, as PHP does not natively support this type of
conversion, so we need to do more to get our full list displayed as arrays:
$ourXML= '<Response>
<Griffin>
<Peter >Father</Peter>
<Lois>Mother</Lois>
<Stewie>Son</Stewie>
<Chris>Son</Chris>
<Meg>Daughter</Meg>
<Brian>Dog</Brian> Array ( [Griffin] => Array ( [Peter]
</Griffin> => Father [Lois] => Mother [Stewie]
<Quagmire> => Son [Chris] => Son [Meg] =>
<Glen>Neighbor</Glen> Daughter [Brian] => Dog ) [Quag-
</Quagmire> mire] => Array ( [Glen] => Neighbor
</Response>'; ))
$familyGuy =
simplexml_load_string($ourXML);
$familyGuy = (array) $familyGuy;
foreach ($familyGuy as &$group)
{$group = (array) $group;}
print_r($familyGuy);

While we were able to make the outermost layer of the data an array just by re-declaring
its type, the type casting conversion in PHP is not recursive. However, simplexml_load_
string turns our XML into objects not arrays, so by looping through our array again and
recasting each element to an array, we can correct the data in the second layer. This process
would need to be repeated for each nested layer of data.

LEARN MORE
Keywords, search terms: json, xml, data formatting, data structures

Essential XML Quick Reference: http://bookos.org/book/491155/a86a21

Json.org: http://www.json.org/

Data Structures Succinctly (Pt 1): http://www.syncfusion.com/resources/techportal/ebooks/


datastructurespart1

172
Chapter 29

Email

Disclaimer: Unless you are working on a server that already has email capability, this chapter
may not work for you. WAMP 2.0 (or just Apache, MySQL, and PHP by themselves) do
not contain the ability to act as an email server in and of themselves. If you have an email
account that uses an exchange email server or another hosted solution, you can research
how to configure that account into your server to use your address to send email. Since this
process will differ depending on the service you use, comprehensive directions on how to
do so are not possible here.
In short, you will need account credentials such as a username and password, some
connection settings that can be found in your account settings that may be stored in your
email software, web settings, or phone settings, and you will need to edit your php.ini file’s
sendmail settings. Once you have made the necessary changes, do not forget to stop and
start your server for them to take effect.

Text-Based
Regardless of what service you use to facilitate sending email, you will always use the
same function in PHP to trigger it. The mail() function allows us to specify the “Who,
What, and Where” settings. Through this function we can support multimedia (HTML-
based) emails and attachments as well.
The minimum information necessary to send an email is the recipient and message,
assuming you have placed an email address in the “From” portion of the php.ini settings file:
mail("[email protected]", "That is a nice inbox you got
there!");
The full list of options at our disposal includes the following:
mail([to], [subject], [message], [headers]);
The headers section allows us to pass further information like a different “from” address
than our default, a reply email, CCs, BCCs, and information on other features like HTML
content or attachments. Since this last section and our actual message can be quite long, it
is helpful to declare all of these elements as variables first to keep our actual mail function
call readable:
$to = "[email protected]";
$subject= "You Win a million dollars!";
$message = "Not really. We just wanted you to read this.";
$headers .= 'From: Us <[email protected]>' . "\r\n";

173
The Missing Link: An Introduction to Web Development and Programming Chapter 29

$headers .= 'Cc: [email protected] . "\r\n";


$headers .= 'Bcc: [email protected]' . "\r\n";
mail($to, $subject, $message, $headers);
You will notice that our headers string actually contains the labels of the email, and that
line breaks are included at the end of each piece. This helps translate the string into separate
pieces of information when we submit the variable to the mail function in order to create
our actual email.

HTML
To make our messages look better and incorporate things like color and images, we can
add HTML to our message. We can do this by inserting two more lines to our header that
specify this:
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
Declaring our MIME Type version and content type of text/html allows us to include
HTML in our message. At this point, we can edit our message string to include HTML
tags. Since it is still a PHP string, we can include variables and concatenate results from
functions just as we can in other strings, allowing us to create messages that include content
specific to the user or recipient:
$message = "<table width=20%'><tr><td>First:</td><td>Jose</
td></tr>
<tr><td>Last:</td><td>Jalapeno</td></tr></table>";
Now we have sent our user some information formatted into a table. While we can
include a lot of HTML in a message, keep in mind your users will be viewing them on a
number of different devices and through different programs. The more complex the con-
tent, the more likely your user will not see it as you intend.
In fact, best practices for HTML email are to include the content formatted for email
clients that only support text, or as a fall back when something else goes awry. To do this,
we need to add a few more lines of code to specify which parts of our message belong to the
HTML version, and which parts belong to the text version. Part of this involves creating an
indicator that specifies where sections start and end. To do this, we need a unique string—
unique enough that it would never be an intended part of our message. An easy way to do
this is to use the md5 and time functions to generate our string. This does not mean we
have encrypted our email. The use of md5 simply helps us generate a long, random string:
$divider = md5((date('r', time()));
We also need to edit our header line to announce that our message is multipart and not
just HTML:
$headers .= "MIME-Version: 1.0\r\n";
$headers .= " Content-Type: multipart/alternative;
boundary=\"PHP-alt-".$random_hash; charset=ISO-8859-1\r\n";
Now we will add our $divider where our message starts, where we fall back from HTML
to text, and then at the end of our text section. Whenever we start a new section, we need
to specify which MIME format we are using. This allows us to mix and match multiple
things, even text, HTML, and attachments, all in one message. Since things are getting a
bit more complex, we will introduce a new concept, output buffering, to keep things cleaner.

174
The Missing Link: An Introduction to Web Development and Programming Chapter 29

Output buffering allows us to “stop” outputting anything to the screen or browser. By using
the buffer, we can create larger sections of text to use elsewhere. When we are done, we will
store the buffer contents into our message variable.
<?php ob_start(); ?>
—PHP-alt-<?php echo $divider; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<table width=20%'><tr><td>First:</td><td>Jose</td></tr>
<tr><td>Last:</td><td>Jalapeno</td></tr></table>

—PHP-alt-<?php echo $divider; ?>


Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

First: Jose
Last: Jalapeno

—PHP-alt-<?php echo $divider; —


$message = ob_get_clean(); ?>
You will note that we closed our PHP tags after starting our output buffer. This means
everything that follows would be treated as HTML to be rendered, so we still need to open
and close PHP tags when we want to insert dynamic content into our message. Once we
are done with our message(s), we use the ob_get_clean() function to dump the buffer’s
content into our message variable. This action also closes, or clears, the buffer we were using.
Now we have an email that supports an HTML and plain text version of our message. To
add an attachment, we would add one more MIME type section that names the file format
we want to attach, then include in our buffer content the file’s content. Since we cannot
drop the actual file into our code, we need to encode it. We can take care of all of this by
adding a couple extra lines at the start of our section for our attachment.
—PHP-mixed-<?php echo $division; ?>
Content-Type: application/zip; name="ourFile.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>


—PHP-mixed-<?php echo $division; ?>—
When you send attachments, you will want to keep in mind the size of the file(s) that
you are attaching. Just because your server is able to process and send the file does not
mean your recipient’s server will be able to accept it. Emails with attachments should be
accompanied by a body as well. If there is no text in the body of the email, the recipient’s
email client may elect to treat the attachment as the body of the message.

175
Chapter 30

File Interaction

We can use PHP to create and read files in a variety of formats, allowing us to create whole
new pages, store information in document form, copy files, and plenty more. The first step
in this process is creating a new file, or opening an existing file, that we want to work with.
To do this, we use the function fopen() to declare the file’s location and how we intend to
interact with its contents.

File Permissions
PHP follows the Unix/Linux approach to file permissions, which is more granular to
what Microsoft and Apple users are typically used to. In this approach, a particular file can
have different permission levels depending on if the person editing the file is the owner,
belongs to the same system group as the owner, or falls into the “anyone else” category.
Within these three categories we can also specify whether or not the person is allowed to
read, write, or execute the file, in any combination.
One of the methods used to depict permissions is with a string of letters and dashes,
using R, W, and X to represent read write and execute. In this approach, three groupings
of these letters are strung together in the order of owner, group, other, by read, write and
execute. A file that everyone has full permissions would be represented by rwxrwxrwx,
while a file where the owner can do anything, others in his group can read and execute, and
anyone else can execute would be shown as rwxr-xr—. The dashes here indicate that the
permission is lacking. Group membership refers to the group your account is associated
with on the server, which can be anything the server is told to recognize like administrators,
users, guests, professor, student, and so on. If the owner of our imaginary file was in the
administrator group, other administrators could read and execute the file, where anyone in
any other group would only be able to execute it without seeing its contents.
Understanding this structure is important to understanding why file open methods are
necessary, and can also help us understand problems opening files when appropriate per-
missions are not used. Any time we open a file in PHP we need to use one of the following
methods, which will determine what PHP lets us do with the file.

176

You might also like