Learn PHP 7: Object-Oriented Modular Programming using HTML5, CSS3, JavaScript, XML, JSON, and MySQL (2016)

Chapter 1. An Introduction to PHP 7

Steve Prettyman1 

(1)

Georgia, USA

Electronic supplementary material

The online version of this chapter (doi:10.​1007/​978-1-4842-1730-6_​1) contains supplementary material, which is available to authorized users.

PHP is a popular general-purpose scripting language that is especially suited to web development. Fastflexibleand pragmaticPHP powers everything from your blog to the most popular web sites in the world.” — www . php . net

Chapter Objectives/Student Learning Outcomes

After completing this chapter, the student will be able to:

·               Understand the differences between LAMP, WAMP, and MAMP

·               Successfully install a version of LAMP, WAMP, or MAMP

·               Search the Internet for troubleshooting problems

·               Explain the difference between a programming language and a scripting language

·               Create an error-free simple PHP program

PHP 5.5+, PHP 7+, and PHP.NET

Today, PHP (Hypertext Preprocessor) is one of the most popular languages used for web application development. The language has evolved to allow the programmer to quickly develop well-formed error-free programs using both procedural and objected-oriented programming techniques. It provides the ability to use many preexisting libraries of code that either come with the basic installation or can be installed within the PHP environment. This gives you multiple ways to complete a particular task. It provides more flexibility than many other languages. The ease with which additional libraries of code can be added to the environment is one of the many driving forces in its popularity.

Procedural languageA procedural programming language includes functions/methods that can be called from the main flow of the program. The flow of the program jumps to the function/methodexecutes the code within the moduleand then returns to the next statement in the main flow of the program. Some Procedural languages include a main function/method that automatically is called when the program is executed.

Object-oriented languageAn object-oriented language uses classes and objects. Classes are similar to blue prints. A class describes what an object can containincluding properties/variables and functions/methods. An object is an instance of a class (like a building that has been created from a blueprint). Object-oriented languages provide polymorphismencapsulationand inheritance. Objects are naturally encapsulated by containing all related functions/methods and properties/variables within the object itself. Polymorphism allows duplicate method/function names within object-oriented objects. Howeverthe “signature” must be different. The “signature” is the combination of the types of variables (numbers and characterspassed into the method/function and the type of information passed out of a method/function. For exampleseveraladd methods could be createdone that only accepts integers (whole numbers), one that only accepts floating point numbers (numbers with decimals), and one that accepts a combination. The program will determine which method/function to call by what has been passed into the method/function. Inheritance in object-oriented programming allows an object to inherit properties/variables and functions/methods from another object. The object can also override those items inherited. This is similar to a child inheriting characteristics from the parents. Object-oriented languages can also be event-driven. An event-driven program will “sleep” until an event occurs. This is similar to an ATM machine program waiting for a user to input an ATM card.

PHP is an open source language. As such, each version of the language is created using input from the individuals who use it—the programmers themselves. This allows the language, over time, to evolve and float into the direction that is driven by the users. From its first release in 1995 as a Personal Home Page Tool (PHP) by Rasmus Lerdorf, the versions have been released on the Internet with forums to provide users the ability to make suggestions and even provide code changes and additions. Today www.php.net is the official PHP web site.

Open source languageAn open source programming language is developed by a community of interested parties. The community accepts input from fellow programmers for suggested upgrades and corrections. Several members of the community work together to present proposals and to make changes to the language. Open source languages are “free”. A non-open source language (such as Microsoft C#) is created and updated by a company or major organization. Non-open source languages are not usually “free”.

A978-1-4842-1730-6_1_Fig1_HTML.jpg

Figure 1-1.

PHP.NET (09/24/15)

The www.php.net home page provides information on each of the latest releases of the language. It also provides information on future releases, the features planned for those releases, and the planned release dates. In addition, other related PHP information can be found, including links and information to major PHP conferences.

A978-1-4842-1730-6_1_Fig2_HTML.jpg

Figure 1-2.

Get involved (09/24/15)

As mentioned, this site provides the ability for users to help with the future development of the language. Users can get involved with testing beta versions and reporting errors or program bugs. Visitors can also view documentation related to the development of possible future versions. This is a good way of discovering future enhancements or security fixes before major announcements have been made to the public.

A978-1-4842-1730-6_1_Fig3_HTML.jpg

Figure 1-3.

Download page (09/24/15)

The download page, as you might have guessed, provides the ability to gain easy access to the latest versions of the language. However, as you will note, only the language itself is provided. It is more common, and recommended, that the beginning user use a WAMP (Windows, Apache, MySQL, PHP); LAMP (Linux, Apache, MySQL, PHP); or MAMP (Mac, Apache, MySQL, PHP) package for initial installation. These packages (which we will look at later) allow for easy installation of multiple products at the same time. Otherwise, you have to run many separate installations, which can become complicated and error-prone if incompatible versions are installed.

A978-1-4842-1730-6_1_Fig4_HTML.jpg

Figure 1-4.

Documentation pages (09/24/15)

WAMP/LAMP/MAMPOpen source (freecombinationsincluding Apache Web ServerMySQLand PHP for a specific operating system (WindowsLinuxand Mac). These packages are open source. The combination of software is used for creating dynamic web sites and web applications.

One of the more important pages of the PHP web site is the documentation page. This page allows users to search for descriptions and functionality of the language itself. You can also download the complete documentation. However, since this is a “live” site, with possible changes occurring, the most current information is best obtained by directly accessing it from the web site.

A978-1-4842-1730-6_1_Fig5_HTML.jpg

Figure 1-5.

The Manual (11/11/14)

You can use the manual as if it were a textbook by clicking through each link from the beginning. The limited amount of explanation provided with each section of the manual might cause a beginner to want to give up on programming and change interests to something ghastly like networking! The manual does provide a great guide for experienced programmers, as the syntax of the language is similar to other languages such as JavaScript, Perl, and Java.

A978-1-4842-1730-6_1_Fig6_HTML.jpg

Figure 1-6.

Search (11/11/14)

On any page of the web site, the user can enter a term, an expression, or even a function name to find more information. As the information is entered in search box, the web page will provide the user with one or more options below the box for the user to select.

Once the user has selected an option (such as echo shown in Figure 1-7), the results of the search provide the user with a general description of the item requested, any inputs or outputs for a function (parameters), and example code.

A978-1-4842-1730-6_1_Fig7_HTML.jpg

Figure 1-7.

Echo (11/11/14)

The example code provides explanations of the use of the function within the code itself by using comments (indicated by the // and gold color in Figure 1-8). The comments are not executable code. The executable code is color-coded to highlight strings (red), variables (blue), keywords (green), and the PHP opening and closing tags (blue). Color-coding helps make the code more readable. It also can make it easier to find syntax errors when creating programs. Many PHP editors provide similar color schemes.

A978-1-4842-1730-6_1_Fig8_HTML.jpg

Figure 1-8.

Echo code (11/11/14)

PHP 5.6+ and PHP 7+

With the release of the PHP 7 environment, great improvements have taken place. PHP 5.5+ has dramatically improved security. In this book, we will use the newest PHP encryption tool “password hash” instead of MD5 which many current books use. Over the last several years, MD5 has proven to be vulnerable to hacking.

PHP 7 is based on the PHPNG project (PHP Next-Gen), that was led by Zend to speed up PHP applications. The performance gains realized from PHP 7 are hugeThey vary between 25and 70on real-world appsand all of that just from upgrading PHPwithout having to change a single line of code!” — www . zend . com

PHP 7 also replaces fatal errors, which previously would crash a program, with exceptions that can be handled within the program itself.

If you are migrating from a previous version of PHP to PHP 7, please review the following link:

http://php.net/manual/en/migration70.php

The code used in the examples in this book is compatible with PHP 7. Most examples are also compatible with PHP 5.5 and PHP 5.6.

Do It

1.

Go to www.​php.​net. Search for information on the print and printf functions. How are these functions similar? How are they different?

2.

How do you “join the team” and help with the creation of the next version of PHP? Hint: Go to the “Get Involved” section of www.php.net , select “Guide for Contributors,” and then find the “Join the team” link. Of course, the web site changes, so you may need to find a different route to the information.

3.

Which ways can the www.php.net web site be useful for a beginning PHP programmer?

4.

What language is used to create PHP? Hint: The answer is somewhere on the www.php.net web site.

5.

Go to www.php.net . Search for the list of improvements and changes with PHP 7. List those improvements and changes. Which of these do you think will affect a beginning level programmer?

PHP, JavaScript, CSS, HTML, and Apache Web Server

PHP is a scripting language. A scripting language is different than an actual programming language. Programming languages (such as Java) are written by the programmer in an English-like syntax. The program is compiled, which means it’s converted from the English syntax into machine code (0s and 1s). This code is then executed (run) within a compatible operating system and hardware. Scripting languages do not use a compiler. The first time the code is accessed it is interpreted line by line as the program is executed.

You may wonder if this causes the code to be slower than compiled code. The answer is no. Once the code has been executed once, the interpreted code stays in the memory of the computer, or server, for other executions. If the programmer changes this code, a new version will replace the previous version in memory.

JavaScript is also a scripting language. As you may be aware, JavaScript code can be seen within a web browser by viewing the source, as shown in Figure 1-9.

A978-1-4842-1730-6_1_Fig9_HTML.jpg

Figure 1-9.

JavaScript, HTML, and CSS code from yahoo.com (11/11/14)

The source code displayed in Figure 1-9 is from www.yahoo.com and it shows a combination of several languages, including HTMLCSS, and JavaScript. The JavaScript code (displayed in black) is located between script tags(<script type="text/JavaScript"> and </script>). This JavaScript code will attempt to create a cookie on your machine, if your browser allows cookies.

However, when we look at the www.php.net source code (in Figure 1-10), we cannot see any PHP script code. There are links to some PHP files present, but no actual PHP code is displayed. Why?

A978-1-4842-1730-6_1_Fig10_HTML.jpg

Figure 1-10.

The www.php.net source code (11/11/14)

JavaScript code resides on the user’s computer. It is interpreted and executed within the browser. PHP code resides on a web server. The code is also interpreted and executed, but by the web server, not by the browser. The results of executing the PHP code are returned to the browser, not to the actual code itself.

<?php

Print "Hello";

?>

Note

You may notice other formats for using PHP (such as: <%, <%=, %>, or <script language="php">); with PHP 7 these styles are no longer valid. There were actually depreciated previously, but still usuable.

You might guess that this code will display Hello. While this is correct, the question is, what processes happen to produce this result?

If this code is placed in a file (such as hello.php) on a web server, we would use our web browser to request this file by entering its name and location in the URL (address) box (such as http://servera.com/hello.php ). The address entered instructs the browser to send an HTTP Getrequest to the web server (servera.com) to return the web page (hello.php).

A978-1-4842-1730-6_1_Fig11_HTML.jpg

Figure 1-11.

Requesting an HTML/JavaScript web page

The web server receiving the request will determine that PHP code must first be interpreted and executed. It determines this simply by looking at the file extension (.php) of the file requested. Any PHP code within the file is then sent to the PHP processor for interpretation and execution. The results of the execution of the code is returned to the web server, which in turn sends it (and any other HTML and/or JavaScript code) back to the browser. In this example, Hello would be returned and displayed by the browser. If we then viewed the source code, as mentioned, we would only see the actual word Hello. We would not see any HTML or PHP. Why? Because we did not send any HTML back to the browser.

A978-1-4842-1730-6_1_Fig12_HTML.jpg

Figure 1-12.

Requesting a web page with PHP code

You may be wondering if you can use this process to send back actual HTML (and/or JavaScript) code to create a dynamic web page. The answer is yes. The PHP print function will return any HTML (or JavaScript) code that has been placed between the "". The browser will interpret any code returned by the web server.

Print function. The print function is not actually a function. It is a language construct. Functions require that strings be included in quotes when passed. Language constructs do not require quotes around strings. Howeverit is still recommended. Print will pass whatever has been passed into it to the browser. It will attempt to convert any item that is not a string to string (textformat since all items displayed within a web page are in text format.

For more informationvisit:

http :// php . net / manual / en / function . print . php .

For a more in-depth explanation of the print commandvisit the free “The New Boston” (thenewboston.comvideo(sat:

https :// www . thenewboston . com / videos . php ? cat = 11 & video = 16996

Note

All links provided in this book can be accessed from http://www.littleoceanwaves.com/securephp .

<?php

Print "<h1>Hello</h1>";

?>

If we change our code to the listing above, the browser will display Hello as an HTML header (h1). The disadvantage of using the print function is that the program will have no control over where the statement is displayed on the web page. The statement will actually be displayed as the first line of code, even before any other existing HTML tags. This might be okay if we are just returning a statement to the user, such as “Your process has been completed”. However, this might not be acceptable if your goal is to format output at an exact location on the page. There are other techniques and functions that we could choose to eliminate this problem. However, it is beyond our current discussion.

Now that we know we must interpret and execute PHP code with the help of a web server, what server should we use?

The Apache web server is the server that is most commonly used to host and handle PHP web page requests. Like other web servers, Apache can also accept and return requests for other types of files, including HTML, JavaScript, PERL, images, and RSS feeds. Apache, as mentioned, determines what processes need to be completed from HTTP requests by first looking at the file extensions of the requested files.

A978-1-4842-1730-6_1_Fig13_HTML.jpg

Figure 1-13.

Apache.org web site (09/24/15)

Apache, like PHP, is an open source product. All changes to the Apache web server are coordinated by the Apache Software Foundation. ASP maintains the apache.org web site to provide users and developers the ability to discover projects currently under development and the ability to download the latest versions of Apache. However, as mentioned, downloading separate versions of PHP, Apache, and MySQL can cause issues with incompatible versions. Unless you know what you are doing, it’s much wiser to download a complete WAMP, LAMP, or MAMP version.

A978-1-4842-1730-6_1_Fig14_HTML.jpg

Figure 1-14.

Apache’s Get Involved (09/24/15)

The Apache Software Foundation also encourages all users of their products to keep up to date and to get involved in the development of future products. Users are encouraged to join discussion and mailing groups, test out new releases, and even help fix bugs or add new features to their products.

Do It

1.

What are the differences in executing PHP code compared to executing Java code?

2.

What is the difference between a scripting language and a programming language? What type of language is PHP?

3.

How does the Apache web server handle requests for a PHP web page?

4.

Why can we see JavaScript code within a web browser but we can’t see PHP code?

5.

Go to www.apache.org . What are some of the ways that you can become involved with the development of Apache projects, even though you have limited experience?

PHP, Apache, and MySQL

What happens when a web page requests information from a database?

Commonly databases are stored on servers that are separate from the web server itself.

Does the request for data come from the web server or from the PHP processor?

Since the SQL statements are contained within the PHP code itself, the PHP processor sends the SQL statements to the Database Management System (MySQL) to be processed.

A978-1-4842-1730-6_1_Fig15_HTML.jpg

Figure 1-15.

Requesting a PHP web page that retrieves information from a MySQL database

SQLStructured Query Language is a special language used to updateinsertor delete data from a DBMS (Database Management System). A DBMS is an application that interacts with a program language and a database to updateinsertor delete data. The DBMS uses SQL to interpret the required changes to the data within the database. For more information on SQLvisit http :// en . wikipedia . org / wiki / SQL .For more information on DBMSvisit http :// en . wikipedia . org / wiki / Database .

The Apache server will first discover that PHP code must be interpreted. The PHP code will then be sent to the PHP processor. The PHP processor interprets the code (line by line). While doing so, it will discover that SQL statements must be executed against a database. The SQL statements are then transferred to the appropriate Database Management System (DBMS) for processing. The DBMS will return the results of the execution of the SQL statements to the PHP processor. The PHP processor will then use those results to format output to be given to the Apache server. The Apache server will then combine the results of what is returned by the PHP processor with any other HTML (and/or JavaScript) code that might reside on the original page requested and return all output to the browser on the user’s machine. The browser will then interpret the HTML and JavaScript to display the results of the page requested.

Did you catch all of that?

Let’s look at a “real-world” example, shown in Figure 1-16.

A978-1-4842-1730-6_1_Fig16_HTML.jpg

Figure 1-16.

Google.com search for “green cats” (11/12/14)

For some very strange reason we have decided to look up “green cats” on the Internet. As we enter the string into our favorite search engine (Google in this example) and then click the Search button, the information is passed to a Google server farm somewhere. Where?

Who knows; it could be anywhere on the planet. But the power of the Internet is that we don’t care as long as we get our results back quickly.

A978-1-4842-1730-6_1_Fig17_HTML.jpg

Figure 1-17.

Green cats (11/12/14)

Okay, I must say I am amazed that there are 104 million possible links to green cats. Wow. Maybe we should have filtered that down some. The point, however, is that Google returns a web page with a listing of links and descriptions of those links (plus ads).

Did Google return a static page that already existed?

No. The servers created a dynamic page from the request of the user. The Google algorithms (software) searched the massive Google database farms. The request was first sent to a Google web server from the user’s browser. The web server then sent a request to the Google databases (actually using a Google Query Language similar to SQL) to return information about “green cats”. The software on the web server then compiled the results, added HTML and JavaScript (also some Google Script Language code) for formatting the results web page, and returned the information to the user.

Static vs. dynamic web pagesA static web page does not change in relation to user requests or input. The page is created by a web developer and resides on the web server. When the user requests the page via a browsera copy of the page is sent to the browser for display. A dynamic page does not exist within a web server. The page is created using input from the user. A program residing on the web server will create and format the page. The page that is created by the program is then downloaded to the users browser. A copy of the page is not (usuallymaintained on the web server. For more information on static web pages visit http :// en . wikipedia . org / wiki / Static _ web _ page . For more information on dynamic web pages visithttp :// en . wikipedia . org / wiki / Dynamic _ web _ page .

Did every page get downloaded to the user’s web browser?

No, just the first page. The page links at the bottom of the first results page return information to the web server requesting the next set of information (to dynamically create the second page, or another requested page). As you might now be starting to figure out, the same process we have just discussed related to processing PHP files on the Internet is a very common process for creating dynamic pages.

Your might have noticed something interesting about the results page URL address that was displayed. The address is now https://www.google.com/?gws_rd=ssl#q=Green+Cats , not www.google.com . Google algorithms use the GET HTTP Request when sending search requests to their servers.

HTTPHypertext Transfer Protocol is the protocol (standardfor transferring messages (text and web pagesbetween nodes (computers and serverson the Internet. It is a request-response protocol. For examplea user “requests” a web page though a browser. The web serverresponds” to the request and returns the page to the browser. The browser changes the request into an HTTP Get Request (such as GET/pages/mypage.html HTTP/1.1that is sent to the web server. The web server responds with the information requested and a status code (such as HTTP/1.1 200 OK). For more information on HTTPvisit http :// en . wikipedia . org / wiki / Hypertext _ Transfer _ Protocol # Request _ methods .

<form name="orders" method="get" id="orders" action="searchprocess.php">

Name: <input type="text" name="customername" id="customername"><br />

<input type="submit" value="Submit your name">

</form>

Let’s look at a simpler example above to discover what occurs. Assume the code above is saved in an index.html file on your localhost web site under the projects folder.

A978-1-4842-1730-6_1_Fig18_HTML.jpg

Figure 1-18.

Index.html example

If the user enters Fred in the textbox displayed in the browser, the results page (created by interpreting and executing the searchprocess.php file on the web server and sending the results back to the browser) will display the URL line : http://127.0.0.1/projects/searchprocess.php?customername=Fred .

A978-1-4842-1730-6_1_Fig19_HTML.jpg

Figure 1-19.

Execution of searchprocess.php

The name of the textbox (customername) and the value entered in the textbox (Fred) are now visible on the URL line. Actually, customername is now a parameter and Fred is now the value the parameter holds. This is the result of using the GET process.

When we click the Google Search button or the Search button in our simple example, the requested information is send via the GET HTTP process. All information (and variables) needed for the receiving program are sent on the actual URL line to be received by the program on the web server that will process the initial request.

Why does the Google search engine send information via GET instead of POST (which would have hidden the information)?

The main reason is to save server memory. Just think of the millions of requests that Google has for information. If all of these requests resided in memory, the servers would soon crash. Also, since the user is doing a “public” search for information, there is no reason to hide the information. In later chapters, we will discover how to read both GET and POST parameters within PHP programs.

However, for now let’s get back to our discussion of Apache, PHP, and DBMS.

PHP can access information from many types of DBMS systems, including Oracle and SQL Server. However, the most popular combination (as mentioned already) is to pair PHP with MySQL. I bet at this point you can guess why? Yes, it’s open source and free. MySQL is also one of the easier DBMS systems to use.

A978-1-4842-1730-6_1_Fig20_HTML.jpg

Figure 1-20.

www.​mysql.​com (09/24/15)

Just like all the open source products we have discussed, the user can go to the official web site ( www.mysql.com ) to download the latest versions. Also, as you can probably guess, you can join in on the fun of helping to develop new versions of MySQL and related products. Documentation of current and several previous versions are available for download. The documentation is pretty intense and not for the weak of mind or the beginner. Also, as you probably are tired of reading it is not recommended that you download a new version of MySQL individually until you have more experience. Stick with the WAMP, LAMP, and MAMP packages, at least for now.

Do It

1.

Why does the PHP processor send SQL to the DBMS instead of the Apache web server sending it directly to the DBMS?

2.

What might Apache do with the information received from the DBMS before sending it back to the user’s browser?

3.

Go to www.mysql.com . What is the latest version of MySQL? Which versions of Apache and PHP are compatible?

4.

Why do search engines pass information via GET HTTP requests instead of POST HTTP requests? When would you use a POST request?

Putting it All Together—PHP, Apache, and MySQL

As you have hopefully discovered by this point, PHP, Apache, and MySQL need to run seamlessly together to successfully create dynamic web pages. There are numerous development packages available that provide a combination of these products, along with other tools such as PhpMyAdmin (which is a great help in setting up your web server and databases). By installing one of these products, you will greatly reduce your frustration level and maybe even manage to keep most of your hair. We will briefly look at two of the most popular; EasyPHP and XAMPP. We will not dive in-depth or provide step-by-step install directions for two reasons. As soon as this book is published the directions probably will change, and it’s fine to use the default settings. Accepting what the developers suggest works most of the time.

EasyPHP

A978-1-4842-1730-6_1_Fig21_HTML.jpg

Figure 1-21.

 www.​easyphp.​org (09/24/15)

You can download the developer’s version of EasyPHP from the following link. It is not necessary to download the host version unless you are planning on hosting “live” web pages directly from your computer onto the Internet.

http://www.easyphp.org/easyphp-devserver.php

The developer’s version of EasyPHP is a WAMP (Windows, Apache, MySQL, PHP) package that’s used in the Microsoft Windows environment. There are additional tools that you can choose to also install to assist in development. However, for our purposes you need only the basic install. After installation, the files will be located in your program files directory under the EasyPHP directory.

Warning

Pay attention to which buttons you click on the web site during download. You might download extra items you are not interested in if you don’t read what you are downloading before you click the button(s).

After downloading the installer by clicking the download arrow on the web site, follow the directions provided with the software. On your first attempt, leave all the default settings. Hopefully, everything will install correctly. If not, read the next section entitled, “Common Installation Problems”.

Common Installation Problems

Missing C# Library

PHP 7 (and earlier versions of PHP) require the Microsoft Visual Studio C# library. If you have Windows 8 or later, this library is probably already installed. Also, if you have a recent version of Microsoft Visual Studio, it is also probably already installed. If you receive an error indicating that C# is missing or the wrong version, paste the message into a search engine on the Internet. Search for a response from Microsoft for directions to fix the error. The response should include a link to download the missing files and installation instructions.

Port Conflicts

If you already have a service using port 80, the default port for HTML traffic between your PC and the outside world, you will receive an error message from Apache when it attempts to run. You can fix this problem in multiple ways.

Wikipedia defines a port as:

In computer networkinga port is an application-specific or process-specific software construct serving as a communications endpoint in a computer's host operating system. The purpose of ports is to uniquely identify different applications or processes running on a single computer and thereby enable them to share a single physical connection to a packet-switched network like the Internet. In the context of the Internet Protocola port is associated with an IP address of the hostas well as the type of protocol used for communication.

For more information on portsvisit:

http :// en . wikipedia . org / wiki / Port _( computer _ networking ).

A. If you don’t mind shutting down other services using the port while you are developing, you can follow the directions below. Once you are done using Apache and PHP, you can turn the services back on or just reboot your PC and the services will turn back on.

1.

Go to the Microsoft Windows 7/8/10 Task Manager (press Ctrl+Alt+Delete at the same time).

2.

Select the Services tab.

3.

Look for any of the following services in Windows 7/8/10. If you find one running, right-click it and turn it off. Then try restarting Apache again. If that does not work, turn that one back on and try another one. (The names may be slightly different depending on the version of Windows.)

SQL Server Reporter, Web Deployment Agent, BranchCache, Sync Share Service, WAS (IIS Administrator), and W3SVC

B. If you need your other services running or you do not have the administrative privileges to turn off services on port 80, you can change the default listening port location for Apache.

Go to your system tray (bottom-right corner of your screen). Find the EasyPHP icon by scrolling over the icons. A description of each should appear. If you don’t see the icon, click the up arrow in the system tray to see more icons. Right-click the EasyPHP icon. Select Configuration and then select Apache. This will open the Apache configuration file (httpd.conf) into Notepad (or your default text editor). First save a copy of this file somewhere in case you make an error. This will allow you to recover from any major mistakes that occur. Then search for Listen 127.0.0.1:80within the file. Change the occurrence of 80 to 8080 or to 81; on that line only. This will allow the Apache server to listen to one of the ports that are not commonly used. Resave the file (make sure you are resaving the original file to the original location).

Note

Make sure when you’re using Notepad or any other text editor that you use Save As, and then select All Files for the file type. Also make sure to include the .conf file extension. If you do not change the file type to all files, your file will be saved as httpd.conf.txt. If that happens, the server will not see the file. You can easily fix the problem by reopening the file and saving it in the proper method.

You can then restart Apache by going back to your system tray to find the EasyPHP icon. Double-click the icon; a message box will appear that will give you the status Apache and MySQL. You will probably see red for the Apache status. Click the Apache button. Within a few moments, it should turn green. This will indicate that the server is now running. Do the same for MySQL.

Missing Files

If you receive an error message related to this, somehow your files have become corrupted before installation. Return to the EasyPHP web site and download the files again. Also, if you somehow mess up the Apache configuration file, go back and reinstall the product again.

Can’t Install Files In Program Files Directory

This indicates that you or something else has a high security restriction on that directory. Rerun the installation and change the location of your installation to another directory. Just remember, when we reference the program files directory later in this book, that you should instead look at the directory in which your files were installed.

Apache Delays and Hang-ups

In Windows 8/10 you may experience problems with Apache working slowly or hanging-up. To correct this problem go to your system tray (bottom-right corner of your screen). Find the EasyPHP icon by scrolling over the icons. A description of each should appear. If you don’t see the icon, click the up arrow in the system tray to see more icons. Right-click the EasyPHP icon. Select Configuration and then select Apache. This will open the Apache configuration file (httpd.conf) into Notepad (or your default text editor). First save a copy of this file somewhere in case you make an error. This will allow you to recover from any major mistakes that occur. Then add the following two lines to the bottom of the file.

AcceptFilter http none

AcceptFilter https none Resave the file (make sure you are resaving the original file to the original location).

Other Errors

For errors that have not been discussed here, copy and paste the error into a search engine. Locate an answer column or blog that provides suggestions to fix your error. There are many free resources on the Internet. Do not pay for a web site (or someone else) to fix your problem.

Configurations

You need to determine when you want Apache to run. Apache can be set to run when you boot your PC, when an application needs it, or manually. To change settings, you can right-click the EasyPHP Icon in the system tray (bottom-right corner of your screen), then select Configuration and then select EasyPHP. If you don’t see the icon, click the up arrow in the system tray. A small screen should appear that will allow you to check (or uncheck) two options—Start on Session Startup and Launch Servers When the Application Starts.

There are many optional libraries that you can link or unlink to PHP as needed. In many cases the libraries are already loaded and just need to be linked. You can add these libraries by going to the PHP configuration file (php.ini) and removing the comment (;) character at the beginning of the line. The PHP configuration file can easily be found by right-clicking the EasyPHP icon in the system tray. Then select Configuration and PHP. It is not necessary to make any changes at this point. It is also suggested that you make these changes only when needed. Other libraries can be added using Curl and other methods discussed in later chapters of this book.

For a more in-depth explanation of the php.ini file, view the free “The New Boston” (thenewboston.com) video at https://www.thenewboston.com/videos.php?cat=11&video=16993.

XAMPP

A978-1-4842-1730-6_1_Fig22_HTML.jpg

Figure 1-22.

XAMPP at www.​apachefriends.​org (09/24/15)

Although XAMPP is similar to EasyPHP, XAMPP is more popular because it has free Windows, Linux, and OS X versions. It also includes a lot of add-ons, including some of the most popular content management systems—Drupal, Joomla, and WordPress. The latest downloads can be accessed directly at the official XAMPP web site or at many other download locations.

https://www.apachefriends.org/

Warning

Pay attention to what buttons you click on the web site. You might download extra items you are not interested in if you don’t read what you are downloading before you click the button(s).

During your first attempt at installing, use the default settings that the developers have suggested in the installation software. You will greatly reduce the possibility of problems or headaches. If you do have errors, read the next section entitled “Common Installation Problems” for assistance.

Common Installation Problems

Port Conflicts

If you already have a service using port 80, the default port for HTML traffic between your PC and the outside world, you will receive an error message from Apache when it attempts to run. You can fix this problem in multiple ways.

A. If you don’t mind shutting down other services using the port while you are developing, you can follow the directions on the video link. Once you are done using Apache and PHP you can turn the services back on or just reboot your PC and the services will turn back on.

1.

Go to the Windows 7/8/10 Task Manager (press Ctrl+Alt+Delete at the same time).

2.

Select the Services tab.

3.

Look for any of the following services in Windows 7/8/10. If you find one running, right-click it and turn it off. Then try restarting Apache again. If that does not work, turn that one back on and try another one. (The names may be slightly different depending on the version of Windows.)

SQL Server Reporter, Web Deployment Agent, BranchCache, Sync Share Service, WAS (IIS Administrator), and W3SVC

B. If you need your other services running or you do not have the administrative privileges to turn off services on port 80, you can change the default listening port location for Apache.

Go to your system tray (in Microsoft Windows it’s at the bottom-right corner of your screen). Find the XAMPP icon by scrolling your mouse over the icons. A description of each should appear. If you don’t see the icon, click the up arrow in the system tray to see more icons. Double-click the icon. The Control Panel should appear. You should see start up error messages in red on the console. If it is a port conflict, click the Config button to the right of Apache. Select httpd.conf from the list provided. This will open the Apache configuration file (httpd.conf) into Notepad (or your default text editor). First save a copy of this file somewhere in case you make a mistake. This will allow you to recover the original file. Search for Listen 80 within the file. Change the occurrence of 80 to 8080 or to 81. This will allow the Apache server to listen to one of these ports that are not commonly used. Resave the file (make sure you are resaving the original file to the original location).

Note

Make sure when using Notepad or any other text editor that you use Save As, then select All Files for the file type. Also make sure to include the .conf file extension. If you do not change the file type to All Files, your file will be saved as httpd.conf.txt. If that happens, the server will not see the file. You can easily fix the problem by reopening the file and saving it in the proper method.

You can then restart Apache by clicking the Start button next to Apache in the XAMPP console. If you get a green status for Apache, you will also want to start MySQL by clicking the Start button to the right of MySQL.

Missing Files

If you receive an error message related to this, somehow your files have become corrupted before installation. Return to the XAMPP web site and download the files again. If you somehow have messed up the Apache configuration file, you also will need to download the files again.

Can’t Install Files in Program Files Directory

This would indicate that you or something else has a high security restriction on that directory. Rerun the installation and change the location of your installation to another directory. Just remember, when you reference the program files directory later in this book, that you should instead look at the directory in which your files were installed.

Apache Delays and Hang-ups

In Windows 8/10 you may experience problems with Apache working slowly or hanging-up. To correct this problem go to your system tray (bottom-right corner of your screen). Find the XAMPP icon by scrolling over the icons. A description of each should appear. If you don’t see the icon, click the up arrow in the system tray to see more icons. Right-click the XAMPP icon. Select Configuration and then select Apache. This will open the Apache configuration file (httpd.conf) into Notepad (or your default text editor). First save a copy of this file somewhere in case you make an error. This will allow you to recover from any major mistakes that occur. Then add the following two lines to the bottom of the file.

AcceptFilter http none

AcceptFilter https none

Resave the file (make sure you are resaving the original file to the original location).

Other Errors

For errors that have not been discussed here, copy and paste the error into a search engine. Locate an answer column or blog that provides suggestions to fix your error. There are many free resources on the Internet. Do not pay for a web site (or someone else) to fix you problem.

Configurations

You can change configurations for XAMPP by going to the Control Panel (double-click the XAMPP on the system tray at the bottom-right of your screen). Then click on the config button at the upper-right of your screen (not the config buttons to the right of the applications). You can then check (or uncheck) those applications that you want to have automatically start the next time the Control Panel starts. You should check Apache and MySQL for the lessons in this book. Of course, you can always start them from the Control Panel when needed.

There are many optional libraries that you can link or unlink to PHP as needed. In many cases, the libraries are already loaded and just need to be linked. You can add these libraries by going to the PHP configuration file (php.ini) and remove the comment (;) character at the beginning of the line. The PHP configuration file can easily be found by double-clicking the XAMPP icon in the system tray. Then click the Config button to the right of Apache. A list will display; select php.ini. It is not necessary to make any changes at this point. It is also suggested that you make these changes only when needed. Other libraries can be added using Curl and other methods discussed in later chapters of this book.

Microsoft Internet Information Server

Alternatively, if you are unable to get Apache to perform properly in Windows (especially Windows 8 or Windows 10), or you like Microsoft’s IIS Server, you can install PHP to use Microsoft IIS (Internet Information Server) instead of Apache. For more information, visit:

http://www.microsoft.com/web/platform/phponwindows.aspx

Do It

1.

Use a search engine to answer this question: You receive the following error either while installing or as soon as you try to start XAMMP or EasyPHP. How can you find the solution to your problem? What might be causing this error?

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, you@example.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

2.

Use a search engine to answer this question: What is XAMPP error #1130? How can you fix this error?

3.

Use a search engine to answer this question: When trying to run a PHP program using EasyPHP (and Apache) you receive the error below. What is causing this error? How can you fix it?

Cannot load mcrypt extension. Please check your PHP configuration.

4.

If you have not already attempted to do so, install either EasyPHP or XAMPP on your personal machine. Did you have any problems with your installation? If so, what problems did you have? How did you solve those problems?

Testing Your Environment

You have green lights now, right? Everything is working correctly?

Well, hopefully. However, you need to make sure. The best way to do this is to test your environment.

Testing Your Administration Environment

First we need to test the server and see if our administration pages will display. In EasyPHP, you can do either of the following:

1. Right-click on the EasyPHP icon and select Administration.

or

2. Open your favorite browser and enter the following:

http://127.0.0.1/home/

If you had to change your port due to conflicts, you may need to enter the port number, such as:

http://127.0.0.1:8080/home/

You should see a screen similar to the one shown in Figure 1-23.

A978-1-4842-1730-6_1_Fig23_HTML.jpg

Figure 1-23.

EasyPHP administration screen (PHP 5.6)

For XAMPP, open your favorite browser and enter this address:

http://127.0.0.1/dashboard/

If you had to change your port due to conflicts, then you must also include this port:

http://127.0.0.1:8080/dashboard/

If XAMPP is installed properly, you should see a screen similar to the one shown in Figure 1-24.

A978-1-4842-1730-6_1_Fig24_HTML.jpg

Figure 1-24.

XAMPP dashboard screen (09/24/15)

If at this point you are not seeing this page (or some page with XAMPP displayed), something is wrong. Check the following:

Is EasyPHP or XAMPP running (started)? Do you see the green light or green shaded color for Apache either in the XAMPP Control Panel or in EasyPHP? If not, try clicking the start buttons or links.

If Apache will not start, are you seeing an error message? If not, check the error log file. For EasyPHP, right-click the icon on the system tray and select the error log file for Apache. For XAMPP, click the Log button on the Control Panel next to Apache and select Error Log.

If you see green and the pages seem to be locked up, try stopping and restarting Apache. If might take a couple of attempts to wake it up. If it continues to hang, check your computer settings. Are you maxing out on CPU usage?

Can you determine the problem? If you have an error message, paste it in your favorite search engine and see what the experts say about the problem.

Do It

1. If you have not already done so, test your environment using the directions above. Did you have any problems? If so, what problems occurred? How did you fix those problems?

Testing Your PHP Environment

Hopefully everything is good at this point. Either you have been flying through with great luck, or you managed to fix all the problems you have encountered. However, you still need to see if you can actually run your own PHP program in Apache.

Open a text editor (not Word, but Notepad or Notepad++ are good), and enter the following code exactly as it has been shown.

<?php

print "Hello World";

?>

A978-1-4842-1730-6_1_Fig25_HTML.jpg

Figure 1-25.

Using Save As with All Files to save PHP programs

Using the Save As selection on the File menu, change the File Type to All Files or to php. Enter the file name myfirstprogram.php and save it in one of the locations below.

If you are using EasyPHP, save it to:

C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects

Of course, you should change the version name (or Program File name) to the correct version (location) that you are using on your machine. If you have a version of EasyPHP that does not have the localweb\projects folders, find the location of the www folder under the EasyPHP folder and create a folder called projects. Then save the file under that folder.

If you are using XAMPP, first go to C:\xampp\htdocs and create a folder called projects. Then go back to your text editor, choose Save As (don’t forget to change the file type to All Files or php), name the file myfirstprogram.php and save it to the location below.

C:\xampp\htdocs\projects

If you saved your files correctly in the EasyPHP or XAMPP locations, you can attempt to run your program by entering the following in your browser URL box.

http://127.0.0.1/projects/myfirstprogram.php

If you changed the port, then change the first part to http://127.0.0.1:8080/ (enter the correct port you are using in place of 8080).

Your program should display the message shown in Figure 1-26.

A978-1-4842-1730-6_1_Fig26_HTML.jpg

Figure 1-26.

Hello World

Common Problems

Nothing is displayed, error 404:

1.

Make sure you typed the address exactly as shown.

2.

Your server might be hung up. Stop and restart it.

3.

Make sure you placed your file in the correct location.

4.

Make sure you saved your file as a .php file and not as .txt. Try Save As again and renaming the file (make sure file type is either All Files or php).

5.

Check for typos in your actual program code. Did you remember the semicolon (;)? Fix any and resave. You might need to stop and start the server if it does not see the changes for some reason. You can go to the log files and look at the PHP log files to see any errors that might exist in your code.

6.

Go to the Apache log files (see directions in previous common problems) to look for errors. If you cannot correct them, copy the errors and paste them in a search engine to see what others have found as solutions.

The actual program code is displayed not the results of executing the code:

1.

Make sure you saved your file as a .php file and not as .txt. Try Save As again and renaming the file (make sure file type is either All Files or php).

2.

Your Apache server or PHP might not be started or is hung. Stop and start Apache again.

3.

Did you forget or have a typo in the <?php or ?> lines?

4.

Go to the Apache log files (see directions in previous common problems) to find the errors. If you cannot correct them, copy the errors and paste them in a search engine to see what others have found as solutions.

For any other errors, copy and paste them into a web search engine to see what others have discovered as a solution.

EasyPHP’s Code Classroom

If you are still having problems getting a version of LAMP, MAMP, or WAMP to work on your computer, all is not lost.

EasyPHP ( www.easyphp.org ) now has an online coding environment for students and teachers. This environment (see Figure 1-27) allows you to enter code (black window below), click a Submit button (red button), and see your results on the right (white window).

A978-1-4842-1730-6_1_Fig27_HTML.jpg

Figure 1-27.

 www.​codeclassroom.​net

Do It

1. If you have not already tested your environment, do so. Did the test work? What problems, if any, did you have? How did you solve those problems?

Alias Directories

It is common practice in the real world to create alias directories in web servers. Alias directories are “fake” locations of files that trick the user of your web site into believing a file is in one location when it is in another.

Why would you use an alias directory? As web sites grow, the locations of files on servers may have to change. By using an alias the user of your web site will not know that the actual location of the file has changed. The alias gives you the ability to store your files in any location on your computer (server). If you are not using an alias all your files must be stored in the default location. The default locations are:

EasyPHP: C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\

XAMPP: C:\xampp\htdocs\

You might want to consider creating an alias directory, especially if you want to locate your files on a jump drive. In this book, we assume that files are located under the default locations in a projects folder.

EasyPHP: C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects

XAMPP : C:\xampp\htdocs\projects

This will allow us to test programs using the same URL whether we are using EasyPHP or XAMPP.

http://127.0.0.1/projects/myfirstprogram.php

If you do create an alias directory, just remember to replace projects with whatever alias name you are using.

A978-1-4842-1730-6_1_Fig28_HTML.jpg

Figure 1-28.

EasyPHP alias screen

In EasyPHP, alias directories can be created from the Administration screen. Go to the system tray (bottom-right of your screen), right-click the EasyPHP icon, and select Administration. In the middle of the screen, locate Local Files, and then locate the Add an Alias button to the right. Click and follow the directions. Before adding your alias, the folder must already exist.

A978-1-4842-1730-6_1_Fig29_HTML.jpg

Figure 1-29.

The httpd-xampp file

In XAMPP, it takes a little more work. Open the system panel by double-clicking the XAMPP icon. Then click the Config button to the right of Apache. Select the httpd-xampp configuration file from the list. Choose Edit. Find from your text editor menu. Search for the string '<IfModule alias_module>'. Do not change anything that is already listed in this section. However, you can add locations (using the following code) for your executable files. Once you have entered the required lines, stop and start Apache to help it find the new changes.

Alias /myfiles "C:/Temp"

<Directory "C:/Temp">

Options Indexes FollowSymLinks MultiViews ExecCGI

  AllowOverride All

  Require all granted

</Directory>

For more information on creating alias directories, visit:

https://www.youtube.com/watch?v=XX6t3zJRXF8 .

Note

This directory setting allows complete read and write capability to the directory. We will discuss options to secure the directory for “live” sites in a later chapter.

A978-1-4842-1730-6_1_Fig30_HTML.jpg

Figure 1-30.

Hello World running from the alias directory called myfiles as an index.php file

This listing would allow any files in the C:/Temp directory to execute in Apache when the user enters myfiles as a directory name in the URL line. The directory settings provided don’t provide much security. However, this is just for testing on a test machine. If you are in a live environment, you would need to tighten the security settings under the directory tag. To execute the files within this directory, you would enter the URL http://127.0.0.1/myfiles in a browser. If you do not include a file name, Apache will try to find an index.html or index.php file. If neither exists, Apache will list the files in the directory, with the current settings. This allows easy access to files for testing. However, it is not a good idea in a live environment. You can request a file that is not the index file by adding the file name ( http://127.0.0.1/myfiles/myfirstprogram.php ). Remember to include the port number if you had to change it ( http://127.0.0.1:8080/myfiles/myfirstprogram.php ). Of course, the directory must exist and the files must be in the directory before you test the URL in a browser.

Do It

1. Create an alias folder called myfiles that points to an existing location on your hard drive or jump drive. Place the hello world program that you used to test your environment in the folder. Try to run the program from the folder using the previous instructions. Were you successful? If not, what problems did you have? How did you fix those problems?

Notepad++, Editors, and Code Testers

When creating PHP code, you do not need to use a specific editor or purchase an editor. You can create all code within a text editor (even in Notepad). However, it does help to have an editor that highlights (colors) your code to make it easier to discover coding (syntax) errors.

Notepad++

A978-1-4842-1730-6_1_Fig31_HTML.jpg

Figure 1-31.

Hello World inside Notepad++

Notepad++ is available for download at www.notepad-plus-plus.org . This editor is basic and easy to use. It can create files in over 20 different forms (including PHP). Most of the coding examples provided in this book are created with Notepad++. When you’re creating a new PHP program in Notepad++, you must tell the application the file type. You can do this by choosing the Language menu item and then choosing PHP. This will allow the application to help you with color-coding and other features.

Other Editors

There are hundreds of other editors available. I suggest you pick one that you are most comfortable using; www.download.com is a good site to find PHP free editors. Pick one that has lots of users and a strong rating.

As mentioned previously, you may want to also try EasyPHP’s code classroom at:

www.codeclassroom.net

Do It

1. Decide on a text editor that you will use to complete your coding while using this book. Download the editor to your PC. Retype your hello world program in the editor and save the program. Run the program from your browser. Why did you choose the editor that you downloaded? What do you like about the editor? What do you not like about the editor?

Chapter Terms

PHP

Procedural Language

Object-Oriented Language

www.php.net

WAMP

LAMP

MAMP

Scripting Language

Programming Language

JavaScript

Web Browser

Source Code

HTML

CSS

Script Tags

Web Server

print Function

Apache

Apache Software Foundation

SQL

Database Management System

Static Page

Dynamic Page

GET HTTP Request

MySQL

EasyPHP (Developer’s Version)

Port 80

httpd.conf

php.ini

XAMPP

XAMPP Control Panel

Alias Directories

Open Source

Notepad++

Chapter Questions and Projects

Multiple Choice

1.

MAMP stands for

a.

Mobile Application Motor Processor

b.

My Awesome Mobile Program

c.

Apache-MySQL-PHP

d.

Modern Application Modular Programing

e.

None of these

2.

The goals of the Apache Software Foundation (ASP) include

a.

Coordination of all changes to the Apache web server

b.

Overseeing the selling of all Apache software

c.

Licensing all web servers

d.

Maintaining membership to open source programming through the Apache web server

3.

What scripting languages can be viewed within a web browser?

a.

Java

b.

XML

c.

JavaScript

d.

PHP

4.

Select the statements that are true about static web pages:

a.

They are sometimes called flat page/stationary pages

b.

They are generated by a web application

c.

Static web pages display the same information for all users

d.

All of the above

e.

A and C

5.

___________ is an object-oriented computer programming language commonly used to create interactive effects within web browsers.

a.

HTML

b.

XML

c.

JavaScript

d.

PHP

6.

What is the correct way to end a PHP statement?

a.

;

b.

New line

c.

<!php>

d.

.

7.

The configurations button on the XAMPP Control Panel allow the user to do what?

a.

Install XAMPP

b.

Select applications to automatically start

c.

Manage add-ons

d.

Configure MYSQL

8.

php.net provides all of the following except

a.

Information of each latest release

b.

PHP language documentation

c.

LAMP, MAMP, and WAMP downloads

d.

Contributions to the PHP documentation

9.

Which of the following best describes a scripting language?

a.

The language is compiled.

b.

The program must be compatible with operating system and hardware.

c.

The first time the code is accessed is when the program is first executed.

d.

The code is slower than compiled code

True/False

1.

The alias directory allows you to save your web page files in a directory (folder) of your choice rather than a www directory. It allows a URL address to point directly to that folder.

2.

A static page is a page added to the dryer when drying clothes to prevent static cling.

3.

A client browser submits a GET HTTP request to the server, then the server returns a response to the client browser.

4.

The (Developer’s Version) of EasyPHP can be purchased only for one year at a time.

5.

A dynamic web page never changes but a static web page is always changing.

6.

WAMP stands for Windows, Apache, MySQL, and PHP.

7.

Apache is an example of a web server.

8.

HTML stands for Hypertext Markup Language.

9.

PHP originally stood for Personal Home Page.

10.

A procedural language is a programming language that uses classes and objects.

11.

While viewing a web site in a browser, you may view the source code, which can show you HTML, JavaScript, and CSS. However, PHP code will not be visible.

12.

Java is a procedural programming language.

Short Answer/Essay

1.

Explain the process that occurs when a browser requests a static web page.

2.

Explain the process that occurs when a browser requests a dynamic web page.

3.

Explain the difference between a procedural language and a scripting language.

4.

How do you add access to PHP library code to your program?

5.

Why should you use WAMP, MAMP, or LAMP instead of installing each application individually?

Projects

1.

Create a PHP program to display a summary of your work history and educational history.

2.

Create a PHP program to display your major and the courses required to complete your major.

3.

Create a PHP program to display the goals and/or objectives of your college/university.

Term Project

1.

Your supervisor has requested that you design a secure application that will keep track of inventory in the warehouse of the ABC Computer Parts Corporation. This application will be accessible both within the warehouse itself and outside (via the Internet and/or smart phones). What data fields are necessary to keep track of this information? What size and data types (string, integer, floating point) should define these fields? What other restrictions on input (no negative values for item number) should be defined for these fields?

For example, if a Social Security Number (SSN) was a required field:

SSN: SIZE: Min: 9 characters (string) Max: 9 characters (string) Restrictions: Valid SSN format

Notice that it uses characters, not integers, because no calculations will be done on the SSN number.