Getting Started with PHP
echo is an example of a php command.
Client-Side vs Server-Side
The server receives the php code from the client side browser, runs the code, then generates html that it sends back to the browser.
php has a date command you can use to display the server time. Each time you refresh the page, the time will update. Note that if you view the source of the page, there’s no php code, only the html that the php generated.
Installing PHP
Since PHP is a server-side language, we need to have a server that can execute our PHP code before we can view it in a browser. Any computer can act as one. For mac, the easiest way is with a package called MAMP (Mac, Apache, MySQL, PHP). Apache is web server software commonly used to run PHP.
After installing, before you start servers, go to Preferences > Ports > Change the port for Apache to 80. Then, click start servers. localhost is a special address for your computer, it’s the root of your local web server. Under Applications > MAMP you’ll find the htdocs folder. Files in there will be available in your localhost web address. It’s worth adding this as a link in the finder siderbar by dragging it over. This is referred to as the htdocs directory.
When you go to localhost, you’ll see an index of the files you’ve placed there. Click on the on you’d like to view.
Your First PHP File
Now to start on the site. We’ll start by adding the basics. For the copyright year, we can use the echo and date commands to make sure it’s up to date.
Remember, the php gets executed on the server and then the server sends html to the browser, so when you inspect the source you’ll only see markup.
Creating the Menu and Footer
Starting the Project
If you upload an index.html file, localhost will open that by default, rather than listing out the things current in the htdocs directory. Note that if we try putting php in the index.html it won’t work. This is because it didn’t have the .php extension, so simply change that to fix it.
If you have an error, the page actually won’t load and will give you an error screen or white page. php is much less forgiving than html.
Including the Header
Let’s make a new page, contact.php. With static html we’d have to copy paste, but this isn’t effective if we need to change something, as we’d then need to change it across all pages manually. We’ll make a new file to contain the header. This is called an include file, as these are included in other files. It’s a good idea to put them in their own folder, usually called inc or includes. You can then call that file using the include command, which takes the file path. This makes it wayyyyy easier to maintain the update file.
Including the Footer and Adding Additional Pages
Let’s make an include file for the footer. We can now include the footer and header.php files in all new pages we make. It’s super easy to update the main nav links now, as we only need to do so in the header.php file, rather than in the html of each page.
Using Variables for the Title Tag
Note that variable names are case sensitive. We’ll change header.php so that it echos the $pageTitle variable, then declare that variable on each page prior to including the header.php file.
Adding Active States to the Navigation
Adding the on class to our nav links will underline them to let us know what page we’re on. Rather than adding the html for each one, we’ll use a variable.
Adding a Contact Form
Creating Input Fields
For the form element, set its method attribute to post. Then, give the inputs a name attribute so later the server will know which input they were. We’ll use a table here since out form inputs are tabular data.
Working with POST Variables
You can specify to what php file the form will send its data to using the action attribute for the form element. Here we make a file called contact-process.php for it to link to. When we submit the form, it just seems to take us to that page. When a php file receives form data, it will store it in a special $_POST variable. If we add this to our page with var_dump, it will display the data it received.
We can load these values into variables using the array’s keys. In this case the keys are the names we gave the inputs, so it looks like this is an associative array.
Working with Concatenation and Whitespace
You can concatenate in php with a period. You can concatenate strings, variables, or both. A line break can be added with \n, but this will only appear in the page source, not in the browser. For that, you’d need to add a <br> tag.
Though you wouldn’t normally do this, we can wrap our code in some pre tags to see the whitespace in the browser that it normally wouldn’t display. Now, we also want all this info in one variable, rather than having to echo out the three lines. To do that, make a new variable and set it to nothing. Then, we’ll add each line by setting it equal to itself, concatenated to the info at the end.
Redirecting After a Form Submission
Now, we can put the thank you page after someone submits the form in the contact-process.php page, but this can lead to some problems. If the person goes to another page after, but then uses the back button to go back it will ask them if they want to resubmit the form, which could send off another email.
The best way to do this is to have php first send the confirmation email, and then redirect you to the thank you page. We’ll make a new file for the thank you page called contact-thanks.php, and copy the thank you page code over. Then, in the contact-process.php file, we’ll do a redirect using the header command, which is part of HTTP that defines how the server and the browser communicate before any html gets passed. The field we want to define is Location, which tells it to go look for a different page. Now, when we submit the form it takes us to contact-thanks.php, and if we hit the back button, it takes us back to the form, rather than trying to resubmit the data.
Checking the Request Method
So we did this with three php files, but it’s a far more common practice to use just one with conditionals. First, we’ll set the action attribute in the form element to contact.php. This is the default behavior, it will be set to the page it’s on.
We can then copy the code from the contact-process file to the top of contact.php.
We can check the request method using the special php variable $_SERVER, which is an array with multiple elements in it. The one we want to check is REQUEST_METHOD. Also, it’s good practice to add the exit command after the header command. This will stop any other php code from running, and redirect to the thank you page.
Working With Get Variables
Now, we need the header to redirect to the thank you page, but we want that to be this contact.php page. To do that, add a ? at the en of its name, then any variable name, in this case we’ll use status, then an = sign and a value, in this case thanks.
We can then use the $_GET variable to check for the value for that variable. If it is set to thanks, we’ll display the thank you message, and if not, it will display the form. Now, you also need to use php’s isset function to check if the status variable exists.
Listing Inventory Items
Introducing Arrays
We could use variables to store the attributes of each shirt. We’ll need a lot for each one, its name, price, the sizes it’s available, etc. This would be a pain to manage, so we’ll use an array instead. An array is a variable that stores other variables. Each variable within it is known as an array element. Each element has an index that can be used to reference it.
To access the values in an array, put it’s name, then square brackets with the index you want.
php can retrieve the number of elements in an array using the count function, which takes the arrays name as its argument. The foreach command lets php execute a block of code for each element in the array. It takes the array name, then as, then a variable name that each element will be set to when it’s its turn.
Mingling PHP and HTML
php code gets processed by the server, html gets sent directly to the browser. Basically, you can mix and match php and html to get the result you want.
Creating the Products Array
We’ll start by writing an array for the shirts. Note that you can put each element on a different line to make things easier to read.
It’s good practice to write out the html you need, then work backwards for the php you need.
Here’s how you’d do that with a foreach loop. It’s good to write the array name as plural and the variable after as as the singular.
To add things to our array later, rather than having to go back and add it to the original array, simply write $arrayname[]= “new value”. The index assigned will be the next available one. It’s actually good practice to declare an empty array first, then each element with this method. Note that if you need to, you can specify a key inside the square brackets.
Introducing Associative Arrays
You can use strings of texts for your keys. Arrays that do this as known as associative arrays. Think of it as a two column spreadsheet.
Now, if you needed a lot of info on one country, you could write it like this:
But, you could also write it like this. => always has to do with key value pairs in arrays in php.
Nesting Arrays within Arrays
AKA a multidimensional array. Basically, you set the values of an array as arrays themselves.
To access the second level array, simply use another set of square brackets.
Here’s a more complex example involving a foreach loop.
Displaying all Products
Now back to the shirt page. We’ll make a multidimensional array for the shirt data.
Now to tweak the html/php to get the info to display.
Understanding Whitespace
It’s only showing three shirts per row instead of four. The reason for this is the whitespace between the list items in the page source.
To fix this, we’ll rewrite the code to have the html element be echoed out by php and concatenate them, which will leave no whitespace between them. We run into an issue though with echoing out a quotation mark for the href’s value.
To fix this, you can use an escape sequence via a backslash.
Or, you can surround the text using single quotes rather than double ones. This is usually the easier option.
For the image and alt parts of it, we’ll use a combination of single quotes and concatenation. Now, there are four rows, and if you look at the source there is no whitespace between the list items.