Saturday, May 4, 2024
HomeWeb developmentIntroducing PHP: A Newbie's Information

Introducing PHP: A Newbie’s Information


The next article is an excerpt from PHP & MySQL: Novice to Ninja, seventh Version, a hands-on information to studying all of the instruments, rules, and methods wanted to construct knowledgeable internet software. On this second tutorial within the sequence, you’ll study the fundamentals of PHP, together with statements, variables, operators, feedback, and management buildings.



PHP & MySQL: Novice to Ninja


Now that you’ve your server up and operating, it’s time to put in writing your first PHP script. PHP is a server-side language. This idea could also be slightly tough to understand, particularly for those who’ve solely ever designed web sites utilizing client-side languages like HTML, CSS, and JavaScript.

A server-side language is just like JavaScript in that it means that you can embed dynamically generated content material into the HTML code of an online web page, providing you with larger management over what seems within the browser window than HTML alone can present. The important thing distinction between JavaScript and PHP is the stage at which the code is run.

Consumer-side languages like JavaScript are learn and executed by the net browser after downloading the net web page (embedded packages and all) from the net server. In distinction, server-side languages like PHP are run by the net server, earlier than the net web page is shipped to the browser. Whereas client-side languages provide you with management over how a web page behaves as soon as it’s displayed by the browser, server-side languages allow you to generate personalized pages on the fly earlier than they’re even despatched to the browser.

As soon as the net server has executed the PHP code embedded in an online web page, the end result takes the place of the PHP code within the web page. All of the browser sees is customary HTML code when it receives the web page. That’s why PHP known as a “server-side language”: its work is finished on the server.

Word: within the early days of the Net — and when the primary version of this ebook was revealed! — JavaScript was a client-side scripting language used primarily within the browser. Then alongside got here applied sciences like Ajax, which allowed JavaScript to speak with the server. And extra just lately nonetheless, JavaScript has been used each within the browser and on the server to create database-driven apps. Whereas these new makes use of for JavaScript supply thrilling prospects, there’s nonetheless very a lot a spot for PHP — as this ebook units out to display!

PHP code is written in PHP tags. Like most HTML tags, PHP has a begin tag and and finish tag: <?php and ?> respectively. Something inside these PHP tags is handled as PHP code and run on the server.

PHP code should be positioned in a file with a .php extension. When somebody connects to the server and asks it to load a file with a .php extension, the server then runs it as a PHP script. If you happen to put PHP tags in a file with a .html or any extension aside from .php, the net server gained’t run any PHP code, and the PHP code can be despatched on to the browser — which doesn’t perceive PHP code!

Let’s check out a PHP script.

Instance: PHP-RandomNumber

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Random Quantity</title>
  </head>
  <physique>
    <p>Producing a random quantity between 1 and 10:
      <?php
      echo rand(1, 10);
      ?>
    </p>
  </physique>
</html>

To run this code, reserve it as random.php within the public listing and navigate to https://v.je/random.php.

Most of that is plain HTML. Solely the road between <?php and ?> is PHP code. <?php marks the beginning of an embedded PHP script and ?> marks its finish. The online server is requested to interpret every thing between these two delimiters and convert it to common HTML code earlier than it sends the net web page to the requesting browser. If you happen to right-click inside your browser and select View Supply (the label could also be completely different relying on the browser you’re utilizing) you’ll be able to see that the browser is introduced with one thing like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Random Quantity</title>
  </head>
  <physique>
    <p>Producing a random quantity between 1 and 10:
      5
    </p>
  </physique>
</html>

There’s no HTML file on the server that accommodates this actual code. This HTML is generated dynamically on the server earlier than being despatched to the browser.

Strive operating the script a few instances and see how the quantity modifications. PHP code has been used to generate a random quantity, however all indicators of the PHP code have disappeared when viewing the supply within the browser. As a substitute, the output of the script has appeared, and it appears similar to customary HTML. This instance demonstrates a number of benefits of server-side scripting:

  • Safety. Within the instance above, we positioned a random quantity generated by the net server into the net web page. If we had inserted the quantity utilizing JavaScript, the quantity can be generated within the browser and somebody may doubtlessly amend the code to insert a particular quantity.
  • No browser compatibility points. PHP scripts are interpreted by the net server alone, so there’s no want to fret about whether or not the language options you’re utilizing are supported by the customer’s browser.
  • Entry to server-side assets. The code on the server can do something; it’s not restricted to the capabilities of the browser. The ensuing HTML could possibly be generated from a database or an Excel file, or it could possibly be the results of a calculation, reminiscent of the full of the person’s buying cart.
  • Diminished load on the shopper. JavaScript can delay the show of an online web page considerably (particularly on cellular units!), for the reason that browser should obtain after which run the script earlier than it might probably show the net web page. With server-side code, this burden is handed to the net server, which you may make as beefy as your software requires (and your pockets can afford).
  • Alternative. When writing code that’s run within the browser, the browser has to know how one can run the code given to it. All trendy browsers perceive HTML, CSS and JavaScript. To jot down some code that’s run within the browser, you will need to use considered one of these languages. By operating code on the server that generates HTML, you’ve gotten a alternative of many languages — considered one of which is PHP.

Primary Syntax and Statements

PHP syntax can be very acquainted to anybody with an understanding of JavaScript, C, C++, C#, Goal-C, Java, Perl, or another C-derived language. But when these languages are unfamiliar to you, or for those who’re new to programming normally, there’s no want to fret.

A PHP script consists of a sequence of instructions, or statements. Every assertion is an instruction that should be adopted by the net server earlier than it might probably proceed to the subsequent instruction. PHP statements, like these within the aforementioned languages, are at all times terminated by a semicolon (;).

It is a typical PHP assertion:

echo 'It is a <robust>check</robust>!';

That is an echo assertion, which is used to generate content material (normally HTML code) to ship to the browser. An echo assertion merely takes the textual content it’s given and inserts it into the web page’s HTML code on the place the place the PHP script was positioned.

On this case, we’ve provided a string of textual content to be output: It is a <robust>check</robust>!. Discover that the string of textual content accommodates HTML tags (<robust>and </robust>), which is completely acceptable.

So, if we take this assertion and put it into a whole internet web page, right here’s the ensuing code.

Instance: PHP-Echo

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Take a look at web page</title>
  </head>
  <physique>
    <p><?php echo 'It is a <robust>check</robust>!'; ?></p>
  </physique>
</html>

If you happen to place this file in your internet server after which request it utilizing an online browser, your browser will obtain this HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Take a look at web page</title>
  </head>
  <physique>
    <p>It is a <robust>check</robust>!</p>
  </physique>
</html>

The random.php instance we checked out earlier contained a barely extra complicated echo assertion:

echo rand(1, 10);

You’ll discover that, within the first instance, PHP is given some textual content to print immediately, and within the second, PHP is given an instruction to observe. PHP tries to learn something that exists exterior quotes as an instruction it should observe. Something inside quotes is handled as textual content — or, to make use of the technical time period, as a string. PHP doesn’t course of strings as instructions to observe. They’re handled as information within the software. You are able to do issues with them, reminiscent of sending them to the browser, however PHP doesn’t deal with one string in another way from one other.

So the next code will cross the string It is a <robust>check</robust>! on to the echo command:

echo 'It is a <robust>check</robust>!';

A string is signified utilizing a begin quote and an finish quote. PHP will see the primary ' as the beginning of the string and discover the subsequent ' and use that as the top of the string.

Something exterior of quotes is handled as a sequence of instructions to run. The next is just not legitimate code:

echo It is a <robust>check</robust>!;

As a result of the quotes have been eliminated, PHP will first attempt to run the command This, then the command is, adopted by the command a, and so forth. As none of those are legitimate instructions in PHP, the above code would produce an error message. If you wish to deal with one thing as textual content, bear in mind to place quotes round it!

In distinction, the next code will run a sound command — the built-in “operate” rand — to generate a random quantity after which cross the end result to the echo command:

echo rand(1, 10);

A operate is a particular kind of command that performs a particular job. Behind the scenes, PHP will do some processing after which generate a end result. On this case, the rand operate will produce a random quantity, however completely different capabilities carry out completely different duties.

You’ll be able to rapidly determine if one thing is a operate as a result of it’s adopted by parentheses. PHP has many built-in capabilities that allow you to do all kinds of issues, reminiscent of sending e mail and dealing with info saved in varied sorts of databases.

PHP gained’t attempt to run something that’s inside a string. The next code gained’t course of the rand operate:

echo 'rand(1, 10)';

PHP will see 'rand(1, 10)' as a string, and can ship the textual content rand(1, 10) to the browser, which most likely isn’t what you’d need to do. It’s necessary to know the distinction between a string and code. PHP will see any textual content exterior quotes as a sequence of instructions it ought to observe. Something inside quotes is a string and is information that PHP will work with.

PHP doesn’t attempt to perceive strings. They will comprise any characters in any order. However code (something not inside quotes) — which is actually a sequence of directions — should observe a inflexible construction for a pc to know it.

Word: utilizing a code editor with syntax highlighting makes it simple to rapidly see if one thing is a string or code. Strings can be a special shade from code that must be processed.

The picture under reveals easy code highlighting within the Visible Studio Code editor.

An example of code highlighting in VS Code

PHP helps each single quotes (') and double quotes (") to encase strings. For many functions, they’re interchangeable. PHP builders are inclined to favor single quotes, as a result of we take care of HTML code loads, which tends to comprise loads of double quotes. For instance:

echo '<a href="http://www.sitepoint.com">Click on right here</a>';

If double quotes have been used at every finish right here, we’d want to inform PHP that the quote after href= is just not the top of the string by putting a earlier than it (often called an escape character) and do the identical with any double quotes we really wished to ship to the browser as a part of the HTML:

echo "<a href="http://www.sitepoint.com">Click on right here</a>";

For that reason, PHP builders use single quotes, though there are some variations between single and double quotes. For our functions right here, although, they’re successfully interchangeable.

A operate might be considered a miniature program inside your program. You’ll be able to instruct PHP to run the operate through the use of its identify (reminiscent of rand in our instance earlier) adopted by parentheses. The instruction rand(1, 10) tells PHP to run the operate with the identify rand. Operating a operate can also be extra generally known as calling a operate.

Most capabilities in PHP return a worth after they’re referred to as. As soon as the worth is returned, PHP behaves as for those who’d really simply typed that returned worth in your code as a substitute. Within the echo rand(1, 10); instance, our echo assertion accommodates a name to the rand operate, which returns a random quantity as a string of textual content. The echo assertion then outputs the worth that was returned by the operate name.

Each operate in PHP can have a number of arguments that will let you make the operate behave in a barely completely different manner. The rand operate takes two arguments: a minimal and most random quantity. By altering the values which are handed to the operate, you’re in a position to change the best way it really works. For instance, for those who wished a random quantity between 1 and 50, you possibly can use this code:

echo rand(1, 50);

We encompass the arguments with parentheses ((1, 50)) for 2 causes. First, they point out that rand is a operate that you simply need to name. Second, they mark the start and finish of an inventory of arguments — PHP statements that you simply want to present — in an effort to inform the operate what you need it to do. Within the case of the rand operate, you’ll want to present a minimal and a most worth. These values are separated by a comma.

In a while, we’ll have a look at capabilities that take completely different sorts of arguments. We’ll additionally contemplate capabilities that take no arguments in any respect. These capabilities will nonetheless want the parentheses, regardless that nothing can be typed between them.

Variables

Variables in PHP are equivalent to variables in most different programming languages. For the uninitiated, a variable might be considered a reputation given to an imaginary field into which any worth could also be positioned. The next assertion creates a variable referred to as $testVariable (all variable names in PHP start with a greenback signal) and assigns it a worth of 3:

$testVariable = 3;

PHP is a loosely typed language. Which means that a single variable might comprise any kind of knowledge — be it a quantity, a string of textual content, or another type of worth — and will retailer several types of values over its lifetime. If you happen to have been to kind the next assertion after the assertion proven above, it will assign a brand new worth to the prevailing $testVariable. Whereas the $testVariable variable used to comprise a quantity, it will now comprise a string of textual content:

$testVariable="Three";

After you have information saved in a variable, you’ll be able to ship it to the browser utilizing the echo command from earlier:

$testVariable = 3;
echo $testVariable;

When this code runs, the digit “3” can be despatched to the browser to be displayed on the web page.

Along with particular strings or numbers, it’s potential to retailer the results of a operate after which use it afterward within the script:

$randomNumber = rand(1, 10);
echo $randomNumber;

Operators

The equals signal we used within the final two statements known as the project operator, because it’s used to assign values to variables. (There’s a special technique to really point out “equals” in PHP, as we’ll see under.) Different operators could also be used to carry out varied mathematical operations on values:

$testVariable = 1 + 1;  // assigns a worth of two
$testVariable = 1 - 1;  // assigns a worth of 0
$testVariable = 2 * 2;  // assigns a worth of 4
$testVariable = 2 / 2;  // assigns a worth of 1

From these examples, you’ll be able to most likely inform that + is the addition operator, - is the subtraction operator, * is the multiplication operator and / is the division operator. These are all referred to as arithmetic operators, as a result of they carry out arithmetic on numbers.

Word: every of the arithmetic traces above ends with a “remark” after the semicolon. Feedback allow you to explain what your code is doing. They insert explanatory textual content into your code — textual content that the PHP interpreter will ignore.

Single-line feedback start with //. A single-line remark might be by itself line or, as within the instance above, it may be positioned on the finish of a line of code.

If you would like a remark to span a number of traces, begin it with /*, and finish it with */. The PHP interpreter will ignore every thing between these two delimiters. I’ll be utilizing feedback all through the remainder of this ebook to assist clarify a few of the code I current.

One operator that sticks strings of textual content collectively known as the string concatenation operator:

$testVariable="Hello " . 'there!';  // Assigns a worth of 'Hello there!'

Variables could also be used nearly anyplace you utilize a worth. Take into account this sequence of statements:

$var1 = 'PHP';          // assigns a worth of 'PHP' to $var1
$var2 = 5;              // assigns a worth of 5 to $var2
$var3 = $var2 + 1;      // assigns a worth of 6 to $var3
$var2 = $var1;          // assigns a worth of 'PHP' to $var2
$var4 = rand(1, 12);    // assigns a worth to $var4 utilizing the rand() operate
echo $var1;             // outputs 'PHP'
echo $var2;             // outputs 'PHP'
echo $var3;             // outputs '6'
echo $var4;             // outputs the random quantity generated above
echo $var1 . ' guidelines!'; // outputs 'PHP guidelines!'
echo '$var1 guidelines!';    // outputs '$var1 guidelines!'
echo "$var1 guidelines!"     // outputs 'PHP guidelines!'

Word the final two traces specifically. If you happen to place a variable inside single quotes, it should print the identify quite than the contents of the variable. In distinction, when utilizing double quotes, the variable within the string is changed with the variable’s contents.

Putting variables inside double quotes works in easy conditions, however for many of this ebook it gained’t be usable, as we gained’t be utilizing such easy code. So it’s a good suggestion to get used to the apply of concatenation (proven within the third-from-last line: echo $var1 . ' guidelines!';).

Management Constructions

The examples of PHP code we’ve seen to this point have been both one-statement scripts that output a string of textual content to the net web page, or a sequence of statements that have been to be executed one after the opposite so as. If you happen to’ve ever written packages in different languages (reminiscent of JavaScript, Goal-C, Ruby, or Python), you already know that sensible packages are not often so easy.

PHP, similar to another programming language, offers services that allow you to have an effect on the move of management. That’s, the language accommodates particular statements that you should utilize to deviate from the one-after-another execution order that has dominated our examples to this point. Such statements are referred to as management buildings. Don’t perceive? Don’t fear! A number of examples will illustrate it completely.

If Statements

Essentially the most primary, and most frequently used, management construction is the if assertion. The move of a program by an if assertion might be visualized as proven under.

The logical flow of an if statement

Right here’s what an if assertion appears like in PHP code:

if (situation) {
  ⋮ conditional code to be executed if situation is true
}

This management construction lets us inform PHP to execute a set of statements provided that some situation is met.

For instance, we would need to create a recreation that mimics a cube roll and by which you need to roll a six to win. The cube roll might be modeled utilizing the rand() operate we used earlier, setting the minimal and most from 1 to six:

$roll = rand(1, 6);

echo 'You rolled a ' . $roll;

To print out a message if the participant rolls a six and wins, you should utilize an if assertion.

Instance: PHP-DiceRoll

$roll = rand(1, 6);

echo 'You rolled a ' . $roll;

if ($roll == 6) {
  echo 'You win!';
}

The == used within the situation above is the equals operator, which is used to check two values to see whether or not they’re equal. That is fairly completely different from utilizing a single =, which is used for project, and might’t be used for comparability.

The if assertion makes use of braces ({ and }) to encompass the code you need to run solely when the situation is met. You’ll be able to place as many traces of code as you want between the braces; the code will solely be run when the situation is met. Any code positioned after the closing brace (}) can be run on a regular basis:

$roll = rand(1, 6);

echo 'You rolled a ' . $roll;

if ($roll == 6) {
  echo 'You win!'; // This line will solely be printed for those who roll a 6
}

echo 'Thanks for taking part in'; // This line will at all times be printed

Word: bear in mind to kind the double-equals (==). A typical mistake amongst newbie PHP programmers is to kind a situation like this with a single equals signal:

if ($roll = 6)     

This situation is utilizing the project operator (=) as a substitute of the equals operator (==). Consequently, as a substitute of evaluating the worth of $roll to the quantity 6, it should really set the worth of $roll to 6. Oops!

To make issues worse, the if assertion will use this project operation as a situation, which it should contemplate to be true, so the conditional code inside the if assertion will at all times be executed, no matter what the unique worth of $roll occurred to be.

If you happen to save this as diceroll.php and run the code, you’ll see the random quantity being generated. If you happen to run it till you win, you’ll see this within the browser:

You rolled a 6You win!Thanks for taking part in

This isn’t very fairly. However as a result of PHP outputs HTML, you’ll be able to add some paragraph tags in an effort to format the output.

Instance: PHP-DiceRoll-Formatted

$roll = rand(1, 6);

echo '<p>You rolled a ' . $roll . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}

echo '<p>Thanks for taking part in</p>';

If you happen to run the up to date code, you’ll see that it now prints this within the browser:

You rolled a 6

You win!

Thanks for taking part in

That is way more person pleasant. To make the sport itself extra person pleasant, you may need to show a special message to individuals who didn’t roll a 6 and didn’t win. This may be carried out with an else assertion. The else assertion should observe an if, and can be run if the situation isn’t met.

Instance: PHP-DiceRoll-Else

$roll = rand(1, 6);

echo '<p>You rolled a ' . $roll . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

echo '<p>Thanks for taking part in</p>';

Word: as a result of the phrase did not accommodates a single quote, it must be “escaped”. By previous the one quote with a backslash (), it tells PHP to not deal with the ' in did not as the top of the string.

With an else assertion, one (and just one!) of the 2 blocks of code is assured to run. Both the code within the if block will run if the situation is met, or the code within the else block will run if it isn’t.

Circumstances might be extra complicated than a single test for equality. An if assertion can comprise a couple of situation. For instance, think about if the sport have been adjusted in order that each 5 and 6 have been profitable numbers. The if assertion could possibly be modified to the next.

Instance: PHP-DiceRoll-Or

if ($roll == 6 || $roll == 5) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

The double pipe operator (||) means “or”. The situation above is now met if both situation is met. This may be learn as “If you happen to roll a 6 otherwise you roll a 5”.

Nonetheless, this may be expressed in a good higher manner. if statements aren’t restricted to utilizing the equals (==) operator. They will additionally make the most of the mathematical larger than (>) and fewer than (<) operators. The if assertion above may be carried out with a single expression.

Instance: PHP-DiceRoll-Larger

if ($roll > 4) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

The situation $roll > 4 can be met if the worth saved within the $roll variable is larger than 4, permitting us to have 5 and 6 as profitable numbers with a single situation. If we wished 4, 5 and 6 as profitable numbers, the situation could possibly be modified to $roll > 3.

Just like the “or” expression (||), there’s an “and” expression that’s solely met when each circumstances are met. We may develop the sport to incorporate two cube and require gamers to roll two sixes to win.

Instance: PHP-DiceRoll-TwoDice

$roll1 = rand(1, 6);
$roll2 = rand(1, 6);

echo '<p>You rolled a ' . $roll1 . ' and a ' . $roll2 . '</p>';

if ($roll1 == 6 && $roll2 == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

echo '<p>Thanks for taking part in</p>';

The situation $roll1 == 6 && $roll2 == 6 will solely be met if $roll1 == 6 is true and $roll2 == 6. Which means that the participant has to roll a 6 on each cube to win the sport. If we modified the and (&&) to an or (||) — that’s, if ($roll1 == 6 || $roll2 == 6) — the participant would win in the event that they rolled a 6 on both cube.

We’ll have a look at extra sophisticated circumstances as the necessity arises. In the interim, a normal familiarity with if … else statements is ample.

Word: PHP additionally permits using or instead of || and and instead of &&. For instance:

if ($roll == 6 or $roll == 5) {}

There are some minor variations between the best way or and || work that may result in surprising habits. Usually talking, keep away from the “spelled out” operators. Sticking to the double pipe (||) and double ampersand (&&) will assist forestall a lot of complicated bugs.

Loops

One other kind of management construction that’s very helpful is a “loop”. Loops will let you repeat the identical traces of code time and again. Two necessary type of loops are for loops and whereas loops. Let’s have a look at how they work.

For Loops

The for loop is used when you understand up entrance what number of instances you’ll want to run the identical code. The picture under reveals the move of a for loop.

The logical flow of a for loop

Right here’s what it appears like in code:

for (declare counter; situation; increment counter) {
  ⋮ assertion(s) to execute repeatedly so long as situation is true
}

The declare counter assertion is executed as soon as at the beginning of the loop. The situation assertion is checked every time by the loop earlier than the statements within the physique are executed. The increment counter assertion is executed every time by the loop after the statements within the physique.

To rely to 10 utilizing a for loop, you should utilize the next code:

for ($rely = 1; $rely <= 10; $rely++) {
  echo $rely . ' ';
}

This appears fairly scary, as there’s loads occurring, however let me break it down for you:

  • $rely = 1;. You’re already accustomed to this code. It’s making a variable referred to as $rely and setting the worth to 1.
  • $rely <= 10;. That is the situation. It may be learn as “maintain looping whereas $rely is lower than or equal to 10”.
  • $rely++. This says “add 1 to the counter every time”. It’s equivalent to $rely = $rely + 1.
  • echo $rely . ' ';. This prints the worth of the counter adopted by an area.

The situation on this instance makes use of the <= operator. This acts equally to the lower than operator (<), however evaluates to true if the quantity being in contrast is lower than or equal to the second. Different obtainable operators embody >= (larger than or equal) and != (not equal).

All three components of the for loop are mixed to supply the entire loop. Though, at first look, the code appears slightly harder to learn, placing all of the code that offers with controlling the loop in the identical place really makes it simpler to know when you’re used to the syntax. Most of the examples on this ebook will use for loops, so that you’ll have loads of alternatives to apply studying them.

You’ll be able to change every a part of the for loop to have completely different outcomes. For instance, let’s have a look at how one can add 3 every time you’ll be able to change the for loop by amending the final half.

The ultimate a part of the loop, $rely++, says add 1 to the worth of $rely, and it’s a brief manner of writing $rely = $rely + 1.

By altering $rely++ to $rely = $rely + 3, the for loop can be utilized to rely in threes.

Instance: PHP-For

for ($rely = 1; $rely <= 10; $rely = $rely + 3) {
  echo $rely . ' ';
}

This may end result within the following:

1 4 7 10

for loops might be mixed with different statements — reminiscent of if statements — to carry out particular duties on every iteration. For instance, quite than refreshing the web page on our cube recreation every time, we would need to roll the cube ten instances and print the outcomes.

Instance: PHP-DiceRoll-ManyDice

for ($rely = 1; $rely <= 10; $rely++) {
  $roll = rand(1, 6);
  echo '<p>You rolled a ' . $roll . '</p>';

  if ($roll == 6) {
    echo '<p>You win!</p>';
  }
  else {
    echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
  }
}

echo '<p>Thanks for taking part in</p>';

This lets us roll the cube ten instances with no need to refresh the web page every time. Utilizing a loop is functionally equivalent to copying and pasting the code ten instances, and can produce the very same end result as the next:

$roll = rand(1, 6);
echo '<p>You rolled a ' . $roll . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

$roll = rand(1, 6);
echo '<p>You rolled a ' . $roll . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

$roll = rand(1, 6);
echo '<p>You rolled a ' . $roll . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}

// and so forth …

The pc doesn’t care which methodology you utilize: you’ll be able to copy/paste or use a loop. It should simply run the code. Nonetheless, as a developer, you’ll rapidly understand {that a} loop is the higher alternative. If you happen to wished to replace the code to additionally enable 5 as a profitable quantity, you’d must replace the situation in ten completely different locations. Utilizing a loop, you’ll be able to change the code in a single place and it’ll have an effect on every iteration of the loop. If you happen to ever end up copy/pasting code, there’s at all times a greater manner of reaching what you’re making an attempt to do.

Word: given your new data of loops, it is best to have the ability to begin coding for your self. Are you able to full these challenges?

  • Problem 1: print all of the odd numbers from 21 to 99.
  • Problem 2: print the 9 instances desk as much as 12 x 9 (9 18 27 … and so forth.) with out utilizing the multiplication operator (*) or an if assertion.
  • Problem 3: print the 9 instances desk on this format:
    1x9 = 9
    2x9 = 18
    … and so forth.

    This time, you’ll want to make use of the multiplication operator!

Whereas Loops

One other often-used PHP management construction is the whereas loop. The place the if … else assertion permits us to decide on whether or not or to not execute a set of statements relying on some situation, the whereas loop permits us to make use of a situation to find out what number of instances we’ll execute a set of statements repeatedly.

The next picture reveals how a whereas loop operates.

The logical flow of a while loop

Right here’s what a whereas loop appears like in code:

whereas (situation) {
  ⋮ assertion(s) to execute repeatedly so long as situation is true
}

The whereas loop works very equally to an if assertion. The distinction arises when the situation is true and the assertion(s) are executed. As a substitute of constant the execution with the assertion that follows the closing brace (}), the situation is checked once more. If the situation continues to be true, the assertion(s) are executed a second time, and a 3rd, and can proceed to be executed so long as the situation stays true. The primary time the situation evaluates false (whether or not it’s the primary time it’s checked, or the hundredth), the execution jumps instantly to the assertion that follows the whereas loop, after the closing brace.

You should use a whereas loop to create a counter that has the same end result to a for loop.

Instance: PHP-WhileCount

$rely = 1;
whereas ($rely <= 10) {
  echo $rely . ' ';
  ++$rely;
}

This works in precisely the identical manner as a for loop, and also you’ll discover loads of the identical statements in other places. This code might look a bit horrifying, I do know, however let me speak you thru it line by line:

  • $rely = 1;. The primary line creates a variable referred to as $rely and assigns it a worth of 1.
  • whereas ($rely <= 10). The second line is the beginning of a whereas loop, the situation being that the worth of $rely is lower than or equal (<=) to 10.
  • {. The opening brace marks the start of the block of conditional code for the whereas loop. This conditional code is usually referred to as the physique of the loop, and is executed time and again, so long as the situation holds true.
  • echo $rely . ' ';. This line merely outputs the worth of $rely, adopted by an area.
  • ++$rely;. The fourth line provides 1 to the worth of $rely. ++$rely is a shortcut for $rely = $rely + 1. $rely++ may even work right here! The place of the ++ might be necessary, however on this case it doesn’t matter. If the ++ is earlier than the variable identify, the counter is incremented earlier than the worth is learn. When $rely is zero, the code echo ++$rely; will print 1, whereas echo $rely++; will print 0. Watch out when utilizing ++, as placing it within the unsuitable place may cause bugs.
  • }. The closing brace marks the top of the whereas loop’s physique.

So right here’s what occurs when this code is executed. The primary time the situation is checked, the worth of $rely is 1, so the situation is unquestionably true. The worth of $rely (1) is output, and $rely is given a brand new worth of 2. The situation continues to be true the second time it’s checked, so the worth (2) is output and a brand new worth (3) is assigned. This course of continues, outputting the values 3, 4, 5, 6, 7, 8, 9, and 10. Lastly, $rely is given a worth of 11, and the situation is discovered to be false, which ends the loop.

The web results of the code is proven within the following picture.

The net result of the while loop code

Whereas loops aren’t usually used for easy counters like this; it’s usually the job of the for loop. Though you’ll be able to create a counter with a whereas loop, normally they’re used to maintain operating code till one thing occurs. For instance, we would need to maintain rolling the cube till we get a 6. There’s no technique to know what number of cube rolls can be wanted after we write the code: it may take one roll or a whole lot to get a six. So you’ll be able to place the cube roll in a whereas loop.

Instance: PHP-DiceRoll-Whereas

$roll = 0;
whereas ($roll != 6) {
  $roll = rand(1, 6);
  echo '<p>You rolled a ' . $roll . '</p>';

  if ($roll == 6) {
    echo '<p>You win!</p>';
  }
  else {
    echo '<p>Sorry, you did not win, higher luck subsequent time!</p>';
  }
}

This may maintain rolling the cube till a 6 is rolled. Every time you run the code, it should take a special variety of rolls earlier than you win.

The whereas assertion makes use of the situation $roll != 6. To ensure that the whereas loop to be run the primary time, the $roll variable should be set to a worth for the preliminary comparability. That’s the aim of the $roll = 0; line above the whereas loop. By setting the worth to zero initially, when the whereas loop runs the primary time, the situation $roll != 6 is met, as a result of $roll is the same as zero, not 6, and the loop will begin. If the $roll variable isn’t created previous to beginning the loop, you’ll get an error, as a result of the $roll variable hasn’t been set to something earlier than it’s used.

There’s a variant of the whereas loop referred to as do … whereas, which is beneficial in these sorts of circumstances. It means that you can run some code with out a situation after which run it once more if the code isn’t set. This takes the next construction:

do {
 assertion(s) to execute after which repeat if the situation is true
}
whereas (situation);

For the dice-roll instance above, this lets you ignore the primary line.

Instance: PHP-DiceRoll-DoWhile

do {
  $roll = rand(1, 6);
  echo '<p>You rolled a ' . $roll . '</p>';

  if ($roll == 6) {
    echo '<p>You win!</p>';
  }
  else {
    echo '<p>Sorry, you did not win, higher luck subsequent time!</p>';
  }
}
whereas ($roll != 6);

This time, as a result of the situation is on the backside, by the point the whereas assertion is run, the $roll variable has been given a worth, so that you don’t want to offer it an preliminary worth of zero to drive the loop to run the primary time.

Word: PHP doesn’t thoughts the way you format your code, and whitespace is ignored. You possibly can write the earlier instance like this:

do {
  $roll = rand(
  1,
  6);

  echo '<p>You rolled a ' . $roll . '</p>';

  if (
      $roll == 6
  ) 
  {
    echo '<p>You win!</p>';
  }
  else
  {
    echo '<p>Sorry, you did not win, higher luck subsequent time!</p>';
  }
}
whereas ($roll != 6);

The script will execute in the very same manner. Completely different programmers have completely different most popular types, reminiscent of utilizing tabs or areas for indentation, or putting the opening brace on the identical line because the assertion or after it. There are even coding fashion guides that dictate the place braces and brackets must be positioned and the way code must be formatted. However the pc doesn’t care whether or not a brace is on the identical line or the subsequent line, so use no matter fashion you are feeling most comfy with.

Arrays

An array is a particular type of variable that accommodates a number of values. If you happen to consider a variable as a field that accommodates a worth, an array might be considered a field with compartments the place every compartment is ready to retailer a person worth.

To create an array in PHP, use sq. brackets ([ and ]) containing the values you need to retailer, separated by commas:

$myArray = ['one', 2, '3'];

Word: arrays in PHP will also be outlined utilizing the array key phrase. The next code is equal to the sq. bracket notation above:

$myArray = array('one', 2, 3);

The sq. bracket notation was launched in PHP 5.4 and is most popular by PHP builders, because it’s much less to kind, and sq. brackets are extra simply seen amongst spherical brackets in management buildings like if statements and whereas loops.

This code creates an array referred to as $myArray that accommodates three values: 'one', 2, and '3'. Similar to an unusual variable, every area in an array can comprise any kind of worth. On this case, the primary and third areas comprise strings, whereas the second accommodates a quantity.

To entry a worth saved in an array, you’ll want to know its index. Sometimes, arrays use numbers as indices to level to the values they comprise, beginning with zero. That’s, the primary worth (or component) of an array has index 0, the second has index 1, the third has index 2, and so forth. Subsequently, the index of the nth component of an array is n–1. As soon as you understand the index of the worth you’re interested by, you’ll be able to retrieve that worth by putting that index in sq. brackets after the array variable identify:

echo $myArray[0];    // outputs 'one'
echo $myArray[1];    // outputs '2'
echo $myArray[2];    // outputs '3'

Every worth saved in an array known as an component. You should use a key in sq. brackets so as to add new parts, or assign new values to current array parts:

$myArray[1] = 'two';     // assign a brand new worth
$myArray[3] = '4';    // create a brand new component

You can even add parts to the top of an array utilizing the project operator as ordinary, however leaving empty the sq. brackets that observe the variable identify:

$myArray[] = '5';
echo $myArray[4];    // outputs '5'

Array parts can be utilized like another variable, and in loads of circumstances selecting to make use of an array or a number of variables will rely upon the programmer’s choice. Nonetheless, arrays can be utilized to unravel issues that ordinary variables can’t!

Bear in mind the cube recreation from the final part? It will be extra user-friendly if it confirmed the English phrase quite than the numeral for the end result. For instance, as a substitute of “You rolled a 3” or “You rolled a 6”, it may be nicer to learn “You rolled a 3” or “You rolled a six”.

To do that, we want a way of changing from a numeral to the English phrase for that quantity. That is potential with a sequence of if statements.

Instance: PHP-DiceRoll-English-If

$roll = rand(1, 6);

if ($roll == 1) {
  $english="one";
}
else if ($roll == 2) {
  $english="two";
}
else if ($roll == 3) {
  $english="three";
}
else if ($roll == 4) {
  $english="4";
}
else if ($roll == 5) {
  $english="5";
}
else if ($roll == 6) {
  $english="six";
}

echo '<p>You rolled a ' . $english . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win. Higher luck subsequent time!</p>';
}*

This resolution works, however it’s very inefficient, as you’ll want to write an if assertion for every potential cube roll. As a substitute, you should utilize an array to retailer every roll worth:

$english = [
  1 => 'one',
  2 => 'two',
  3 => 'three',
  4 => 'four',
  5 => 'five',
  6 => 'six'
];

The => notation (often called a double arrow operator) means that you can outline each the keys and the values when creating the array. That is equal to the next:

$english = [];
$english[1] = 'one';
$english[2] = 'two';
$english[3] = 'three';
$english[4] = '4';
$english[5] = '5';
$english[6] = 'six';

Though these are equal, the code required to make use of the shorthand notation is loads faster to kind, and is arguably simpler to learn and simpler to know.

Now that the array is created, it’s potential to learn every English phrase from it:

echo $english[3];    // Prints "three"
echo $english[5];    // Prints "5"

In PHP, a quantity like 3 might be changed with a variable that accommodates that worth. That is additionally potential with array keys. For instance:

$var1 = 3;
$var2 = 5;

echo $english[$var1];    // Prints "three"
echo $english[$var2];    // Prints "5"

Figuring out this, we are able to piece all of it collectively and modify the cube recreation to show the English phrase of the cube roll by studying the related worth from the array utilizing the $roll variable.

Instance: PHP-DiceRoll-English-Array

$english = [
  1 => 'one',
  2 => 'two',
  3 => 'three',
  4 => 'four',
  5 => 'five',
  6 => 'six'
];

$roll = rand(1, 6);

echo '<p>You rolled a ' . $english[$roll] . '</p>';

if ($roll == 6) {
  echo '<p>You win!</p>';
}
else {
  echo '<p>Sorry, you did not win, higher luck subsequent time!</p>';
}

As you’ll be able to see, this can be a lot cleaner and tidier than an extended listing of if statements. There are two large benefits right here.

Firstly, for those who wished to signify a ten-sided cube, it’s loads simpler so as to add to the array than add an additional if assertion for every quantity.

Secondly, the array is reusable. For the model with two cube, you’ll be able to simply reuse the $english array quite than repeating all of the if statements for every cube roll.

Instance: PHP-DiceRoll-English-If-TwoDice

$roll1 = rand(1, 6);
$roll2 = rand(1, 6);

if ($roll1 == 1) {
  $english="one";
}
else if ($roll1 == 2) {
  $english="two";
}
else if ($roll1 == 3) {
  $english="three";
}
else if ($roll1 == 4) {
  $english="4";
}
else if ($roll1 == 5) {
  $english="5";
}
else if ($roll1 == 6) {
  $english="six";
}

if ($roll2 == 1) {
  $englishRoll2 = 'one';
}
else if ($roll2 == 2) {
  $englishRoll2 = 'two';
}
else if ($roll2 == 3) {
  $englishRoll2 = 'three';
}
else if ($roll2 == 4) {
  $englishRoll2 = '4';
}
else if ($roll2 == 5) {
  $englishRoll2 = '5';
}
else if ($roll2 == 6) {
  $englishRoll2 = 'six';
}

echo '<p>You rolled a ' . $english . ' and a ' . $englishRoll2 . '</p>';

As a substitute, the array can be utilized for each rolls.

Instance: PHP-DiceRoll-English-Array-TwoDice

$english = [
  1 => 'one',
  2 => 'two',
  3 => 'three',
  4 => 'four',
  5 => 'five',
  6 => 'six'
];

$roll1 = rand(1, 6);
$roll2 = rand(1, 6);

echo '<p>You rolled a ' . $english[$roll1] . ' and a ' . $english[$roll2] . '</p>';

Whereas numbers are the most typical alternative for array indices, there’s one other chance. You can even use strings as indices to create what’s referred to as an associative array. It’s referred to as this as a result of it associates values with significant indices. On this instance, we affiliate a date (within the type of a string) with every of three names:

$birthdays['Kevin'] = '1978-04-12';
$birthdays['Stephanie'] = '1980-05-16';
$birthdays['David'] = '1983-09-09';

Just like the numerical indexes, you should utilize the shorthand notation for associative arrays as properly:

$birthdays = [
  'Kevin' => '1978-04-12',
  'Stephanie' => '1980-05-16',
  'David' => '1983-09-09'
];

Now, if we need to know Kevin’s birthday, we glance it up utilizing the identify because the index:

echo 'Kevin's birthday is: ' . $birthdays['Kevin'];

This sort of array is particularly necessary on the subject of person interplay in PHP, as we’ll see shortly. I’ll additionally display different makes use of of arrays all through this ebook.

Word: as a result of Kevin's accommodates an apostrophe (single quote) and PHP would see this as the top of the string, it should be escaped with a in order that PHP treats it as a part of the string, quite than marking the top.

Consumer Interplay and Varieties

Database-driven web sites usually must do greater than dynamically generate pages based mostly on database information. You additionally want to offer a point of interactivity, even when it’s only a search field.

As a result of JavaScript code can stay within the browser, it permits customers to have all kinds of quick interactions with an online web page. Server-side scripting languages reminiscent of PHP have a extra restricted scope on the subject of assist for person interplay. As PHP code is just activated when a request is made to the server, person interplay happens solely in a back-and-forth style: the person sends requests to the server, and the server replies with dynamically generated pages.

The important thing to creating interactivity with PHP is to know the methods we are able to make use of to ship details about a person’s interplay, together with a request for a brand new internet web page. Because it seems, PHP makes this fairly simple.

Word: because the Net has developed, so too have the choices for communication between the back and front ends of an online app. JavaScript permits for communication with a again finish with out web page reloading. A JavaScript framework reminiscent of Vue.js, for instance, can talk with PHP frameworks like Laravel. For the needs of this ebook, nevertheless, we’ll concentrate on what might be carried out with PHP alone.

The best technique to ship info together with a web page request is to make use of the URL question string. If you happen to’ve ever observed a URL containing a query mark that follows the filename, you’ve seen this system in use. For instance, for those who seek for “SitePoint” on Google, it should take you to a search end result web page with a URL like this:

http://www.google.com/search?hl=en&q=SitePoint

See the query mark within the URL? The textual content that follows the query mark accommodates your search question (SitePoint). That info is being despatched together with the request for http://www.google.com/search.

Let’s code up a straightforward instance of our personal. Create an everyday HTML file referred to as identify.html (no .php filename extension is required, since there gained’t be any PHP code on this file) and insert this hyperlink:

<a href="https://www.sitepoint.com/php-beginners-guide/identify.php?identify=Tom">Hello, I’m Tom!</a>

It is a hyperlink to a file referred to as identify.php, however in addition to linking to the file, you’re additionally passing a variable together with the web page request. The variable is handed as a part of the question string, which is the portion of the URL that follows the query mark. The variable known as identify, and its worth is Tom. So, you’ve created a hyperlink that hundreds identify.php, and which informs the PHP code contained in that file that identify equals Tom.

To essentially perceive the impact of this hyperlink, we have to have a look at identify.php. Create it as a brand new file, however this time, word the .php filename extension. This tells the net server that it might probably count on to interpret some PHP code within the file. Within the physique of this new internet web page, kind the next.

Instance: PHP-GET

<?php
$identify = $_GET['name'];
echo 'Welcome to our web site, ' . $identify . '!';
?>

Now, put these two recordsdata (identify.html and identify.php) within the public folder, and cargo the primary file in your browser. (The URL must be https://v.je/identify.html.) Click on the hyperlink in that first web page to request the PHP script. The ensuing web page ought to say “Welcome to our web site, Tom!”, as proven within the picture under.

The welcome message, seen in the browser

Let’s take a better have a look at the code that made this potential. That is an important line:

$identify = $_GET['name'];

Utilizing what you realized from the “Arrays” part above, you could possibly work out what this line does. It assigns the worth saved within the 'identify' component of the array referred to as $_GET to a brand new variable referred to as $identify. However the place does the $_GET array come from?

It seems that $_GET is considered one of a lot of variables that PHP robotically creates when it receives a request from a browser. PHP creates $_GET as an array variable that accommodates any values handed within the URL question string. $_GET is an associative array, so the worth of the identify variable handed within the question string might be accessed as $_GET['name']. Your identify.php script assigns this worth to an unusual PHP variable ($identify), then shows it as a part of a textual content string utilizing an echo assertion:

echo 'Welcome to our web site, ' . $identify . '!';

The worth of the $identify variable is inserted into the output string utilizing the string concatenation operator (.) that we checked out within the “Variables, Operators, and Feedback” part.

However be careful! There’s a safety gap lurking on this code! Though PHP is a straightforward programming language to study, it seems it’s additionally particularly simple to introduce safety points into web sites utilizing PHP for those who’re unaware of what precautions to take. Earlier than we go any additional with the language, I need to ensure you’re in a position to spot and repair this explicit safety challenge, because it’s most likely the most typical one on the Net in the present day.

The safety challenge right here stems from the truth that the identify.php script is producing a web page containing content material that’s underneath the management of the person — on this case, the $identify variable. Though the $identify variable will usually obtain its worth from the URL question string within the hyperlink on the identify.html web page, a malicious person may edit the URL to ship a special worth for the identify variable.

To see how this might work, click on the hyperlink in identify.html once more. Once you see the ensuing web page (with the welcome message containing the identify “Tom”), check out the URL within the handle bar of your browser. It ought to look just like this:

https://v.je/identify.php?identify=Tom

Edit the URL to insert a <b> tag earlier than the identify and a </b> tag following the identify:

https://v.je/identify.php?identify=<b>Tom</b>

Hit enter to load this new URL, and word that the identify within the web page is now daring, as proven within the following picture.

The name shown in bold

Word: you may discover that some browsers will robotically convert the < and > characters into URL escape sequences (%3C and %3E respectively), however both manner, PHP will obtain the identical worth.

See what’s taking place right here? The person can kind any HTML code into the URL, and your PHP script contains it within the code of the generated web page with out query. If the code is as innocuous as a <b> tag, there’s no downside, however a malicious person may embody subtle JavaScript code that performs some low motion like stealing the person’s password. All of the attacker must do is publish the modified hyperlink on another website underneath the attacker’s management, after which entice considered one of your customers to click on it. The attacker may even embed the hyperlink in an e mail and ship it to your customers. If considered one of your customers clicked the hyperlink, the attacker’s code can be included in your web page and the lure can be sprung!

I hate to scare you with this speak of malicious hackers attacking your customers by turning your personal PHP code towards you, significantly while you’re solely simply studying the language. The actual fact is that PHP’s largest weak spot as a language is how simple it’s to introduce safety points like this. Some may say that a lot of the power you spend studying to put in writing PHP to knowledgeable customary is spent on avoiding safety points. The earlier you’re uncovered to those points, nevertheless, the earlier you develop into accustomed to avoiding them, and the much less of a stumbling block they’ll be for you in future.

So, how can we generate a web page containing the person’s identify with out opening it as much as abuse by attackers? The answer is to deal with the worth provided for the $identify variable as plain textual content to be displayed in your web page, quite than as HTML to be included within the web page’s code. It is a delicate distinction, so let me present you what I imply.

Open up your identify.php file once more and edit the PHP code it accommodates in order that it appears just like the code under.

Instance: PHP-GET-Sanitized

<?php
$identify = $_GET['name'];
echo 'Welcome to our web site, ' .
  htmlspecialchars($identify, ENT_QUOTES, 'UTF-8') . '!';
?>

There’s loads occurring on this code, so let me break it down for you. The primary line is identical because it was beforehand, assigning to $identify the worth of the 'identify' component from the $_GET array. However the echo assertion that follows it’s drastically completely different. Whereas beforehand we merely dumped the $identify variable — bare — into the echo assertion, this model of the code makes use of the built-in PHP operate htmlspecialchars to carry out a vital conversion.

Bear in mind, the safety gap happens as a result of, in identify.php, HTML code within the $identify variable is dumped immediately into the code of the generated web page, and might subsequently do something that HTML code can do. What htmlspecialchars does is convert “particular HTML characters” like < and > into HTML character entities like &lt; and &gt;, which prevents them from being interpreted as HTML code by the browser. I’ll display this for you in a second.

First, let’s take a better have a look at this new code. The decision to the htmlspecialchars operate is the primary instance on this ebook of a PHP operate that takes a couple of argument. Right here’s the operate name all by itself:

htmlspecialchars($identify, ENT_QUOTES, 'UTF-8')

The primary argument is the $identify variable (the textual content to be transformed). The second argument is the PHP “fixed” ENT_QUOTES, which tells htmlspecialchars to transform single and double quotes along with different particular characters.

Word: a PHP fixed is sort of a variable whose worth you’re unable to vary. In contrast to variables, constants don’t begin with a greenback signal. PHP comes with a lot of built-in constants like ENT_QUOTES which are used to regulate built-in capabilities like htmlspecialchars.

The third parameter is the string 'UTF-8', which tells PHP what character encoding to make use of to interpret the textual content you give it.

Word: you could have discerned that every one the instance HTML pages on this ebook comprise the next meta component close to the highest:

<meta charset="utf-8">

This component tells the browser receiving this web page that the HTML code of the web page is encoded as UTF-8 textual content.

UTF-8 is considered one of many requirements for representing textual content as a sequence of ones and zeros in pc reminiscence, referred to as character encodings. If you happen to’re curious to study all about character encodings, take a look at “The Definitive Information to Net Character Encoding”.

In a couple of pages, we’ll attain the part on “Passing Variables in Varieties”. By encoding your pages as UTF-8, your customers can submit textual content containing hundreds of overseas characters that your website would in any other case be unable to deal with.

Sadly, a lot of PHP’s built-in capabilities, reminiscent of htmlspecialchars, assume you’re utilizing the a lot easier ISO-8859-1 (or Latin-1) character encoding by default. Subsequently, you’ll want to allow them to know you’re utilizing UTF-8 when using these capabilities.

If you happen to can, you also needs to inform your textual content editor to save lots of your HTML and PHP recordsdata as UTF-8 encoded textual content. That is solely required if you wish to kind superior characters (reminiscent of curly quotes or dashes) or overseas characters (like “é”) into your HTML or PHP code. The code on this ebook performs it secure and makes use of HTML entity references (for instance, &rsquo; for a curly proper quote), which is able to work regardless.

Open up identify.html in your browser and click on the hyperlink that now factors to your up to date identify.php. As soon as once more, you’ll see the message “Welcome to our web site, Tom!” As you probably did earlier than, modify the URL to incorporate <b> and </b> tags surrounding the identify:

https://v.je/identify.php?identify=<b>Tom</b>

Once you hit enter this time, as a substitute of the identify turning daring within the web page, it is best to see the precise textual content you typed, as proven within the following picture.

It sure is ugly, but it’s secure!

If you happen to view the supply code of the web page, you’ll be able to verify that the htmlspecialchars operate did its job and transformed the < and > characters into the &lt; and &gt; entity references respectively. This prevents malicious customers from injecting undesirable code into your website. If they fight something like that, the code is harmlessly displayed as plain textual content on the web page.

We’ll make in depth use of the htmlspecialchars operate all through this ebook to protect towards this type of safety gap. No want to fret an excessive amount of for those who’re having hassle greedy the small print of how one can use it simply for the time being. Earlier than lengthy, you’ll discover its use turns into second nature. For now, let’s have a look at some extra superior methods of passing values to PHP scripts after we request them.

Passing a single variable within the question string was good, however it seems you’ll be able to cross extra than one worth if you wish to! Let’s have a look at a barely extra complicated model of the earlier instance. Open up your identify.html file once more, and alter the hyperlink to level to identify.php with this extra sophisticated question string:

<a href="identify.php?firstname=Tom&amp;lastname=Butler">Hello,
  I’m Tom Butler!</a>

This time, our hyperlink passes two variables: firstname and lastname. The variables are separated within the question string by an ampersand (&, which must be written as &amp; in HTML — sure, even in a hyperlink URL! … though, for those who do wrongly use &, browsers will principally repair it for you). You’ll be able to cross much more variables by separating every identify=worth pair from the subsequent with an ampersand.

As earlier than, we are able to use the 2 variable values in our identify.php file.

Instance: PHP-GET-TwoVars

<?php
$firstName = $_GET['firstname'];
$lastName = $_GET['lastname'];
echo 'Welcome to our web site, ' .
  htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8') . ' ' .
  htmlspecialchars($lastName, ENT_QUOTES, 'UTF-8') . '!';
?>

The echo assertion is turning into fairly sizable now, however it ought to nonetheless make sense to you. Utilizing a sequence of string concatenations (.), it outputs “Welcome to our web site”, adopted by the worth of $firstName (made secure for show utilizing htmlspecialchars), an area, the worth of $lastName (once more, handled with htmlspecialchars), and eventually an exclamation mark.

The result’s pictured under.

The echoed welcome

That is all properly and good, however we’re nonetheless but to realize our aim of true person interplay, the place the person can enter arbitrary info and have it processed by PHP. To proceed with our instance of a customized welcome message, we’d like to ask the person to kind their identify and have it seem within the ensuing web page. To allow the person to kind in a worth, we’ll want to make use of an HTML type.

Passing Variables in Varieties

Take away the hyperlink code from identify.html and change it with this HTML code to create the shape.

Instance: PHP-GET-Type

<type motion="identify.php" methodology="get">
  <label for="firstname">First identify:</label>
  <enter kind="textual content" identify="firstname" id="firstname">

  <label for="lastname">Final identify:</label>
  <enter kind="textual content" identify="lastname" id="lastname">

  <enter kind="submit" worth="GO">
</type>

The picture under reveals how the browser shows the shape produced from this code.

The form as it appears in a browser

Word: I’ve added some CSS to the shape (obtainable in type.css within the pattern code) to make it look slightly prettier. The CSS I’ve used could be very generic, and can be utilized to show any type within the format label-input-line break. I’ll be together with this CSS file on any web page that accommodates a type.

Since this can be a ebook about PHP and MySQL, nevertheless, I gained’t go into element about how the CSS works. Try SitePoint’s HTML5 & CSS3 for the Actual World for recommendation on styling your varieties with CSS.

This way has the very same impact because the second hyperlink we checked out within the “Passing Variables in Hyperlinks” part above (with firstname=Tom&amp;lastname=Butler within the question string), besides you can now enter whichever names you want. Once you click on the submit button (labeled GO), the browser will load identify.php and add the variables and their values to the question string for you robotically. It retrieves the names of the variables from the identify attributes of the kind="textual content" inputs, and obtains the values from the textual content typed into the textual content fields by the person.

The methodology attribute of the shape tag is used to inform the browser how one can ship the variables and their values together with the request. A price of get (as utilized in identify.html above) causes them to be handed through the question string (and seem in PHP’s $_GET array), however there’s another. It may be undesirable — and even technically unfeasible — to have the values seem within the question string. What if we included a <textarea> component within the type, to let the person enter a considerable amount of textual content? A URL whose question string contained a number of paragraphs of textual content can be ridiculously lengthy, and might exceed the utmost size for a URL in in the present day’s browsers. The choice is for the browser to cross the knowledge invisibly, behind the scenes.

Edit your identify.html file as soon as extra. Modify the shape methodology by setting it to submit:

<type motion="identify.php" methodology="submit">
  <label for="firstname">First identify:</label>
  <enter kind="textual content" identify="firstname" id="firstname">

  <label for="lastname">Final identify:</label>
  <enter kind="textual content" identify="lastname" id="lastname">

  <enter kind="submit" worth="GO">
</type>

This new worth for the strategy attribute instructs the browser to ship the shape variables invisibly as a part of the web page request, quite than embedding them within the question string of the URL.

As we’re not sending the variables as a part of the question string, they cease showing in PHP’s $_GET array. As a substitute, they’re positioned in one other array reserved particularly for “posted” type variables: $_POST. We should subsequently modify identify.php to retrieve the values from this new array.

Instance: PHP-POST-Type

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo 'Welcome to our web site, ' .
  htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' .
  htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!';
?>

The picture under reveals what the ensuing web page appears like as soon as this new type is submitted.

The resulting page once the form is submitted

The shape is functionally equivalent to the earlier one. The one distinction is that the URL of the web page that’s loaded when the person clicks the GO button can be with out a question string. On the one hand, this allows you to embody massive values (or delicate values reminiscent of passwords and bank card numbers) within the information that’s submitted by the shape with out them showing within the question string. Alternatively, if the person bookmarks the web page that outcomes from the shape’s submission, that bookmark can be ineffective, because it lacks the submitted values. This, by the way, is the primary cause why search engines like google use the question string to submit search phrases. If you happen to bookmark a search outcomes web page on Google, you should utilize that bookmark to carry out the identical search once more later, as a result of the search phrases are contained within the URL.

Word: as a rule of thumb, it is best to solely use GET varieties if, when the shape is submitted, nothing on the server modifications — reminiscent of while you’re requesting an inventory of search outcomes. As a result of the search phrases are within the URL, the person can bookmark the search outcomes web page and get again to it with out having to kind within the search time period once more. But when, after submitting the shape, a file is deleted, a database is up to date, or a report is inserted, it is best to use POST. The first cause for that is that if a person bookmarks the web page (or presses the again button of their browser) it gained’t set off the shape submission once more and doubtlessly create a reproduction report.

POST can also be safer. Something despatched through GET seems within the URL and is saved within the person’s historical past and bookmarks — that are very insecure places for delicate information reminiscent of passwords and bank card particulars.

That covers the fundamentals of utilizing varieties to supply rudimentary person interplay with PHP. We’ll have a look at extra superior points and methods in later examples.

Hiding the Seams

You’re now armed with a working data of the fundamental syntax of the PHP programming language. You perceive you can take any HTML internet web page, rename it with a .php file identify extension, and inject PHP code into it to generate web page content material on the fly. Not dangerous for a day’s work!

Earlier than we go any additional, nevertheless, I need to cease and solid a vital eye over the examples we’ve mentioned to this point. Assuming your goal is to create database-driven web sites that maintain as much as skilled requirements, there are a couple of unpleasant blemishes we have to clear up.

The methods in the remainder of this chapter will assist advance your programming abilities past the newbie stage, giving them a sure skilled polish. I’ll depend on these methods all through the remainder of this ebook to make sure that, irrespective of how easy the instance, you’ll be able to really feel assured within the high quality of the product you’re delivering.

PHP Templates

Within the easy examples we’ve seen to this point, inserting PHP code immediately into your HTML pages has been an inexpensive method. As the quantity of PHP code that goes into producing your common web page grows, nevertheless, sustaining this combination of HTML and PHP code can develop into unmanageable.

Significantly for those who work in a group of internet designers who aren’t particularly PHP savvy, having massive blocks of cryptic PHP code intermingled with the HTML is a recipe for catastrophe. It’s far too simple for designers to by chance modify the PHP code, inflicting errors they’ll be unable to repair.

A way more sturdy method is to separate out the majority of your PHP code in order that it resides in its personal file, leaving the HTML largely unpolluted by PHP code.

The important thing to doing that is the PHP embody assertion. With an embody assertion, you’ll be able to insert the contents of one other file into your PHP code on the level of the assertion. To point out you ways this works, let’s rebuild the “rely to 10” for loop instance we checked out earlier.

Begin by creating a brand new file, rely.php, in your public listing. Open the file for enhancing and sort on this code:

<?php
$output="";
for ($rely = 1; $rely <= 10; $rely++) {
    $output .= $rely . ' ';
}

embody 'rely.html.php';

Sure, that’s the full code for this file. It accommodates no HTML code in anyway. The for loop must be acquainted to you by now, however let me level out the attention-grabbing components of this code:

  • As a substitute of echoing out the numbers 1 to 10, this script will add these numbers to a variable named $output. At first of this script, subsequently, we set this variable to comprise an empty string.
  • The road $output .= $rely . ' '; provides every quantity (adopted by an area) to the top of the $output variable. The .= operator you see here’s a shorthand manner of including a worth to the top of an current string variable, by combining the project and string concatenation operators into one. The longhand model of this line is $output = $output . $rely . ' ';, however the .= operator saves you some typing.
  • The embody assertion instructs PHP to execute the contents of the rely.html.php file at this location. You’ll be able to consider the embody assertion as a type of copy and paste. You’ll get the identical end result by opening up rely.html.php, copying the contents and pasting them into rely.php, overwriting the embody line.
  • Lastly, you may need observed that the file doesn’t finish with a ?> to match the opening <?php. You’ll be able to put it in for those who actually need to, however it’s not vital. If a PHP file ends with PHP code, there’s no want to point the place that code ends; the top of the file does it for you. The massive brains of the PHP world usually want to go away it off the top of recordsdata like this one which comprise solely PHP code.

Word: exterior of this ebook, you’ll typically see parentheses surrounding the filename in embody code, as if embody have been a operate like date or htmlspecialchars, which is much from the case. For instance, as a substitute of embody 'rely.html.php';, you may see embody('rely.html.php');. These parentheses, when used, solely serve to complicate the filename expression, and are subsequently averted on this ebook. The identical goes for echo, one other standard one-liner.

Because the remaining line of our rely.php file contains the rely.html.php file, it is best to create that file subsequent.

Instance: PHP-Rely-Template

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Counting to Ten</title>
  </head>
  <physique>
    <p>
      <?php echo $output; ?>
    </p>
  </physique>
</html>

This file is sort of totally plain HTML, aside from the one line that outputs the worth of the $output variable. This is identical $output variable that was created by the rely.php file.

What we’ve created here’s a PHP template: an HTML web page with solely very small snippets of PHP code that insert dynamically generated values into an in any other case static HTML web page. Slightly than embedding the complicated PHP code that generates these values within the web page, we put the code to generate the values in a separate PHP script — rely.php on this case.

Utilizing PHP templates like this allows you to hand over your templates to front-end designers with out worrying about what they may do to your PHP code. It additionally enables you to focus in your PHP code with out being distracted by the encompassing HTML code.

I like to call my PHP template recordsdata in order that they finish with .html.php. So far as your internet server is anxious, although, these are nonetheless .php recordsdata; the .html.php suffix serves as a helpful reminder that these recordsdata comprise each HTML and PHP code.

To see how our pages work now, kind https://v.je/rely.php into your browser. You’ll see the outcomes of the rely.php script displayed in our rely.html.php template.

Safety Considerations

One downside with separating out the HTML and PHP code into completely different recordsdata is that somebody may doubtlessly run the .html.php code with out having had it included from a corresponding PHP file. This isn’t a giant downside, however anybody may go to rely.html.php immediately. If you happen to kind https://v.je/rely.html.php into your internet browser, as a substitute of seeing the rely from one to 10, you’ll see an error message: Discover: Undefined variable: output in /web sites/default/public/rely.html.php on line 9.

It’s higher to not let individuals run code in a way you’re not anticipating. Relying on what the web page is doing, this may allow them to bypass safety checks you’ve gotten in place and consider content material they shouldn’t have entry to. For instance, contemplate the next code:

if ($_POST['password'] == 'secret') {
  embody 'protected.html.php';
}

Taking a look at this code, it seems that you’ll want to submit a type and sort secret within the password field to see the protected content material in protected.html.php. Nonetheless, if somebody can navigate on to protected.html.php and see the contents of the web page, it makes the safety test redundant. There are different potential safety points launched by making all of your recordsdata accessible through a URL. Avoiding safety issues like these is simple. You’ll be able to really embody recordsdata from a listing aside from the public listing.

You might have puzzled earlier why the event atmosphere created a public listing contained in the default listing and we then wrote all our recordsdata to the public listing. Effectively, this challenge of safety is the explanation why. Not one of the recordsdata exterior the public listing are accessible through a URL (by somebody typing the file identify into their internet browser).

The embody command might be tweaked to incorporate recordsdata from one other listing. In our case, that listing goes to be the default listing, which accommodates the public listing we’ve been writing our recordsdata to.

So the query is, when the embody file is in a completely different listing, how does a PHP script discover it? The obvious methodology is to specify the situation of the embody file as an absolute path. Right here’s how this might look on a Home windows server:

<?php embody 'C:/Program Information/Apache Software program Basis/Apache2.2/protected.html.php'; ?>

And right here’s how it will look utilizing the Docker atmosphere we’re utilizing:

<?php embody '/web sites/default/protected.html.php'; ?>

Whereas this methodology will work, it’s undesirable as a result of it ties your website’s code to your internet server configuration. As a result of we’re utilizing Docker, deploying the web site would additionally use the identical Docker atmosphere, so this isn’t actually a difficulty as of late. Nonetheless, it is best to ideally have the ability to drop your PHP-based web site onto any PHP-enabled internet server and simply watch it run. That’s impractical in case your code refers to drives and directories which are particular to 1 explicit server. Even for those who do have the luxurious of engaged on a single server, you’ll be kicking your self for those who ever want to maneuver your web site to a different drive/listing on that server.

A greater methodology is to make use of a relative path — that’s, the situation of a file relative to the present file. Once you use embody 'rely.html.php', that is really a relative path: rely.html.php is being included from the identical listing because the script that was executed.

To incorporate a file from the listing above, you should utilize the next code:

embody '../rely.html.php';

The ../ bit tells PHP to search for the file within the listing above the listing of the present script. It should search for rely.html.php within the default listing as a substitute of the public listing.

Go forward and transfer rely.html.php up a stage into the default listing and amend rely.php to reference the brand new location.

Instance: PHP-Rely-Template-Secured

<?php
$output="";
for ($rely = 1; $rely <= 10; $rely++) {
    $output .= $rely . ' ';
}

embody '../rely.html.php';

If you happen to run the code above, it should work. However there’s a possible downside while you embody recordsdata on this manner. Relative paths are relative to the script that was run, to not every file.

That’s, for those who open up default/rely.html.php and add the road embody 'count2.html.php'; you’d count on count2.html.php to be included from the default listing. Nonetheless, the trail is relative to one thing referred to as the present working listing, which, while you run a PHP script, is initially set to the listing that script is saved in. So operating embody 'count2.html.php'; from rely.html.php will really attempt to load count2.html.php from the public listing!

The present working listing is ready at the beginning of the script and applies to all of the embody statements, no matter what file they’re in. To make issues much more complicated, it’s potential to vary the present working listing utilizing the chdir() operate.

Due to this, we are able to’t depend on the next:

embody '../rely.html.php';

It should work, but when the listing is modified, or rely.php itself is an embody file, it could not have the end result we’re anticipating.

To beat this, we do really need to make use of absolute paths. Fortunately, PHP offers a relentless referred to as __DIR__ (that’s two underscores, earlier than and after the phrase DIR) which is able to at all times comprise the trail that accommodates the present file.

For instance, you possibly can create a file referred to as dir.php contained in the public listing with the next code:

echo __DIR__;

This may show /web sites/default/public, which is the total path to the listing containing dir.php. To learn rely.html.php from the listing above public, it’s potential to mix the /../ operator and the __DIR__ fixed:

embody __DIR__ . '/../rely.html.php';

This may now embody the file /web sites/default/public/../rely.html. That’s, PHP will look within the public listing, then go up one stage into default and embody rely.html.php.

This method will work on any server, as a result of __DIR__ will differ relying on the place the file is saved, and it doesn’t rely upon the altering present working listing. I’ll be utilizing this method for together with recordsdata all through this ebook.

Any further, we’ll solely write recordsdata to the public listing that we really need customers to have the ability to entry immediately from their internet browser. The public listing will comprise any PHP scripts the person must entry immediately together with any photographs, JavaScript and CSS recordsdata required by the browser. Any recordsdata solely referenced by an embody assertion can be positioned exterior the public listing so customers can’t entry them immediately.

Because the ebook goes on, I’m going to introduce you to a number of several types of embody recordsdata. To maintain issues organized, it’s wise to retailer several types of embody recordsdata in numerous directories. We’ll retailer template recordsdata (with a .html.php extension) inside a listing referred to as templates contained in the default folder. We are able to then reference them in an embody assertion utilizing embody __DIR__ . '../templates/file.html.php';.

Many Templates, One Controller

What’s good about utilizing embody statements to load your PHP template recordsdata is you can have a number of embody statements in a single PHP script, in addition to have it show completely different templates underneath varied circumstances!

A PHP script that responds to a browser request by choosing considered one of a number of PHP templates to fill in and ship again is often referred to as a “controller”. A controller accommodates the logic that controls which template is shipped to the browser.

Let’s revisit yet another instance from earlier on this chapter — the welcome type that prompts a customer for a primary and final identify.

We’ll begin with the PHP template for the shape. For this, we are able to simply reuse the identify.html file we created earlier. Create a listing templates inside default for those who haven’t already, and save a replica of identify.html referred to as type.html.php into this listing. The one code you’ll want to change on this file is the motion attribute of the shape tag.

Instance: PHP-Type-Controller

<!doctype html>
<html>
  <head>
    <title>Enter your identify</title>
    <hyperlink rel="stylesheet" href="https://www.sitepoint.com/php-beginners-guide/type.css" />
    <meta charset="utf-8">  
  </head>
  <physique>
  <type motion="" methodology="submit">
    <label for="firstname">First identify:</label>
    <enter kind="textual content" identify="firstname" id="firstname">

    <label for="lastname">Final identify:</label>
    <enter kind="textual content" identify="lastname" id="lastname">

    <enter kind="submit" worth="GO">
  </type>
  </physique>
</html>

As you’ll be able to see, we’re leaving the motion attribute clean. This tells the browser to submit the shape again to the identical URL it obtained it from — on this case, the URL of the controller that included this template file.

Let’s check out the controller for this instance. Create an index.php file contained in the public listing that accommodates the next code:

<?php
if (!isset($_POST['firstname'])) {
    embody  __DIR__ . '/../templates/type.html.php';
} else {
    $firstName = $_POST['firstname'];
    $lastName = $_POST['lastname'];

    if ($firstName == 'Tom' && $lastName == 'Butler') {
        $output="Welcome, oh superb chief!";
    } else {
        $output="Welcome to our web site, " .
      htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8') . ' ' .
      htmlspecialchars($lastName, ENT_QUOTES, 'UTF-8') . '!';
    }

    embody  __DIR__ . '/../templates/welcome.html.php';
}

This code ought to look fairly acquainted at first look. It’s loads just like the identify.php script we wrote earlier. Let me clarify the variations:

  • The controller’s first job is to determine whether or not the present request is a submission of the shape in type.html.php or not. You are able to do this by checking if the request accommodates a firstname variable. If it does, PHP could have saved the worth in $_POST['firstname'].

    isset is a built-in PHP operate that may inform you if a selected variable (or array component) has been assigned a worth or not. If $_POST['firstname'] has a worth, isset($_POST['firstname']) can be true. If $_POST['firstname'] is unset, isset($_POST['firstname']) can be false.

    For the sake of readability, I wish to put the code that sends the shape in my controller first. We want this if assertion to test if $_POST['firstname'] isn’t set. To do that, we use the not operator (!). By placing this operator earlier than the identify of a operate, you reverse the worth that operate returns — from true to false, or from false to true.

    Thus, if the request doesn’t comprise a firstname variable, then !isset($_POST['firstname']) will return true, and the physique of the if assertion can be executed.

  • If the request isn’t a type submission, the controller contains the type.html.php file to show the shape.
  • If the request is a type submission, the physique of the else assertion is executed as a substitute.

    This code pulls the firstname and lastname variables out of the $_POST array, after which generates the suitable welcome message for the identify submitted.

  • As a substitute of echoing the welcome message, the controller shops the welcome message in a variable named $output.
  • After producing the suitable welcome message, the controller contains the welcome.html.php template, which is able to show that welcome message.

All that’s left is to put in writing the welcome.html.php file into the templates listing. Right here it’s:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Type Instance</title>
  </head>
  <physique>
    <p>
      <?php echo $output; ?>
    </p>
  </physique>
</html>

That’s it! Fireplace up your browser and level it at https://v.je/index.php. You’ll be prompted to your identify, and while you submit the shape, you’ll see the suitable welcome message. The URL ought to keep the identical all through this course of.

You’ll have observed I requested you to call the file index.php as a substitute of identify.php or related. The explanation I used index.php is as a result of it has a particular that means. index.php is called a listing index. If you happen to don’t specify a filename while you go to the URL in your browser, the server will search for a file named index.php and show that. Strive typing simply https://v.je into your browser and also you’ll see the index web page.

Word: internet servers can have completely different configurations and specify a special file to be the listing index. Nonetheless, index.php will work on most internet servers with none additional configuration.

One of many advantages of sustaining the identical URL all through this strategy of prompting the person for a reputation and displaying the welcome message is that the person can bookmark the web page at any time throughout this course of and achieve a wise end result. Whether or not it’s the shape web page or the welcome message that’s bookmarked, when the person returns, the shape can be current as soon as once more. Within the earlier model of this instance, the place the welcome message had its personal URL, returning to that URL with out submitting the shape would have generated a damaged welcome message (“Welcome to our web site, !”), or a PHP error message if, like ours, the server is operating with error reporting enabled.

Word: in Chapter 11, the place we talk about “periods”, I present you how one can bear in mind the person’s identify between visits.

Carry On the Database

On this chapter, we’ve seen the PHP server-side scripting language in motion as we’ve explored all the fundamental language options: statements, variables, operators, feedback, and management buildings. The pattern functions we’ve seen have been fairly easy, however we’ve nonetheless taken the time to make sure they’ve enticing URLs, and that the HTML templates for the pages they generate are uncluttered by the PHP code that controls them.

As you could have begun to suspect, the actual energy of PHP is in its a whole lot (even hundreds) of built-in capabilities that allow you to entry information in a MySQL database, ship e mail, dynamically generate photographs, and even create Adobe Acrobat PDF recordsdata on the fly.

In Chapter 3, we’ll delve into the MySQL capabilities constructed into PHP, after which create a database of jokes. Then, in Chapter 4, we’ll see how one can publish that joke database to the Net. These duties will set the scene for the last word aim of this ebook: to create a whole content material administration system to your web site in PHP and MySQL.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments