3811 Introduction To PHP

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder


Prerequisites[edit]

To get started with PHP on the  Coder Merlin™  server, you'll first need to make sure you have your www folder set up properly. This should be in your home directory. If it does not exist, you can create the folder by using the mkdir command:

mkdir ~/www

Once you have created the folder (or if it already exists), you'll need to set up the permissions for the folder. This isn't as hard as it sounds; simply run the following command:

chmod a+rx ~/www

If you ever encounter any "Access denied." error messages, run the following command, replacing file.php with the full path and filename (e.g., ~/www/index.php):

chmod a+rx file.php

Hello World[edit]

For the first example, we'll simply print "Hello, World!" in your browser. This helps test if everything is set up properly and is quite simple. Create a file called index.php in your www folder with the following contents:

<?php
echo 'Hello, World!';

Once you save the file, you can visit it using your own  Coder Merlin™  URL, which takes the form of https://codermerlin.com/users/your-username/filename

In this case, the filename is index.php because we placed the file directly in your www folder and not in a subfolder.

Troubleshooting[edit]

  • Access denied: make sure you have set the permissions properly (see the previous section)
  • Not found: be sure to double check your URL
  • 500 or server error: be sure to verify that you have copied the entire contents of the index.php file; even a single missing semicolon or opening PHP tag can cause this error

If the issue persists, follow the instructions in W1003_Help_Me!.

Background[edit]

PHP (w3 Schools)

Basics[edit]

Below are some of the more common features of the PHP language you're going to need for the next few missions.

Note: This guide assumes that you are already familiar with these topics, and it explains how they apply to PHP in particular. Each section starts with a link to learn more about the topic if available.

Opening and Closing Tags[edit]

Since PHP can be embedded into HTML, you'll need to let the parser know when your PHP starts and ends. To do this, you have to use the PHP opening tag when you start your PHP code and use the closing tag when you'd like to switch back to HTML. The "correct" version of the opening tag is <?php and the closing tag is ?>. You might also occasionally see the short opening tag: <?, but using the short opening tag is not recommended because it can cause compatibility issues, depending on your PHP server's settings.

Here's an example of embedding PHP in an HTML file:

<h1>Hello, <?php echo 'World';?>!</h1>

If you were to put this in your index.php file, you'd see "Hello, World!" displayed as a heading. If you look at the page source, you'll see the following HTML:

<h1>Hello, World!</h1>

This is because the PHP was processed on the server, and the resulting HTML is then sent to the browser. The PHP parser will only run the code between the opening and closing PHP tags, leaving the rest of the HTML alone.

PHP Only Files[edit]

If you're writing a file that is entirely PHP (e.g., a class), it is recommended to use the opening tag at the beginning of the file and to not use the closing PHP tag:

<?php
class MyClass {
...
}

Comments[edit]

In PHP, you can create both single-line comments and multi-line comments. To create a single-line comment, prepend two slashes ('//') to the beginning of the comment (comments don't have to be on their own line):

// Echo hello to the user
echo 'Hello'; // Done

If you'd like a comment that spans multiple lines, instead of beginning each line with '//', use multi-line comments, which start with '/*' and end with '*/':

/*
Everything in between
the start and end markers
is a comment
*/

The echo Function[edit]

The echo function (which is technically a language construct, not a function) is commonly used in PHP to echo data into the page. In the previous section, we used the echo function to print 'World', which is a simple string. However, the echo function can also be used to print more complex strings, including variables, function outputs, and more. Since echo is a language construct, you can use it without parenthesis:

echo 'string to print';

Variables[edit]

Unlike some other programming languages you might be familiar with, variables in PHP start with a dollar sign ('$'). To define a variable, you can use the assignment operator ('='):

$myVar = 'Hello, World!';

To use variables, you can use them the same way you would use literals:

$x = 5;
$y = 10;
$xy = $x * $y;


Concatenate Strings[edit]

To concatenate strings, use a period ('.') in between the strings:

$myVar = 'a' . 'b' . 'c';

Variables in Strings[edit]

To use variables in strings, you must use double quotes instead of single quotes. For example, the following will work as expected:

$x = 10;
echo "The value of x is $x";

Whereas the following literally prints "The value of x is $x":

$x = 10;
echo 'The value of x is $x';

If/Else/Else If[edit]

If, else, and else if work similarly to many other programming languages you might already be familiar with. Here is an example that uses all three:

$x = 10;
if ( $x == 10 ) {
    echo 'x is 10';
} else if ( $x == 15 ) {
    echo 'x is 15';
} else {
    echo 'x is not 10 or 15';
}

It is also worth noting that PHP also has the keyword elseif as one word, which is equivalent to else if (two words) when using curly brackets (which is probably the format you're more familiar with).

Double vs Triple Equal[edit]

PHP offers two comparison operators for equality: == and ===. Here, two equal signs check for equivalence regardless of type, and three equal signs check for equivalence of value and type. Here's an example to illustrate the differences:

$x = 10;
$y = '10';

$x == $y; // true
$x === $y; // false

Functions[edit]

W1205_Function_Introduction

To define a function, you start the line with the function keyword, followed by the function name and argument list:

function multiply( $x, $y ) {
    return $x * $y;
}

To return a value from the function, use the return keyword, followed by the value to return. In this example, the function accepts two parameters, then returns their product.

To call a function, you use the function's name followed by the arguments you'd like to pass:

multiply( 5, 8 );

Here's a more complete example that defines the function multiply, then echoes the product of two numbers:

function multiply( $x, $y ) {
    return $x * $y;
}

echo '5 * 8 = ' . multiply( 5, 8 );

Loops[edit]

For Loops[edit]

W1154_For_Loop

PHP for loops are similar to for loops in C, C++, Java, and many other languages you might be familiar with. To use a for loop in PHP, use the following syntax:

for ( $i = 0; $i < 100; $i++ ) {
...
}

The first section ($i = 0) is run once when the loop starts. The next section ($i < 100) is evaluated at the beginning of each iteration to determine whether to continue the loop. The last section ($i++) is run at the end of each iteration.

While Loops[edit]

W1152_While_Loop

While loops in PHP are similar to while loops in most other programming languages:

while ( condition ) {
...
}

Exercises[edit]

ExercisesExercisesIcon.png
  • Using HTML and PHP, demonstrate your ability to:
    • Create a Hello, World! program that displays a PHP-generated message on a page served from your www directory.
    • Create a page with the numbers 1 ... 1000 each displayed on a new line (Hint: '<br>' will add a new line in your browser)

References[edit]