Difference between revisions of "3811 Introduction To PHP"

From Coder Merlin
m (Editorial review and minor corrections)
 
Line 1: Line 1:
== Prerequisites ==
== Prerequisites ==
In order to get started with PHP on the {{CM}} 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, then you can create the folder by using the '''mkdir''' command:
To get started with PHP on the {{CM}} 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:


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 12: Line 12:
</syntaxhighlight>
</syntaxhighlight>


If you ever encounter any "Access denied." error messages, then run the following command, replacing file.php with the full path and filename (e.g. ~/www/index.php):
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):


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Line 19: Line 19:


== Hello World ==
== Hello World ==
For the first example, we'll simply print "Hello, World!" in your browser. This will help test if everything is set up properly, and is quite simple. Simply create a file called index.php in your www folder with the following contents:
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:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 26: Line 26:
</syntaxhighlight>
</syntaxhighlight>


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


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


=== Troubleshooting ===
=== Troubleshooting ===
Line 35: Line 35:
* '''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
* '''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, please follow the instructions in [[W1003_Help_Me!]]
If the issue persists, follow the instructions in [[W1003_Help_Me!]].


== Background ==
== Background ==
[https://www.w3schools.com/php/ PHP] (w3 Schools)
[https://www.w3schools.com/php/ PHP] (w3 Schools)
== Basics ==
== Basics ==
Here are some of the more common features of the PHP language you're going to need for the next few missions.
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 the following topics, and simply explains how they apply to PHP in particular. Each section will start with a link to learn more about the topic if available.  
'''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 ===
=== Opening and Closing Tags ===
Since PHP can be embedded into HTML, you'll need to let the parser know when your PHP starts and ends. In order 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 <syntaxhighlight lang="php" inline><?php</syntaxhighlight> and the closing tag is <syntaxhighlight lang="php" inline>?></syntaxhighlight>. You may also occasionally see the short opening tag: <syntaxhighlight lang="php" inline><?</syntaxhighlight>, but using the short opening tag is not recommended as it may cause compatibility issues depending on your PHP server's settings.
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 <syntaxhighlight lang="php" inline><?php</syntaxhighlight> and the closing tag is <syntaxhighlight lang="php" inline>?></syntaxhighlight>. You might also occasionally see the short opening tag: <syntaxhighlight lang="php" inline><?</syntaxhighlight>, 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:
Here's an example of embedding PHP in an HTML file:
Line 59: Line 59:
</syntaxhighlight>
</syntaxhighlight>


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 in between the opening and closing PHP tags, leaving the rest of the HTML alone.  
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 ====
==== PHP Only Files ====
If you're writing a file that is entirely PHP (e.g. a class), then it is recommended to use the opening tag at the beginning of the file, and to not use the closing PHP tag:
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:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 72: Line 72:


=== Comments ===
=== Comments ===
In PHP, there are both single line comments and multi-line comments. To create a single line comment, simply prepend two slashes ('//') to the beginning of your comment (comments don't have to be on their own line):
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):


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 79: Line 79:
</syntaxhighlight>
</syntaxhighlight>


If you'd like a comment that spans multiple lines, instead of beginning each line with '//', you can instead use multi-line comments, which start with '/*' and end with '*/':
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 '*/':


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 98: Line 98:
=== Variables ===
=== Variables ===


Unlike some other programming languages you may be familiar with, variables in PHP start with a dollar sign ('$'). In order to define a variable, you can use the assignment operator ('='):
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 ('='):


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 104: Line 104:
</syntaxhighlight>
</syntaxhighlight>


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


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 114: Line 114:


=== Concatenate Strings ===
=== Concatenate Strings ===
To concatenate strings, simply use a period ('.') in between the strings:
To concatenate strings, use a period ('.') in between the strings:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 120: Line 120:
</syntaxhighlight>
</syntaxhighlight>


=== Variables In Strings ===
=== Variables in Strings ===
In order to use variables in strings, you must use double quotes instead of single quotes. For example, the following will work as expected:
To use variables in strings, you must use double quotes instead of single quotes. For example, the following will work as expected:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 128: Line 128:
</syntaxhighlight>
</syntaxhighlight>


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


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 136: Line 136:


=== If/Else/Else If ===
=== If/Else/Else If ===
If, else, and else if work similarly to many other programming languages you may already be familiar with. Here is an example that uses all three:
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:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 151: Line 151:
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).
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 ====
==== Double vs Triple Equal ====
In PHP, there are two comparison operators for equality: '''==''' and '''==='''. Simply put, two equal signs checks for equivalence regardless of type, while three equal signs checks for equivalence of value ''and'' type. Here's an example to illustrate the differences:
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:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 165: Line 165:
[[W1205_Function_Introduction]]
[[W1205_Function_Introduction]]


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


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 173: Line 173:
</syntaxhighlight>
</syntaxhighlight>


In order to return a value from the function, you use the ''return'' keyword, followed by the value to return. In this example, the function accepts two parameters, then returns their product.
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:
To call a function, you use the function's name followed by the arguments you'd like to pass:
Line 196: Line 196:
[[W1154_For_Loop]]
[[W1154_For_Loop]]


PHP for loops are similar to for loops in C, C++, Java, and many other languages you may be familiar with. To use a for loop in PHP, use the following syntax:
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:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 204: Line 204:
</syntaxhighlight>
</syntaxhighlight>


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 or not. The last section (''$i++'') is run at the end of each iteration.
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 ====
==== While Loops ====
Line 220: Line 220:
{{Exercises|
{{Exercises|
* Using HTML and PHP, demonstrate your ability to:
* Using HTML and PHP, demonstrate your ability to:
** Create a Hello, World! program which displays a php-generated message on a page served from your www directory.
** 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: '&lt;br&gt;' will add a new line in your browser)
** Create a page with the numbers 1 ... 1000 each displayed on a new line (Hint: '&lt;br&gt;' will add a new line in your browser)
}}
}}

Latest revision as of 16:40, 7 September 2022

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]