Skip to main content
Engineering LibreTexts

3: Scripting Languages

  • Page ID
    45735
  • Section 3:

    Scripting Languages

    Learning Objectives:

    By the end of this section, you should be able to demonstrate:

    • An ability to create PHP scripts
    • An ability to receive, store, and manipulate user data
    • An ability to interact with files
    • The ability to create and send basic email
    • The ability to use logic and control structures in scripts
    • The ability to create functions and simple classes
    • Altering a page using JavaScript and jQuery

    Chapter 23

    Server-Side and Client-Side Scripting

    19144.pngPHP

    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 developers 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 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 appearance, 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 loosely, 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 of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.

    Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.

    Variable data types are not declared (dynamic typing).

    Variable data types must be declared (static typing).

    Cannot automatically write to hard disk.

    Cannot automatically write to hard disk.

    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.

    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.

    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

    1. 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 intended 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

    1. 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

    1. PHP Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in database.inc on line 43

    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 exception 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:

    1. <?php
    2. error_reporting(E_WARNING | E_ERROR);
    3. //This next line will trigger a notice that the variable does not exist, but we will not see it
    4. echo $test;
    5. ?>
    6. <?php
    7. error_reporting(E_ALL);
    8. //This time we will see the notice
    9. echo $test;
    10. ?>
    11. 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 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 allocation 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_WARNING

    Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by 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_ERROR

    Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the 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().

    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 important 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!

    1. <?php echo "Hello, World!"; ?>

    We can also wrap the string in parenthesis as we discussed above if you feel it makes things more clear:

    1. <?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 functions 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:

    1. <?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.

    chap26_echo.png

    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/

    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

    • 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 development, 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:

    1. $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 underscores 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 information 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:

    1. $counter = $counter + 1;

    But we can shorten that by using the “plus equal”:

    1. $counter +=1;

    Or if we only need to add 1, the “plus plus”:

    1. $counter++;

    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 languages 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:

    1. $string = "Hello"; // The quotes we use here do not matter for this example
    2. echo "$string there";
    3. echo '$string there';
    4. Hello there
    5. $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 commonly 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 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

    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 $address = ‘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:

    1. 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:

    1. 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:

    1. 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:

    1. echo "This server runs on ". PHP_OS . " and use PHP version ". PHP_VERSION;

    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:

    1. $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:

    1. 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.

    1. $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:

    1. echo $theGriffins[0];

    which would give us:

    1. 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:

    1. print_r($theGriffins);
    2. Array(
    3. 0: Peter
    4. 1: Lois
    5. 2: Stewie
    6. 3: Chris
    7. 4: Brian
    8. )

    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:

    1. $theGriffins[]='Meg';

    Now if we run print_r, we would see:

    1. Array(
    2. 0: Peter
    3. 1: Lois
    4. 2: Stewie
    5. 3: Chris
    6. 4: Brian
    7. 5: Meg
    8. )

    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:

    1. $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:

    1. echo array_search("Meg", $theGriffins);

    will give us:

    1. 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:

    1. $location = array_search("Meg", $theGriffins);
    2. $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:

    1. $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 character 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:

    1. $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 declaration 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:

    1. print $theGriffins['lois'];

    gives us:

    1. 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 processed. 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:

    1. print $_GET['firstName'];

    If it was sent using post, all we would change is the variable name:

    1. 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:

    1. 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:

    1. 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 information 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 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 information 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 considered 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:

    1. 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:

    1. <?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:

    1. <?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:

    1. <?php setcookie("users","",time()-60*60); ?>

    In this example we set our cookie to an hour ago.

    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:

    1. <?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:

    1. <?php session_start(); unset($_SESSION['User']; ?>

    Or we can jump right to ending the entire session by using the session_destroy function:

    1. <?php session_destroy(); ?>

    This will remove the entire $_SESSION[] array from memory. Create or modify another 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/

    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 different 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 to

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

    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 between 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 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!

    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.

    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.

    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

    ? :

    right

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

    left

    and

    left

    xor

    left

    or

    Let us look at a few examples to demonstrate precedence in PHP:

    1. echo 3 * 4 + 3 + 2;

    17 Multiplication takes precedence and all are evaluated left to right

    1. echo 3 * (4 + 3 + 2);

    27 Parenthesis take precedence so addition is evaluated before multiplication

    Given: $this = true; $that=false

    1. $result = $this && $that
    • $result = false true and false is false
    1. $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 information 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:

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

    If we asked for the Griffins and Quagmire, we might get:

    1. {"Griffins":
    2. {"Peter":"Father", "Lois":"Mother", "Stewie":"Son", "Chris":"Son", "Meg":"Daughter", "Brian":"Dog"},
    3. {"Quagmire":"Neighbor"}
    4. }

    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 information is done by nesting the tags within each other. Using our Family Guy example above, our XML response would be as follows:

    1. <Response>
    2. <Griffin>
    3. <Peter >father</Peter>
    4. <Lois>mother</Lois>
    5. <Stewie>son</Stewie>
    6. <Chris>son</Chris>
    7. <Meg>daughter</Meg>
    8. <Brian>dog</Brian>
    9. </Griffin>
    10. <Quagmire>
    11. <Glen>neighbor</Glen >
    12. </Quagmire>
    13. </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 response 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.

    For brevity, we will consider examples of receiving data in these two formats. While converting 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", "Lois":"Mother", "Stewie":"Son", "Chris":"Son", "Meg":"Daughter", "Brian":"Dog"}, }';
    • $familyGuy = json_decode($ourJson,1);
    • print_r($familyGuy);

    Array ( [Griffins] => Array ( [Peter] => Father [Lois] => Mother [Stewie] => Son [Chris] => Son [Meg] => Daughter [Brian] => Dog ) )

    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 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:

    1. $ourXML= '<Response>
    2. <Griffin>
    3. <Peter >Father</Peter>
    4. <Lois>Mother</Lois>
    5. <Stewie>Son</Stewie>
    6. <Chris>Son</Chris>
    7. <Meg>Daughter</Meg>
    8. <Brian>Dog</Brian>
    9. </Griffin>
    10. <Quagmire>
    11. <Glen>Neighbor</Glen>
    12. </Quagmire>
    13. </Response>';
    14. $familyGuy = simplexml_load_string($ourXML);
    15. $familyGuy = (array) $familyGuy;
    16. foreach ($familyGuy as &$group){$group = (array) $group;}
    17. print_r($familyGuy);

    Array ( [Griffin] => Array ( [Peter] => Father [Lois] => Mother [Stewie] => Son [Chris] => Son [Meg] => Daughter [Brian] => Dog ) [Quagmire] => Array ( [Glen] => Neighbor ) )

    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

    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:

    1. mail("ourRecipient@nowhere.com", "That is a nice inbox you got there!");

    The full list of options at our disposal includes the following:

    1. 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:

    1. $to = "ourRecipient@nowhere.com";
    2. $subject= "You Win a million dollars!";
    3. $message = "Not really. We just wanted you to read this.";
    4. $headers .= 'From: Us <us@somewhereOutThere.com>' . "\r\n";
    5. $headers .= 'Cc: someoneelse@nowhere.com . "\r\n";
    6. $headers .= 'Bcc: hiddenPerson@definatelyNotHere.com' . "\r\n";
    7. 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:

    1. $headers .= "MIME-Version: 1.0\r\n";
    2. $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:

    1. $message = "<table width='20%'><tr><td>First:</td><td>Jose</td></tr>
    2. <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 content, 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:

    1. $divider = md5((date('r', time()));

    We also need to edit our header line to announce that our message is multipart and not just HTML:

    1. $headers .= "MIME-Version: 1.0\r\n";
    2. $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. 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.

    1. <?php ob_start(); ?>
    2. —PHP-alt-<?php echo $divider; ?>
    3. Content-Type: text/html; charset="iso-8859-1"
    4. Content-Transfer-Encoding: 7bit
    5. <table width='20%'><tr><td>First:</td><td>Jose</td></tr>
    6. <tr><td>Last:</td><td>Jalapeno</td></tr></table>
    7. —PHP-alt-<?php echo $divider; ?>
    8. Content-Type: text/plain; charset="iso-8859-1"
    9. Content-Transfer-Encoding: 7bit
    10. First: Jose
    11. Last: Jalapeno
    12. —PHP-alt-<?php echo $divider; —
    13. $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.

    1. —PHP-mixed-<?php echo $division; ?>
    2. Content-Type: application/zip; name="ourFile.pdf"
    3. Content-Transfer-Encoding: base64
    4. Content-Disposition: attachment
    5. <?php echo $attachment; ?>
    6. —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.

    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 permissions 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.

    Table 13 PHP File Methods

    mode

    Description

    ‘r’

    Open for reading only; place the file pointer at the beginning of the file.

    ‘r+’

    Open for reading and writing; place the file pointer at the beginning of the file.

    ‘w’

    Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

    ‘w+’

    Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

    ‘a’

    Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

    ‘a+’

    Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

    ‘x’

    Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlyingopen(2) system call.

    ‘x+’

    Create and open for reading and writing; otherwise it has the same behavior as ‘x’.

    ‘c’

    Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file. This may be useful if it is desired to get an advisory lock (see flock()) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

    PHP.net [CC-A 3.0]

    File Actions

    Assuming we want our file in the same folder as our page and that the web server has permission to create files in that location, we can start a new file with the following:

    1. $handler = fopen("ourFile.txt", 'x+');

    If all was successful in creating our new file, the $handler variable would now represent the system’s position in our open file as a reference. If the file already existed, we would have received an error (this keeps us from accidently overwriting a file we wanted). If no permissions errors cropped up, you can now add content to your file. If you do have permission errors, you will need to change folders to one your web server can write to, or give your server permissions on that folder. Since this is an operating system task, you will need to find instructions on how to achieve this based on your OS type, version, and web server settings.

    We can now add whatever we want to our file, so long as it results in valid content for the file type we are creating. For example, any HTML placed in a text file will appear as plain text, not a web page. We would need to create our file as ourFIle.html for that type of content to render correctly. If we had a large block of text already stored in a variable called content, we can add it to our file by using fwrite(). Each time we call fwrite, the variable passed to it will be appended to what we have already sent. If we had opened an existing file, the content might be appended (‘a’) or overwrite what exists (‘w+’) depending on how we opened it. When we are done, we need to close the file, which actually writes the content using the $handler variable and saves it in our folder:

    1. fwrite($content);
    2. fwrite($moreContent);
    3. fclose($handler);

    If we browse to our file from our operating system, you should be able to open it in a text editor and see the text you stored in your $content variable.

    Uploading Files

    In order to allow users to upload files to our server, we have to create a folder that allows the web server to write to it, and make the following changes in our php.ini file:

    1. File_uploads = on
    2. Upload_tmp_dir = [location of our upload folder]
    3. Upload_max_filesize = [size in megs, i.e. 5M = 5 megs]

    After making these changes and restarting our web server, our users will be able to use upload form elements, which we create using an input with a type attribute of file:

    1. <input type="file" name="userUpload" id="userUpload">

    On the page that processes our form we can access the file (and information describing it) by using the reserved PHP array $_FILES:

    1. echo "File name:" . $_FILES["userUpload"]["name"] . "<br>";
    2. echo "Type:" . $_FILES["userUpload"]["type"] . "<br>";
    3. echo "Size:" . ($_FILES["userUpload"]["size"] / 1024) . "kB<br>";
    4. echo "Stored in:" . $_FILES["userUpload"]["tmp_name"];

    Chapter 31

    Structures

    Referred to as selection, control, or loop structures, this set of elements dictate conditions under which certain sections code are executed. They allow our program to be flexible, instead of restricting it to the same actions every iteration. Here, we will consider all of them together, as structures in general.

    If

    “If” is perhaps the simplest test we can apply in logic. In programming, the “then” side is implied in the code contained in the definition of our statement—If [some condition] is true, then do something. We can use this to put exceptions into our code, or to redirect to a different action. Within the If statement we can perform simple comparisons or have the interpreter perform calculations and get returns from functions as part of its comparison task.

    To run some examples, we will check if a variable called coffee is equal to hot. If it is, we want to run the drink function.

    1. if("hot" == $coffee){
    2. drink($coffee);
    3. }

    Additional notes

    Remember that = is an assignment operation! == or === must be used when testing if both sides of the operand are equivalent.

    Else

    Next we will assume our drink() function tells us if we want more or feel full, prompting us to take new actions, like cleaning up after ourselves. This means we need to take one of two actions, which can do by extending our If/Then by adding Else:

    1. if(drink($coffee)=='full'){
    2. cleanUp();
    3. }
    4. else{ //We want more!
    5. drink($coffee);
    6. }

    elseIf

    We can use elseIf when we want to follow up a failed If statement with another check. While the same affect can be created by placing an If inside of our Else, we can eliminate a layer of nesting. We can still follow up an elseIf with its own Else as well:

    1. if ($a > $b) {
    2. echo "a is bigger than b";
    3. } elseif ($a == $b) {
    4. echo "a is equal to b";
    5. } else {
    6. echo "a is smaller than b";
    7. }

    While

    While statements will repeatedly execute until the condition we provide is no longer true. The code will start over, in a loop, as long as the requirement is met.

    Be careful with While statements! You can easily create infinite loops using While, in which your code will continue to run until forced to stop by closing the page or resetting your web service. The first method of prevention is to ensure that you have at least one place in your While loop that can affect the value (or values) in your while condition. The second method of prevention is to make sure that at least one result of those changes satisfies your While condition.

    While loops are very similar to If in terms of structure. Here we will pretend $ourValue is a 4:

    1. $ourValue=4;
    2. while($ourValue!=6){
    3. echo "Wait for it...<br/>";
    4. $ourValue++;
    5. }
    6. echo "6!";
    1. Wait for it...
    2. Wait for it...
    3. 6!

    Let us try one that counts for us:

    1. $ourValue=4;
    2. while($ourValue!=10){
    3. echo "$ourValue," ;
    4. $ourValue++;
    5. }
    • 4, 5, 6, 7, 8, 9,

    To see a broken While statement in action, change $ourValue to 11 and refresh your page!

    Do While

    Do While loops are very similar to While loops with the difference that every Do While loop will run at least one time. This is because a Do While loop evaluates the equation after each loop, not before. Since it does not check if conditions are met until the end, the first loop will never be checked. For example, compare the following loops and their output:

    1. do {
    2. echo $i;
    3. } while ($i > 0);
    4. echo “<br/> done”;
    • 0
    • done
    1. while ($i>0){
    2. echo $i;
    3. }
    4. echo “<br/> done”;
    • done

    For

    For loops are very similar to While loops, but they execute code only while the condition is within the given range. When using a For loop, we need to provide it with the value we want to monitor, the condition we want to stop on, and how we want to change it, right in the declaration. As a result, the body of the loop is strictly what we want to happen while the For’s conditions are true. Let us say we want to watch $x (we will pretend it is 5 right now). We want to keep running until it is greater than 10, and we want to add 2 each time we finish the loop:

    1. $x=5;
    2. for($x;$x<10;$x+=2){
    3. echo "$x is less than 10 <br/>";
    4. }
    5. echo "$x is greater than 10!";
    1. 5 is less than 10
    2. 7 is less than 10
    3. 9 is less than 10
    4. 11 is greater than 10!

    Unlike the While loop, you will notice we did not have to change the value of $x inside our loop, it was done automatically each time the end of the loop was reached. If the termination condition (in our example x would be greater or equal to 10) is not met, the loop starts again. Let us look at another example. This time, if a secondary condition that we test for occurs, we will force the For to stop by changing $x ourselves to something that satisfies the termination condition:

    1. $x=5;
    2. for($x;$x<10;$x+=2){
    3. echo "$x is less than 10 <br/>";
    4. if($x==7)$x=11;
    5. }
    6. echo "$x is greater than 10!";
    1. 5 is less than 10
    2. 7 is less than 10
    3. 11 is greater than 10!

    Foreach

    Although we took a brief look at Foreach when we reviewed pseudo-code, we will take a look at an actual implementation now. This loop format is used to iterate over arrays, allowing us an opportunity to manipulate each element inside. Since it is designed specifically for interacting with arrays, these are the only objects you can pass to it. The function takes the array we want to look at as well as what we want to call each element as we look at it. Alternatively, we can ask that the function take each element as a key and value pair, which can be very useful when position value is needed or associative arrays are in play.

    When we use a Foreach, the engine makes a copy of the array, leaving the original intact, eliminating the need to track and reset the original array’s pointer or reset the array when we are done. This also means that while we are interacting with the elements inside our array, we need to keep in mind that we are dealing with a copy. No changes that are applied to our copy will persist unless we call the function while applying an ampersand (&) before the variable name, which instructs the function to apply changes directly to our original array.

    In order to apply changes to our array, the original that is passed must be a variable already stored in memory, and not an array declared in the function call. Let us look at some examples to clear some of this up by mimicking print_r().

    1. $array = array(1, 2, 3, 4, 5);
    2. foreach($array as $number){
    3. echo "Our value is $number <br />";
    4. }
    1. Our value is 1
    2. Our value is 2
    3. Our value is 3
    4. Our value is 4
    5. Our value is 5

    To play with an associative array and see the key and the value, we will adjust both our starting array and what we pass in the function call:

    1. $array = array("Mike"=>42, "Frank"=>38, "Anne"=>28);
    2. foreach($array as $key=>$value){
    3. echo "$key is $value years old.<br />";
    4. }
    1. Mike is 42 years old.
    2. Frank is 38 years old.
    3. Anne is 28 years old.

    Finally, we will take a look at applying our changes back to the array, multiplying our original array’s values by 2:

    1. $array = array(1, 2, 3, 4, 5);
    2. foreach($array as &$number){
    3. $number = $number * 2;
    4. }
    5. print_r($array);
    1. Array(
    2. 0 => 2
    3. 1 => 4
    4. 2 => 6
    5. 3 => 8
    6. 4 => 10
    7. )

    Switch

    A switch statement lets us run several tests to determine the proper course of action, or to apply one or more changes to our variable or elsewhere in our code, when the condition of our case is met. Some indicators that a switch is appropriate are when you find yourself running several If Then statements on the same variable, or have nested multiple logic statements attempting to control the action of your script.

    To create an example, let us write a switch that gives information about a number passed to it. First, we will design it to determine the smallest positive value of 2 through 9 that $value is a multiple of, and then we will tweak it a bit so it can tell us all the values of 2 through 9 $value is a multiple of. If we just want the smallest value, we only need to test 2, 3, 5, and 7 since 4, 6, 8 and 9 are multiples of these numbers anyway, so they could not be the smallest. Now, if the number we check is divisible by one of these numbers, it would not have a remainder. To check specifically for a remainder, we can use modular division, which in PHP is represented by a %, and returns a 0 or 1. If we get a zero, there is no remainder. So let us create a switch with empty test cases for 2, 3, 5 and 7:

    1. switch($value){
    2. case ($value % 2 == 0 ):
    3. case ($value % 3 == 0 ):
    4. case ($value % 5 == 0 ):
    5. case ($value % 7 == 0 ):
    6. default:
    7. }

    Each case can be followed by a set of parenthesis denoting our logical test or a value, which is followed by a colon that denotes the start of what we want to happen when the case is true. If we wanted a case where the value IS 2, we would use:

    1. Case 2:

    Or, if we wanted to test if the value is the WORD two, we would use:

    1. Case "two":

    By default, each case will be tested until the switch is complete, or we tell it we want it to stop. This ability will be useful in a moment, but for now, we want the switch to stop as soon as we find a value, since we are testing in smallest to largest order, and only need one test to be true. To do this, we put a “break;“ wherever we want the execution of our switch to stop. Typically this is the last line before the following case, but if the case we are in has additional logic tests we might have more than one “break;” depending on the extra conditions we are testing.

    You will also notice the “default:” that snuck in at the bottom. The default case must be last, but is optional, and gives us a “catch all” action in the event that none of our cases were met. We do not need a “break;” after our default, since it will always be the last case in our switch.

    To complete our example, we will want to let the user know what the smallest value we found was, so we need to fill out our code:

    1. switch($value){
    2. case ($value % 2 == 0 ):
    3. echo "$value is divisible by 2 <br/>";
    4. break;
    5. case ($value % 3 == 0 ):
    6. echo "$value is divisible by 3 <br/>";
    7. break;
    8. case ($value % 5 == 0 ):
    9. echo "$value is divisible by 5 <br/>";
    10. break;
    11. case ($value % 7 == 0 ):
    12. echo "$value is divisible by 7 <br/>";
    13. break;
    14. default:
    15. echo "$value is not divisible by 2 through 9.";
    16. }

    Additional notes

    This does not mean our switch will find all prime numbers! Prime numbers have to be tested against the range 2 to n1/2 to ensure there are no dividends.

    With this example, if $value was 4, we would get “4 is divisible by 2.” If $value was 12, we would get “12 is divisible by 2” but would not get a response for 3, 4, or 6 since we included breaks after each test, and it stopped after 2. If $value was 11, we would get all the way to “11 is not divisible by 2 through 9.” In this scenario, it is because 11 is a prime number, which by definition is only divisible by itself and 1.

    Now let us tweak our switch statement so it tells us all of the values between 2 and 9 that can divide our number without a remainder. First, we will have to start testing the values we could skip earlier. For example, 8 is not divisible by 6 even though both are divisible by 2. Second, we no longer want to stop after one expression is true. To do this, we will get rid of all of our breaks except for the one in the case preceding the default, ensuring that if any of the cases were true, we will not still see our default statement. That gives us:

    1. switch($value){
    2. case ($value % 2 == 0 ):
    3. echo "$value is divisible by 2 <br/>";
    4. case ($value % 3 == 0 ):
    5. echo "$value is divisible by 3 <br/>";
    6. case ($value % 4 == 0 ):
    7. echo "$value is divisible by 4 <br/>";
    8. case ($value % 5 == 0 ):
    9. echo "$value is divisible by 5 <br/>";
    10. case ($value % 6 == 0 ):
    11. echo "$value is divisible by 6 <br/>";
    12. case ($value % 7 == 0 ):
    13. echo "$value is divisible by 7 <br/>";
    14. case ($value % 8 == 0 ):
    15. echo "$value is divisible by 8 <br/>";
    16. case ($value % 9 == 0 ):
    17. echo "$value is divisible by 9 <br/>";
    18. break;
    19. default:
    20. echo "$value is not divisible by 2 through 9.";
    21. }

    To repeat our examples using 4, 12, and 11, respectfully we would see the following responses:

    1. 4 is divisible by 2
    2. 4 is divisible by 4
    3. 12 is divisible by 2
    4. 12 is divisible by 3
    5. 12 is divisible by 4
    6. 12 is divisible by 6
    7. 11 is not divisible by 2 through 9

    Chapter 32

    Functions

    Now that we are comfortable creating some code, let us take a look at how to do more with what we have. In any language we use, there are concepts that are not always translatable from one to the next, if the concept is even present in both. In spoken languages, words for a particular concept also may have no direct translation to another language. For example, the German word Kummerspeck is a single word to convey the concept of excess weight gained by emotion-related overeating. Not only does the English language lack a word defining this concept, its closest literal translation in English would be “grief bacon.” Similarly, in Wagiman (Australia) there is an infinitive murr-ma, which means “to walk along in the water searching for something with your feet,”1 which is both much more specific and requires a significantly longer English sentence to convey.

    The development of words that specify such lengthy or concise ideas arise out of the popularity of, or need to convey that concept often in a society. It is far easier to say “I am going to the gym to get rid of this Kummerspeck” than “I am going to the gym to get rid of the weight I gained from overeating due to my emotions,” which allows for the concept to be used more often.

    In programming languages, we can find a parallel to this when functions or abilities in one language are not available in another, or require additional code to achieve. For example, in PHP you can retrieve items available to the page using the GET method by referencing the built-in $_GET array:

    1. <?php echo $_GET['variable name']; ?>

    Attempting to implement the same functionality in JavaScript requires much more effort, even with the assistance of its built-in location.search function:

    1. var $_GET = {},
    2. variablesList = location.search.substr(1).split(/&/);
    3. for (var x=0; i<variablesList.length; ++i) {
    4. var tmp = variablesList[x].split(/=/);
    5. if (tmp[0] != "") {
    6. $_GET[decodeURIComponent(tmp[0])] =decodeURIComponent(tmp.slice(1).join("").replace("+", " "));}}

    The programming equivalent of creating a word to describe a concept is the ability to create our own algorithms and functions, to describe new actions. In the example above, we could take our JavaScript code and wrap it in a function definition, and add a return call to send the results back to where you called the function, like this:

    1. function findValues(){
    2. var $_GET = {},
    3. variablesList = location.search.substr(1).split(/&/);
    4. for (var x=0; i<variablesList.length; ++i) {
    5. var tmp = variablesList[x].split(/=/);
    6. if (tmp[0] != "") {
    7. $_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
    8. }
    9. }
    10. return $_GET;
    11. }

    Now, anytime you wanted to find your values using JavaScript, you could include this function and simply type:

    1. var $_GET = findValues(); document.write($_GET['variable name'];

    Creating a function also allows us to reference it in more than one place, without having to retype or copy and paste those lines into every place we want to use them. This also means that debugging only requires fixing the original block of code in your function, as it is the only place the line exists, since each function call is a reference to this single definition.

    Creating a function in PHP is much like the example we looked at for JavaScript above. To create a function, we use the word function (denoting that we are creating one, not calling one to use it) followed by the name we want to give it and any variables we would like it to use in parenthesis. A set of braces are used to identify the code that belongs to the definition. An empty function called Add that does not accept any variables would look like this:

    1. function Add(){ }

    Note that a terminating semi-colon is not needed after the closing brace. The brace tells PHP that the statement is complete, just as it does when using a logic or control statement. To pass variables into our Add function, the function will need to know what to expect to receive. We do this by adding parameters (names we give to the variables passed to the function) to the definition. Here we will add two parameters:

    1. function Add($num1, $num2){ }

    Now, we will tell the function to add these numbers and give us the result:

    1. $var1 = 4; $var2= 5;
    2. function Add($num1, $num2){
    3. $temp = $num1 + $num2;
    4. return $temp;
    5. }
    6. $value = Add($var1, $var2);

    When we use the function and pass it actual values (in this example, $var1 and $var2) those variables are called arguments; they contain the data we actually want to use. Another example of function output you may see are ones that send output right to the screen, like this:

    1. $var1=4; $var2=5;
    2. function Add($num1, $num2){
    3. $temp = $num1 + $num2;
    4. print $temp;
    5. }
    6. Add($var1, $var2);

    They might also output more than we expect, not just the result of the equation:

    1. function Add($num1, $num2){
    2. $temp = $num1 + $num2;
    3. print "$num1 + $num2 = $temp";
    4. $oddEven = $temp % 2;
    5. if ($oddEven == 0){ print "<br/>$temp is even"; }
    6. else{ print "<br/>$temp is odd"; }
    7. }
    8. Add(7,9);

    While all of these example are effective, the second two examples actually limit our ability to use them again, namely by performing multiple actions, and by mixing action and output. Since the power of a function lies largely in our ability to reuse it, these are attributes we will want to eliminate. To make functions as useful as possible, they should do one thing, and do it well.

    In this example the intent of our function is to add numbers. Our expectation is that we will provide it numbers, and it will provide the sum. Any other actions or steps needed to solve a larger problem should reside elsewhere in your code, or in another function. By doing this, we know that when we use add() all it will do is give us a number. If the function shows our output instead of returning it, we would not be able to use if it we did not want it to show on the screen. By returning it and storing it, we can choose where and when it is displayed, or use it somewhere else.

    To simplify our function and follow these practices, let us refine it to the following:

    1. function Add($num1, $num2){ return $num1 + $num2; }

    Now we can call the function and store it to a variable:

    1. $sum = Add(3,5);

    Or we would chose to display it on the screen:

    1. echo Add(3,5);

    Useful Feature

    Wait! Where did the $temp variable go?! By skipping the use of declaring $temp to hold our sum, we have eliminated one reserved memory space while the function is running. In terms of the size of this function, the number of variables we needed, and the time for it to execute, we would never know the difference. However, in much larger programs, especially when memory is limited, these steps can improve performance.

    Let us take a look at how we can put all of this together:

    1. <?php
    2. function Add($num1, $num2){
    3. return $num1 + $num2;
    4. }
    5. echo "Welcome to the number adding page! <br/>";
    6. echo "The sum of 3 and 5 is " . Add(3,5);echo "<br/>The sum of 9 and 12 is " . Add(9, 12);
    7. ?>

    Seeing as the ability to add numbers is already built into PHP, let us look at a more advanced example. We will design a function that tells us how much to add to a bill for a tip. To do this, we will need to create a function that takes in the total of our bill, calculates the tip amount, and tells us how much the tip would be.

    Remember, a function should do one thing only, so before we worry about final totals or any other issues, let us at least get that far:

    1. function tip($billTotal){
    2. $tip = $billTotal * .15;
    3. return $tip;
    4. }

    In the above example, we assumed a 15% tip. What if that is not the standard where you are? Or maybe the service was better or worse than you expected. This is an additional use case we need to consider. To do this, we will allow the user to tell us the percentage they want, and assume that if they do not tell us, it is still 15%:

    Additional notes

    Do not forget your SCOPE! Functions cannot see anything outside of their braces that are not given to them when they are called. Once you leave your function, any local variables created in it that were not returned are gone!

    1. function tip($billTotal, $percent=.15){
    2. $tip = $billTotal * $percent;
    3. return $tip;
    4. }

    Setting $percent equal to a value in the function definition tells the function that if a second value is not passed, assume it to be .15. This allows that variable to be optional, so we can call this function as tip(45.99,.20) or just tip(45.99). We are still only doing one thing, but now we have some flexibility. What about other use cases, like splitting the bill? While we could tell the function how many people to divide the total by, that would violate our “one thing” rule. Instead, we can divide the total outside of the function, and give tip() the result to figure out how much each person’s contribution to the tip would be.

    If you have been testing out our function as we have progressed, you have probably had some tip values that resulted in half pennies and even smaller fractions of currency to fulfill. This is because our function does not know we are dealing with money—it is just doing the math. Since we only need to calculate to the second decimal point for this type of problem, we can round out our answer to match. PHP already provides us with a rounding function called round, so we will use that to refine our response:

    1. function tip($billTotal, $percent=.15){
    2. $tip = $billTotal * $percent;
    3. $roundedTip = round($tip, 2);
    4. return $roundedTip;
    5. }

    Lastly we will combine our statements, as we did before, to eliminate extra variables and shorten our code:

    1. function tip($billTotal, $percent=.15){ return round(($billTotal * $percent),2) }

    Now we have a concise function that can perform a single task and perform it well. We can refer to it anywhere in our page as often as we need to without having to copy and paste the code. In fact, this is the perfect time to introduce a set of functions that allow us to import other files into our page.

    Additional notes

    Order helps! If all of your optional variables are at the end (right hand side) of the definition, you will not have to pass empty quotes as place holders if you only want to send the required variables.

    The functions include(), require(), and require_once() all allow us to pass a file location on our server that we want to use as part of our code. By importing these outside files, we can create libraries of functions or class files and insert them into any page we want to use them on. Each of these functions runs the same way, by passing a file location. If the contents of the file are not critical to your page, you may want to just use include, as it will not generate an error if the file is missing. Errors will be thrown by using require() or require_once(). The former will always insert the contents of the file, while the latter will only load the file if its contents are not already available. Using required_once() will save us from redefinition errors caused by redefining functions or classes we already have. If the contents of the file tip.php was our function, we could reference it in any page like this:

    1. <?php
    2. require_once("tip.php");
    3. echo tip(49.99);
    4. ?>

    Learn more

    Keywords, search terms: Functions, function scope

    Tizag’s function review: http://www.tizag.com/phpT/phpfunctions.php

    Helper Functions : http://net.tutsplus.com/tutorials/php/increase-productivity-by-creating-

    php-helper-functions/

    Chapter 33

    Objects and Classes

    We can group related functions together into an item called a class. Classes are collections of functions (when they are in classes, they are called methods) and variables that are related or collectively represent our knowledge or actions that can be performed on a concept. We can create a class by writing:

    1. class math{
    2. }

    This gives us an empty class called Math. Let us include our adding function:

    1. class math{
    2. function add($num1, $num2){
    3. return ($num1 + $num2);
    4. }
    5. }

    and add a couple more functions:

    1. class math{
    2. function add($num1, $num2){
    3. return ($num1 + $num2);
    4. }
    5. function subtract($num1, $num2){
    6. return ($num1—$num2);
    7. }
    8. function divide($num1, $num2){
    9. if($num2!=0){return ($num1 / $num2);}
    10. else return "error";
    11. }
    12. }

    By creating the class, we have declared that add, subtract, and divide all belong to Math. To use our new class, we create a copy of it, called an instance, in our script. In the divide function you can see we check to make sure we will not divide by zero, which would cause an error. This is an example of how we can use classes and functions to expand functionality and protect our program. We can reference the variable that is our object to use the functions and data members (variables that are inside a class) inside it:

    1. $ourMath = new math();
    2. echo $ourMath->add(5,9);

    The arrow tells us to use something inside our class, in this case the add method. We can use these methods over several lines:

    1. $temp = $ourMath->add(5,9);
    2. $temp = $ourMath->divide($temp/2);

    or nest them:

    1. $temp = $ourMath->divide($ourMath->add(5,9),2);

    Classes are commonly used to create libraries of related actions, like the Math example we made, or to create collections of methods and data members that pertain to a concept in our system. For example, if this was an online course system we might have objects to represent concepts like students and courses.

    Methods in the student class would revolve around the student, like calculating their GPA or generating a list of courses the student is enrolled in. The courses class might have a similar method that calculates the overall average of all students in a class, but these could only be run from an object of the appropriate type and permission. An object is an instance (or copy) of the class that represents a particular item, like a particular student or course.

    While most functions in PHP can be used by any script, we can control what pieces of our class structures can be accessed by programmers when an instance of the class is used. We do this with the keywords public, private, and protected that precede our methods or data members in our class. This gives us a means to protect our information and/or control what can be done when the object is being used.

    Public items can be accessed by “anyone” (or anything, such as other classes), meaning we can reference them using -> just like in our example. Protected items can be accessed by other methods in the class, or by methods in parent or child classes that use the class in question—we will cover class inheritance here though. Finally, private items can only be accessed by the class itself. This means that a method or data member marked private in our Math example could only be used by other methods in the class, not by us when we write code to use an object based on the class. To see this in action, we will look at public and private in action by adjusting our math class. To learn more about inheritance and protected methods, you can refer to this chapter’s “Learn more” section.

    1. class math{
    2. public function add($num1, $num2){
    3. return ($num1 + $num2);
    4. }
    5. private function subtract($num1, $num2){
    6. return ($num1—$num2);
    7. }
    8. public function divide($num1, $num2){
    9. return ($num1 / $num2);
    10. }
    11. }

    Since our add and divide methods are set to public, our previous example still works—we are able to add and divide from our code without any issues. If you try to use subtract though ($ourMath->subtract(5,2);) you will end up with an error:

    1. Fatal error: Call to private method math::subtract()

    The only way for the subtract method to be used is by being called from within another method in the Math class. If we had a more advanced method like calculating a longer formula, that method could call subtract as part of its execution.

    Learn more

    Keywords, search terms: Functions, classes, objects, inheritance

    More examples: http://php.net/manual/en/language.oop5.visibility.php

    Constructors and inheritance: http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/

    PHP Objects Patterns and Practice 3rd Edition: http://it-ebooks.info/book/411/

    Chapter 34

    JavaScript Syntax

    Tags

    Defining your block of JavaScript code in HTML is done with the use of another set of HTML tags we have not used yet, <script>. The script tags allow us to link to a script file or mark off a section of our code for our JavaScript to reside in. We can place script tags in any section of our HTML. Traditionally, JavaScript is placed in the head of the page, especially when the code consists of functions to be called or actions that are to occur on page load. If your JavaScript will be shorter or creates some simple output, you might find it easier to place it in your code where you want the output to be.

    As the <script> tags can be used for more than just JavaScript, it is recommended to clarify what type of code the tags contain. To start with an example where we link to an external JavaScript file, we will use a <script> tag and give it attributes to define what our code is and where it lives.

    Additional Notes

    If your JavaScript’s action or output is not critical to visual layout or output of your page, you can move <script> tags to the bottom of your page. This allows the page to render before processing your JavaScript, and gives the user a faster (seeming) experience.

    1. <script type="text/javascript " src="http://someplace.com/scripts/ourscript.js">

    This example would populate the <script> tag set with the contents of the JavaScript file just like we did with CSS. Also like our CSS examples, we can place our JavaScript entirely in the HTML as well. To use the ubiquitous Hello World example yet again, we would replace our example above with the following:

    1. <script type="text/javascript">
    2. alert("Hello World!");
    3. </script>

    The alert function in JavaScript will create the pop up box in our browser that must be closed by the user. By placing this block of code into either the head or body of a blank page as follows, we will get an alert box instead of text on the page:

    1. <html>
    2. <head>
    3. <script type="text/javascript">
    4. alert("Hello World!");
    5. </script>
    6. </head>
    7. <body/>
    8. </html>

    Not only is this a little more exciting than just printing it onto our page, we can even add some control to when we receive this output by giving it a trigger event. A trigger event is anything that can be monitored in order to cause another action to occur. In this case, our trigger event will be a click of a button. To do this, we need to stop our alert from running as soon as the page loads. We will do that by wrapping it in a function declaration so it only runs when we call it, and then add a button that calls the function:

    • <head>
    • <script>
    • function howdy(){
    • alert("Hello world!");
    • }
    • </script>
    • </head>
    • <body>
    • <input type="button" onclick="howdy()" value="Our Button" />
    • </body>

    chap34_tags.png

    Now when we load our page, the alert window will not show up until we click our button. If it does not, you may need to check your JavaScript settings to make sure it is allowed in your browser. If you are unfamiliar with how to do this, search the Internet for your browser type, version number, and the words enable JavaScript for directions. JavaScript is usually enabled by default, so a double check of your code for typos may also be in order.

    Variables

    Creating variables in JavaScript is very similar to PHP. The variable names still need to begin with a letter, and are case sensitive. They can also start with $ or _ to help us identify them. One difference is that when we declare variables in JavaScript, we do so by putting “var” in front of them. This identifies what follows as a variable, like the $ in PHP. To convert our example into a string variable, we would adjust it as follows:

    1. <head>
    2. <script>
    3. function howdy(){
    4. var str="Hello World";
    5. alert(str);
    6. }
    7. </script>
    8. </head>
    9. <body>
    10. <input type="button" onclick="howdy()" value="Our Button" />
    11. </body>

    Output

    The “echo“ or “print” equivalent in JavaScript can be achieved by instructing it to place the text you want into the DOM (Document Object Model). We reference the document object in JavaScript with the word document, and call the write method to produce our output:

    1. <script language="javascript">
    2. document.write ("Some output from <b>JavaScript!</b>");
    3. </script>

    We can be more specific as to the exact place(s) on the page we wish to put our content. In PHP, we would simply place our print or echo statement where we want the content to appear. With JavaScript we can continue to take advantage of the document object model to specify where we want output to be. This also means the script that makes the content can be stored in a separate location from the output location itself:

    1. <script language="javascript">
    2. document.getElementById("ourText").innerHTML ="Hello World";
    3. </script>
    4. <div id="ourText"></div>

    No matter where the “ourText” div is on our page, or where the script is, the div would contain Hello World as its text. This is the basic approach taken when we use JavaScript to make changes to our page.

    Strings

    While strings work largely the same as they do in PHP and other languages, concatenation is achieved by the use of the concat() function, or the plus (+) sign instead of PHP’s use of period (.). Let us take a look at a couple examples to see the difference:

    1. str1 = "Hello World!";
    2. str2 = "How are you?";
    3. output = str1.concat(str2); // Note we use . to access concat() from the string
    4. output = str1 + " " + str2; // Concating with +, which works like PHP's .

    Arrays

    Arrays in JavaScript work in much the same way as PHP. All we need to keep in mind is that our output needs to use DOM manipulation:

    1. <script>
    2. //Some examples of setting and using array variables
    3. var x;
    4. var mycars = new Array();
    5. mycars[0] = “Saab”;
    6. mycars[1] = “Volvo”;
    7. mycars[2] = “BMW”;
    8. for (x=0; x<stooges.length; x++){
    9. document.write(mycars[x] + “<br>”);
    10. }
    11. </script>

    Braces and Semi-colons

    When a control structure only has one line, JavaScript will allow us to skip the curly brackets that would normally outline its contents. We also do not need to include semi-colons as long as we include a line break after most statements. However, leaving either of these items out can create bugs by inconsistent coding. Adding a second line to your condition statement when not using brackets might work in some cases, but not all. Instead of a syntax error, though, it would be interpreted as part of the next statement after it. This will create a harder to find logic error.

    Learn more

    Keywords, search terms: JavaScript syntax

    Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript?redirectlocale=en-US&redirectslug=JavaScript

    Chapter 35

    JavaScript Examples

    DOM Navigation

    Now we will look at some other techniques we can use to interact with the DOM using JavaScript. We specified we wanted to use a particular element by referencing its ID (getElementById()) but we can also interact with groups of elements that share a special type or class. To reference by type we would call the getElementsByTagName method, giving us a list of elements that we can review, or modify:

    1. <div id="output"></div>
    2. <input type="text" size="20"><br>
    3. <input type="text" size="20"><br>
    4. <input type="text" size="20"><br><br>
    5. <input type="button" value="Submit Form">
    6. <script>
    7. var x=document.getElementsByTagName("input");
    8. document.getElementById("output").innerHTML = ("Number of elements: "+x.length);
    9. </script>

    Perhaps we only want elements inside of another specific element. We can grab inputs from a particular form. To do this, we change our reference from the document as a whole to the element we want to inspect:

    1. <div id="output"></div>
    2. <form id="form1">
    3. <input type="text" size="20"><br>
    4. <input type="text" size="20"><br>
    5. <input type="text" size="20"><br><br>
    6. <input type="button" value="Submit Form">
    7. </form>
    8. <form id="form2">
    9. <input type="text" size="20"><br>
    10. <input type="text" size="20"><br>
    11. <input type="text" size="20"><br><br>
    12. <input type="button" value="Submit Form">
    13. </form>
    14. <script>
    15. var x=document.getElementsByTagName("input");
    16. document.getElementById("output").innerHTML = ("Number of elements: "+x.length+"</br>Number in form2: "+form2.getElementsByTagName("input").length;
    17. </script>

    In this example all we changed was doubling our inputs and putting them into forms. We also used form2 as our reference instead of document to create our second output, although this time we just tacked it onto the end without creating a second variable. You can see in this example that not only can we concat function results easily in JavaScript, we were still able to refer to the length() method, even though it was added to the end of the getElementsByTagName method. This chain is perfectly valid in JavaScript, and will always be evaluated from the inside out just like sets of parenthesis. In this case, counting the inputs in form2 occurred first, creating a temporary object that .length was instructed to access.

    Events

    It is important to keep in mind that JavaScript is not living within the confines of an object or function and will be processed as soon as it is loaded. Depending on its placement in the document this means our script may attempt to utilize something in the DOM that has not been created yet as the page is still loading. If we want our code to wait until the full page is complete, we need to wrap our code into one of these two items and then use a trigger, or event, to signify when the page is ready. One approach to this is adding an onload attribute to our body tag:

    1. <body onload="ourFunction()">

    We can even monitor events that do not involve the document itself like the location of the mouse. Monitoring the location of the mouse may have little practical application in the average website, but it can be useful in web based games and analytics applications, where knowing the position or path the mouse is on can influence how the page acts:

    1. <script>
    2. function getCoords(event){
    3. var x=event.clientX;
    4. var y=event.clientY;
    5. alert("X: " + x + ", Y: " + y);
    6. }
    7. </script>
    8. <p onmousedown="getCoords(event)">Click anywhere on this sentence to see the x and y coordinates of the mouse. Clear the alert and try again to see the numbers change.</p>

    When an event we are waiting for occurs, we can react by executing other steps before it is processed, or even replace it. We can see an example of this by saying goodbye before a visitor leaves our page:

    1. <script>
    2. function sayGoodbye(){
    3. alert("Thanks for visiting!");
    4. }
    5. </script>
    6. <body onunload="sayGoodbye()">

    To stop an event, we can use the preventDefault() method, which allows us to supersede what would have taken place. For instance, we may want to use a link to trigger a JavaScript function, but do not want to the page to reload, or follow the URL that was clicked on. In this example, we could have the following:

    1. <script type="text/javascript">
    2. addEventListener("load",function(){
    3. var link= document.getElementById("google");
    4. links.addEventListener("click",function(e){
    5. e.preventDefault(); //prevent event action
    6. }
    7. });
    8. </script>
    9. <body>
    10. <a href=http://www.google.com id="google">Google</a>
    11. </body>

    Geolocation

    Devices and browsers that have access to GPS, cellular, or wireless router location data may provide that information to web pages (usually also in conjunction with user permission). When this data is available, our webpage can receive the information from the device. We can use it to improve the user experience, or provide features that are location dependent, like finding the nearest restaurant, or offering local deals. This example demonstrates how to access the information if it is available. Once we have the coordinates, we can write additional scripts on our backend (PHP and/or MySQL) that use them in order to tailor the user experience.

    Keep in mind most browsers/devices allow the user to turn these features on and off, and not all devices will have access to or share this type of information. Because of this, it should not be a required or relied upon features unless you are sure your target users will be on such a device, and are aware that this type of feature is a requirement.

    1. <p id="text">Where am I?</p>
    2. <button onclick="getLocation()">Find Me</button>
    3. <script>
    4. var response=document.getElementById("text");
    5. function getLocation(){
    6. if(navigator.geolocation){
    7. navigator.geolocation.getCurrentPosition(position);
    8. }
    9. else{response.innerHTML="Geolocation is not available from this device or browser.";}
    10. }
    11. function position(loc){
    12. response.innerHTML="Latitude: " + loc.coords.latitude +
    13. "<br>Longitude: " + loc.coords.longitude;
    14. }
    15. </script>

    Chapter 36

    jQuery

    jQuery is a freely available library add-on to JavaScript. It reduces the amount of code and complexity required to produce features and effects commonly used in creating today’s sites. This library rapidly extends how much, and how fast, you can improve upon your site. In addition to jQuery, additional library extensions have been created that extend the jQuery library to automate even more tasks.

    Before we begin to look at jQuery, we should consider implementation. The jQuery library is hosted for free on Google’s servers at ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js (you may need to adjust the version number for future releases). While you are free to save any number of versions to your own site, there are benefits to using Google’s copy. Among them are decreased latency (Google’s copies are distributed on servers around the world), decreased communication load on your server, and a caching benefit—the more sites using Google as their source increases the chance your user will already have a recent copy on their device.

    Once you have connected to Google, you may want a fall back—Google or not, things can happen. To do this, we need a mechanism to detect whether or not our Google hosted copy loaded correctly. To achieve this, we can test for a feature that is only present in jQuery after we have attempted to load it. If this feature fails, we can assume something went wrong, and then load our fallback copy. All of this can be done by adding two lines in our code:

    1. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    2. <script>window.jQuery || document.write('<script src="link/to/our/jquery-1.10.2.js"><\/script>')</script>

    Once we have connected to the jQuery library, we can begin to use it in our JavaScript code. jQuery statements begin with a $ and then expect information on the selector we wish to use or the method we wish to access in order to take action. Using the document object method (DOM) to select a page element in JavaScript bears resemblance to the chain selector approach of Java:

    1. document.getElementByID('ourAttributeName');

    Meanwhile, jQuery allows us to identify the same element simply by referencing the same attribute:

    1. $('#ourAttributeName');

    While neither of these examples actually interact with the attribute, both identify the same unique place in our document. With jQuery, the use of the pound sign (#) in our selector specifies that we are looking for an ID. The #, in this case, takes the place of typing out document.getElementByID.

    Alternatively, if we wanted to select all elements on our page with a particular class, we would exchange our pound sign for a period. This specifies that we want to select all items of the identified class:

    1. $('.ourClassName');

    Once we have declared our selector, it takes on aspects of an object, something that we can interact with whether it represent one or many elements on our page. For example, we can hide all paragraphs on a page by setting a button to do so:

    1. <script>
    2. $(document).ready(function(){
    3. $("button").click(function(){
    4. $("p").hide();
    5. });
    6. });
    7. </script>
    8. <h2>Hide those paragraphs!</h2>
    9. <p>This is a paragraph.</p>
    10. <p>This is also a paragraph.</p>
    11. <button>Hide them!</button>

    In this example you will see we have three statements, all nested together. Moving from the inner-most statement out, we first have the action of actually hiding our paragraphs. This is executed as the callback of the statement it sits inside, meaning it is executed when the button element receives a click. Finally, we want to ensure that none of this occurs until the entire page is ready, as it is a response to a user interaction and not part of creating our page. To ensure this happens, all of this is nested inside a ready function attached to the entire page, which is referred to as document. This means nothing inside the $(document).ready… line will be available until after the page is done loading. Let us look at another example, where we change existing content instead of hiding it:

    1. <script>
    2. $(document).ready(function(){
    3. $("#btn").click(function(){
    4. $("#test").html("<b>We changed it!</b>");
    5. });
    6. });
    7. </script>
    8. <p id="test">This is text we will change.</p>
    9. <button id="btn">Set new HTML</button>

    Like newer versions of CSS, we can traverse elements in our page by utilizing concepts like next and closest to move around from our starting point, without having to know exactly where our destination lies in the DOM. For example, if we were to call closest() on our $(‘#link’) selector, it would traverse up through our page to find the preceding link. In our working example, we do not have one. In this case, the selector would return false, specifying that another link was not found. Otherwise, our selector would now represent that link, and any actions we took would apply to the new, preceding link that we had selected.

    Using classes and IDs as our selectors is another best practice approach to using jQuery. While we could specify that we are looking for images that are in paragraphs that are in forms inside of a div tag, the resulting selector ( $(“div form p img”); is actually read in reverse. jQuery will process this by finding all images, eliminating those not immediately wrapped in a paragraph, eliminating from that list items which are not in a form, and then eliminating from what remains anything that is not immediately within a div.

    Reading out the explanation is exhausting enough, let alone processing it. Although we could use the example above effectively, if we know the use case we want our selector to impact, we should simply add or implement an ID or class to those element(s) we wish to interact with. By sticking with a class or an ID, the selector can simply traverse the DOM looking for those identifiers. If you still need to use the combined selector approach, set it to a variable so you can refer to that variable in other places. This will save you the effort of finding all of those elements again.

    The examples here are only a glimpse of the full power of jQuery. We are keeping it brief for a reason; until you are more comfortable with both JavaScript and CSS, immediately relying on a library can muddle the learning process. That being said, it is a powerful tool that you should embrace when ready to add more complex enhancements to your site.

    Learn more

    Keywords, search terms: jQuery, jQuery libraries

    50 jQuery Add-ons: http://tutorialzine.com/2013/04/50-amazing-jquery-plugins/

    Full Documentation: http://api.jquery.com/

    1 Jacot, de Boinod, Adam. Global Wording. Smithsonian Magazine. March 2006. Web. 15 Dec. 2012

    • Was this article helpful?