3811 Introduction To PHP

From Coder Merlin
(Redirected from 3811 php Hello World)
Jump to navigation Jump to search

Prerequisites[edit]

In order 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, then 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, then 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 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:

<?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-useraname/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.

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, please follow the instructions in W1003_Help_Me!

Background[edit]

PHP (w3 Schools)

Basics[edit]

Here 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.

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. 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 <?php and the closing tag is ?>. You may also occasionally see the short opening tag: <?, but using the short opening tag is not recommended as it may 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 in 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), then 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, 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):

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

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 '*/':

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

$myVar = 'Hello, World!';

In order 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, simply use a period ('.') in between the strings:

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

Variables In Strings[edit]

In order 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";

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

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

If/Else/Else If[edit]

If, ese, and else if work similarly to many other programming languages you may 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]

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:

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

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

Functions[edit]

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:

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

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 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 may 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 or not. 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]

ExercisesIcon.png
Exercises
  • 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 page with the numbers 1 ... 1000 each displayed on a new line (Hint: '<br>' will add a new line in your browser)

References[edit]


CoderMerlin™ proudly recommends:
HintIcon.png

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!


Designed with pride in Silicon Valley, CA, USA