Chapter 2 PHP Fundamentals

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Chapter 2 PHP Fundamentals

This line looks perfectly fine to me. What PHP is telling us is that
you have done something, in this case set a delimiter for text, on the line
BEFORE line 8 and now the perfectly acceptable > on line 8 is unexpected.
You need to look at line 6 where you will find the closing delimiter of “
missing at the end of your text. Go ahead and add “ to the end of the line
and refresh your page, which should now render with no errors.
Now that you can create and assign variables, render text to the screen,
and trigger/understand errors that show up, let’s start building some
pages. This is the reason you picked up this book, right? Go back to your
Chapter2 directory and open the file main.php.

<code>
<?php
error_reporting( E_ALL );
ini_set( "display_errors",1);
$title = "Beginning PHP 8 & MySQL";
$content = "Here is the main content for this page";

$html ="
<!doctype html>

<html lang='en'><?php

<head>
  <meta charset='utf-8'>

  <title>$title</title>
  <meta name='description' content='Basic HTML5 Page'>
  <meta name='author' content='Your name'>

  <link rel='stylesheet' href='css/styles.css?v=1.0'>

</head>

20
Chapter 2 PHP Fundamentals

<body>
$content
</body>
</html>";

echo $html;
</code>

These are the basic elements needed for a HTML 5 webpage with PHP
included. You are declaring that you want errors to be turned on at the
top, as you have done before. The next lines set two variables, one for the
title and one for the content. The rest of the file sets the variable $html
to the entirety of HTML that you want displayed on the page. Within this
code you see the $title and $content variables placed where you want to
display them on the page. Go ahead and open your browser to this page to
see how it looks. This can get a little redundant if you have many pages that
follow the same look and feel presented with the HTML. Therefore, you
will use this page as a template that you can call and just switch out the
values you want displayed. Open up main2.php in your editor.

<code>
<?php
//error_reporting( E_ALL );
//ini_set( "display_errors",1);
$title = "Beginning PHP 8 & MySQL";
$content = "Here is the main content for this page";
$html =include_once "inc/template2.php";
</code>

Here you are introducing the include_once function. By calling


include_once, you tell PHP that you want to load a specific file into this
area. By separating out the design aspect (HTML) from the PHP, you can
view your code better and reuse the HTML elements in other PHP files.

21
Chapter 2 PHP Fundamentals

Building on this example, let’s take it a step further and include multiple
PHP files in your template. In main2.php, change template.php to
template2.php and refresh the page.
In your case, you first include header.php, located within the inc/
directory. When you use this method of including PHP snippets around
the HTML in your file, you are essentially creating a template. This
template (main.php), if used in another file, will still include a header,
contents, and footer. Let’s create a file called second.php by copying the
main.php file and naming it second.php.
Now that you have come to an understanding with your templates on
how to separate them and use them to your advantage, let’s take a look
at your variables. So far you have been using variables for trivial content,
colors, and item names. What if you want to store someone’s name and
address? It’s perfectly correct to do something like this:

<code>
$firstName = "gunnard";
$lastName = "engebreth";
</code>

This works fine until you want to start passing this information around
between functions in your program. Basically, envision passing your friend
a handful of Skittles vs. a bag of Skittles. Your friend still gets the Skittles in
the end, but one way is clean, optimized, and all Skittles are guaranteed to
reach your friend. This brings us to objects.

Objects
In PHP, an object is a specific set of data as defined in a class. In the code
example above, you would say that the information would belong to a class
of User. You would define that class as such:

<code>

22
Chapter 2 PHP Fundamentals

<?php
   class UserClass
      /* User variables */
      var $firstName;
      var $LastName;

      /* Member functions */


      function setFirstName($firstName){
         $this->firstName = $firstName;
      }

      function getFirstName(){
         echo $this->firstName;
      }

      function setLastName($lastName){
         $this->lastName = $lastName;
      }

      function getLastName(){
         echo $this->lastName;
      }
   }
  </code>

To create a new user you can call


<code>
$user = new UserClass();
$user->setFirstName('gunnard');
$user->setLastName('engebreth');
var_dump($user);
</code>

Let’s take a look at this code.

23
Chapter 2 PHP Fundamentals

$user = new UserClass(); does exactly what it shows: the variable


$user is now going to have the configuration and format that you
described in the class UserClass. This also demonstrates the importance
of proper naming in PHP. With one look at this line of code, you can have
a high percentage of certainty that this variable $user is most likely going
to be associated with $UserClass somehow and less likely to be associated
with a class named $DumpTruckClass.
The next two lines call a method (function) you create within
UserClass. These specific types of methods, Get____ and Set___, are
known as helpers and also commonly referred to as the class “getters” and
“setters.” These methods simplify the task of setting values within the object.
The last line is a PHP-specific function used heavily in debugging
code. var_dump() shows you exactly what is in a variable and what type
of variable you are analyzing. In your example, calling var_dump shows all
the information within the object. $user is the bag of Skittles and $user-
>firstName is the individual Skittle.
Now, how do you use this all together? You need to specify the class
information in one file and include it in another file. Thankfully, you
already know how to do that. Let’s open up main3.php.

<code>
<?php
$title = "main3 php file";
require "UserClass.php";
$user = new UserClass;
$user->setFirstName = 'gunnard';
$user->setLastName = 'engebreth';
var_dump($user);
error_reporting( E_ALL );
ini_set( "display_errors",1);
$html =include_once "inc/template2.php";
</code>

24
Chapter 2 PHP Fundamentals

You have already reviewed what the first two lines do, so set up and set
the variable $user as a part of the class UserClass. The next two lines set
the first name and last name. If you run this script on the command line or
browser, you can verify this through the var_dump() function. Figure 2-2
shows what you should see.

Figure 2-2. Code result web page

This is a fundamental stage in development. You have created an


object, assigned values, and can display the information on the page. Now
you need to make it dynamic by adding user interaction via forms.
Forms are more than just what you use to comment on someone’s
picture on Facebook. Forms are the method by which a user can interact
with a program. The user can directly communicate with the code and the
database you have created. With this kind of access, great detail must be
put into validation and sanitization of input, which we will get to later. For
now, just get comfortable with getting and using input. Let’s get technical
about receiving data from the user.

Verbs: GET and POST


HTTP (Hyper Text Transfer Protocol) is what connects the Web that
you know today. This is the protocol or method of agreed-upon
communication that allows for servers, PHP, and users to talk to one

25
Chapter 2 PHP Fundamentals

another. There are a lot of specifications within HTTP for everything


including error handling, expected standard document formats, and
request methods. These methods are defined in five verbs:

GET

The GET method requests a representation of the


specified resource. Requests using GET should only
retrieve data.

POST

The POST method is used to submit an entity to the


specified resource, often causing a change in state or
side effects on the server.

PUT

The PUT method replaces all current representations


of the target resource with the request payload.

DELETE

The DELETE method deletes the specified resource.

PATCH
The PATCH method is used to apply partial
modifications to a resource.

You will be focusing on GET and POST but rest assured, you will be using
the others as you build your REST API.
Point your browser to http://localhost:8000/chapter2/main4.
php?pants=123. Notice in the URL you have main4.php?pants=123. When
the page loads, it should look like Figure 2-3.

26
Chapter 2 PHP Fundamentals

Figure 2-3. URL result web page

At the top is var_dump() and you can see that the info you have in
the URL is now available to you in PHP as the variable $userVars. This is
available to you through the HTTP verb GET and in PHP you use the global
variable $_GET. GET specifically allows for the transfer of data through the
URL. You can send multiple values as well. Change the URL to include

<code>
http://localhost:8000/chapter2/main4.php?pants=123&dog=poodle&f
ood=spaghetti
</code>

Refresh the page and you will now see that Pants, Dog, and Food have
values set to them. The other method of transmitting data from the user to
your code is using POST.
The POST verb behaves in nearly the same way but does not use the
URL, thereby keeping the data you are transmitting a bit more secure. In
order to see the POST functionality, open main5.php and take a look.

<code>
<?php
$userVars = $_POST;
$title = "main5 php file";
require "UserClass.php";
$user = new UserClass;
$user->setFirstName = 'gunnard';
$user->setLastName = 'engebreth';
27
Chapter 2 PHP Fundamentals

var_dump($userVars);
error_reporting( E_ALL );
ini_set( "display_errors",1);
$html =include_once "inc/template3.php";

</code>

The main things that changed in this code are that you are using the
PHP global $_POST instead of $_GET and you include template3.php. Let’s
look at the tempalte3.php file.

<code>
$content = include('contentPost.php');
</code>

Template3 calls in a specific content piece called contentPost.php.

<code>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_
SELF"]);?>" method="post">
<input type="text" id="firstName" name="firstName" />
<input type="text" id="lastName" name="lastName" />
<input type="submit" name="submit">
</code>

Here you see the differences in that allow you to use $_POST. You
define a form and set the action to the file (main5.php) itself. This code
you see allows for the form to be used in multiple places by dynamically
finding the name of the file that houses the form and putting it there.
$_SERVER['PHP_SELF'] is the file currently calling this script and
htmlspecialchars is a PHP function that removes HTML because it can
be used for malicious or evil intent. The two lines underneath declare the
firstname and lastname boxes to collect the users input. Finally, you have
a Submit button that triggers the form to be used by your code. Go ahead
and fill it out and then look at the resulting page (Figure 2-4).

28
Chapter 2 PHP Fundamentals

Figure 2-4. Code result web page

You can see in your var_dump that the variables for first name and last
name came through, and if you look at your URL, you see that it is clean and
no variables are listed. In your examples, you used GET and POST to submit
data to your PHP. Technically, you could use GET to submit this form as well,
but you should really not do that. These two methods, GET and POST, are (as
listed above) part of a larger group of verbs that are used currently in modern
development in APIs. An application programming interface (API) is a method
of allowing access for developers to interact with an application. Think about
it this way: stock tickers, tweet streams, an Instagram plugin for WordPress--
these all are individual pieces of software that connect to other things:

• Stock ticker -> Bloomberg API

• Tweet stream -> Twitter API

• Instagram gallery -> Instagram API

The software will send specifically formatted (typically JSON or XML)


data to the API, which will authenticate the software’s access and return
the requested data. The software will then take that data, and read and
reformat it into a useable form. Referring back to the API verbs above, the
software will send a GET request to an API and expect back a response with
the requested data. This is the stock, Twitter, or Instagram information we
spoke about. Software can then POST data to the API in order to create or
start a process. A POST request is used to create a new Twitter account or
to actually make a trade with Bloomberg. PUT and PATCH can be used as

29
Chapter 2 PHP Fundamentals

“update” methods that can alter a users’ status or swap out profile pictures,
for example. DELETE is primarily used to remove or destroy data from the
API. While it is completely possible to only use GET and POST for an API,
the separation of verbs and (as you will see) routes based off of these verbs
will allow for a much easier and better experience for the developer using
the given API. If you are using POST to create, update, delete, and search,
this can get messy because you will need to not only look at whether the
request is GET/POST but now also a new variable needs to be set to specify
the intended action (create, update, delete, search, etc.). Clear and direct
methods of communication not only help humans communicate but can
keep things straightforward with software, too.

Summary
Let’s review the ideas you’ve learned so far.

1) Variables store information for PHP to use. This


information can be set within the code by the
developer or received from outside by the user.
Variables start with a $ and should be named
something relevant to their purpose.
2) PHP and HTML can be intermixed. It is acceptable
to use PHP within HTML through opening and
closing PHP with <?php and ?>. Keeping the code
clean and readable should be a priority.

3) echo prints out text or variables

4) Errors should be embraced as tools for debugging.


Errors can be turned on/off and configured through

a. error_reporting( E_ALL );

b. ini_set( "display_errors", 1);

30

You might also like