Options are set mainly to change folder access. We set these options on or off respectively with + and –.
Indexes
When allowed, Indexes allows the listing of all files in a folder by accessing this through a request. Therefore, is is especially important to turn this option off (with -) to not reveal the contents of your folders. This will make it harder to exploit your system for evil intents.
MultiViews
When turned on, MultiViews may cause substitute files to be read when others are required that incompletely match the name of those present on the server. In the case of an MVC application, we wish to completely route the application based on requests not matching the files in the system, and furthermore, we wish to still allow resources to be directly loaded by the browser. We must turn off this option.
URL Rewriting
One useful thing Apache can do to make your MVC Web application work well if to rewrite URLs in such a way that the URL becomes a parameter for a PHP application entry point.
RewriteEngine On
Before any URL rewriting happens, we must turn on the rewriting engine.
RewriteBase
The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path. Here, we wish to call the index.php file in the Web server document root.
RewriteCond directive
The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following RewriteRule is then only used if the current state of the URI matches its pattern, and if all these conditions are met.
REQUEST_FILENAME is the full local filesystem path to the file or script matching the request.
-f: Is regular file. (alternatively !-f is NOT regular file.) Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
-d: Is directory. (alternatively !-d is NOT directory.) Treats the TestString as a pathname and tests whether or not it exists, and is a directory.
So the above sets conditions that the requested file is neither a file or folder that exists. This will allow the browser to fetch stylesheets, libraries, etc. from the resources without having to be routed by the MVC application.
RewriteRule
This sets the rule that will be run once the conditions are met. In the above example
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
the rule matches the incoming requested URL, except the server address, and sends this URL to index.php, through the URL query string parameter. Any other query string parameters are added by virtue of the QSA (Query String Append) flag. The L flag ensures that no further rules are applied to this request if this rule is run.
One more .htaccess file is needed in the app folder of your MVC application (or wherever your application stores its code which should not be accesses directly through Http requests). The file is as follows:
Options -Indexes
Deny from all
This will not allow users to list contents of any folder as well as disallow direct access to any file through external requests. Only your internal code will be able to include, require and run this code.
Completing the application
Consider the above .htaccess file is in the Apache server document root with the following index.php file:
<?php
var_dump($_GET);
?>
Then, for any request with characters after the / following the hostname, e.g., https://cstutoring.ca/Hello/Alice, the characters would be displayed in an output of the following nature:
array(1) { ["url"]=> string(11) "Hello/Alice" }
We can now use the ‘url’ value to enable routing within the MVC application.
To learn to use conditional test statements to compare numerical and string data values
To learn to use looping statements to repeat statements
To learn to use Boolean operators to create compound conditional test statements
Using Conditional Test Statements
Conditional statements provide a way for scripts to test for certain data values and then to react differently depending on the value found.
Using the if Statement
Use an if statement to specify a test condition and a set of statements to run when a test condition is true.
if ($average > 69)
$Grade="Pass";
print "Grade=$Grade ";
print "Your average was $average";
If $average was equal to 70 then the above would output:
Grad=PassYouraveragewas70
Boolean Expressions
Boolean expressions use Boolean operators to compare values and output is a Boolean value (true or false).
PHP Boolean Operators
Test
Operator
Effect
==
Equal to
!=
Notequal to
<
Lessthan
>
Greater than
>=
Greater thanor
equal to
<=
Lessthan or
equal to
The === and !=== test for equality and inequality, additionally testing for data type. So'1'==1istruewhereas'1'===1isfalse. and '1'!=1isfalseand'1'!==1istrue.
AFullExample…
Consider the following application which receives two grades as input and determines whether their average is above 89. It uses an HTML form for input grades:
Enter First Score <input type="text" size="4" maxlength="7" name="grade1"> Enter Second Score <input type="text" size="4" maxlength="7" name="grade2">
And the receiving inline PHP:
<html>
<head><title>Decisions</title></head>
<body>
<?php
$grade1= $_POST["grade1"];//get the first grade
$grade2= $_POST["grade2"];//gest the second grade
$average = ($grade1 + $grade2) / 2;
if ( $average > 89 ) {
print "Average score: $average You got an A! <br>";
}
$max=$grade1;
if ($grade1 < $grade2) {
$max = $grade2;
}
print ("Your max score was $max");
?>
</body></html>
ComparingStrings
PHP represents strings using character encodings such as the ASCII code values. These encodings provide a standard, numerical way to represent characters in computer storage. Every letter, number, and symbol is translated into a code number.
For instance:
“A” is ASCII code 65, “B” is 66, “C” is 67, and so on and “a” is ASCII code 97, “b” is 98, “c” is 99, and so on.
ASCII “A” is less than ASCII “a,” “B” is less than “b,” and “c” is less than “d”.
ComparingStrings
You can use == operator to check if one string is equal to another. For example,
$sport1 = "Hockey"; $sport2 = "Soccer";
if ($sport1 == $sport2) {
print ("$sport1 is equal to $sport2." );
} else {
print ("$sport1 is not equal to $sport2.");
}
Outputs: Hockey is not equal to Soccer.
Also use <, >, <=, and >= operators to compare string values using ASCII code values. For Example
$sport1 = "Hockey"; $sport2 = "Soccer";
if ($sport1 < $sport2) {
print ("$sport1 is less than $sport2.");
} else {
print ("$sport1 is not less than $sport2.");
}
Outputs Hockey is less than Soccer.
A Full Example …
Consider the following HTML form element that sets the elements “first” and “second” of $_POST
<form action="" method="POST">
First Name: <input type="text" name="first">
Second Name: <input type="text" name="second">
</form>
Consider the receiving code as follows:
<html>
<head>
<title>String Comparison Results</title>
</head>
<body>
<?php
$first = $_POST["first"];
$second = $_POST["second"];
print ("First=$first Second=$second<br>");
if ($first == $second) {
print ("$first and $second are equal");
}elseif ($first < $second) {
print ("$first is less than $second");
}else{ //if ($first > $second)
print ("$first is greater than $second");
}
?>
</body></html>
This code will compare strings and state that the first is equal, less than, or greater than the second.
Above, since we wanted to code more than 2 branches in our application, we used if and else for the first and last and elseif for all others in between.
In the above, each Boolean expression will only be evaluated if all preceding Boolean expressions evaluate to false. Furthermore, the branch which will run is the first one from the top for which the Boolean expression evaluates to true. If and only if all Boolean expressions evaluate to false, the else branch will be run.
Notice the ordering of the clauses in the following example.
$opening = 9;
$lunchstart=12;
$lunchend=13;
$closing=17;
if ($hour < $opening) {
echo "Sorry, it is $hour and we open at $opening.";
} elseif ($hour < $lunchstart) {
echo "Good morning. It is $hour. ";
echo "We can help you until $closing, except ";
echo "lunch, from $lunchstart to $lunchend.";
} elseif ($hour < $lunchend) {
echo "Sorry, we are out to lunch until $lunchend. ";
echo "We close for the day at $closing";
} elseif ($hour < $closing) {
echo "Good afternoon. The time is $hour. ";
echo "Here to help you until $closing";
} else { //if ($hour <= 23) {
echo 'Sorry, we have gone home already. ';
echo "We will be back tomorrow at $opening";
}
Use an else clause with if and possibly one or more elseif clauses. This is to specify the statements to run when all the previous Boolean expressions evaluate to false.
Switch Statement
Use switch statements to run code depending on a set of discrete values, i.e., specific values as opposed to ranges of values.
switch ($rating) {
case 1:
$rated = "Poor";
print "The rating was $rated";
break;
case 2:
$rated = "Fair";
print "The rating was $rated";
break;
case 3:
$rated = "Good";
print "The rating was $rated";
break;
default:
print "Error: that rating does not exist";
}
In the above code, the value of $rating is accessed. If it is 1, the branch labeled case 1: will be run. In general, if the value is x, if there is a label case x:, then this will be the starting point to run code within the switch block. All case blocks are ended with a break statement, otherwise, the PHP interpreter will continue running code from the following case block.
Repetition
Scripts can use loop statements to repeat sections of code. This allows us to write more flexible scripts.
Using a for loop
Use a for loop to repeat a set of statements a specific number of times.
for ( $i = 0; $i < $max; $i++ ) {//The initialization
//Set of statements to repeat
}
When we try to access elements of a collection, such as an array, the foreach loop is easier to use than the for loop. The syntax is as follows:
foreach($collection as $item){
//perform an action on $item
}
When the collection is a dictionary, a collection of key/value pairs, the syntax is slightly different:
foreach($collection as $key => $value){
//perform actions on $key and $value
//the data should be organized such that
//$collection[$key] == $value
}
Usingthewhileloop…
Use the while loop to repeat a set of statements as long as a Boolean expression remains true.
while ($ctr < $max) {
//Set of statements to repeat
}
A while loop will repeat as long as the Boolean expression is true. If the expression initially evaluates to false, then the statements within the loop body will never run.
In order to avoid infinite looping, the statements in the while loop must lead to modifying the value of the boolean expression. In the example above, the value of $ctr must increase to eventually be greater than or equal to $max.
If the loop conditional test always true, then the loop will never end. This is an infiniteloop. This would consume resources on the Web server and possibly slow down other server activity.
PHP supports a set of Boolean operators you can use to create compound Boolean expressions. These may be used within an if statement or a while statement to specify more than one condition. For example, consider the following
while ($x > $max && $found != 1) {...}
BooleanOperators
PHP supports three logical test operators.
1. &&—theANDoperator. Example:
while ($ctr < $max && $flag == 0) {
Whenever either of these expressions is false, the loop will terminate.
2. ||—theORoperator. Example:
if ($ctr != $max || $flag == 0) {...}
Carries out the statements within the if statement, if either $ctr is not equal to $max or $flag, is equal to 0.
3. !—theNOToperator.Used to test whether an
expression is false. Example,
if (!$flag == 0) {...}
This statement is true when $flag is anything except 0.
The following example asks the user to guess a “secret” two-digit combination and uses Boolean operators. The Input HTML form uses the following to set pick1. A similar group sets a variable pick2.
…<font size=4> Pick a number from 1 to 9<br />
<?php
for($i=1;$i<=9;$i++)
print("<input type="radio" name="pick1" value='$i'>$i");
print("<br />Pick a second number<br />");
for($i=1;$i<=9;$i++)
print("<input type="radio" name="pick2" value='$i'>$i");
?></font>
AFullScriptExample
<html>
<head><title>Number Guess Results </title><head>
<body>
<?php
$pick1 =$_POST["pick1"];
$pick2 =$_POST["pick2"];
$combo1=5;
$combo2=6;
if (($pick1 == $combo1) && ($pick2 == $combo2)) {
print ("Congratulations you got both secret numbers $combo1 $combo2!");
} elseif (($pick1 == $combo1) || ($pick2 == $combo2)){
print ("You got one number right.");
} else {
print ("Sorry, you are totally wrong!");
}
print ("You guessed $pick1 and $pick2.");
?>
</body>
</html>
Theternaryoperator
The ternary operator evaluates one expression if the condition is true and another if the condition is false.
(condition?if true:if false);
It is normally used in assignment and sometimes directly for return/output values, e.g.,
$max=($a>=$b?$a:$b); print('The max is ' . ($a>=$b?$a:$b)); return ($a>=$b?$a:$b);
Summary
Use conditional statements to test for certain conditions and, based on the results of the test, to run specific script statements.
Loops expand the types of programming problems that you can solve and allow you to solve some programming problems much more concisely.
Use Boolean AND (&&), OR (||) and NOT (!) operators to build compound Boolean expressions.
As mentioned in the Hello PHP! post, the first questions regarding a coding language should be about syntax. As we saw, in the Hello World! program (see below), PHP delimits instructions with the semicolon (;), PHP delimiters are required in PHP files, and single quotation marks are accepted delimiters for string literals.
<?php
echo 'Hello World!';
?>
Objectives
To understand what PHP is and how a PHP script functions with a Web Server to handle Web Browser requests.
To learn what software and components you need to get started with PHP.
To create and run a simple PHP script.
To learn how to store and access data in PHP variables.
To understand how to create and manipulate numeric and string data/variables.
To review how to create HTML input forms.
To learn how to receive HTML form data with your PHP scripts.
HTML
HTML is used to provide web browser output.
PHP scripts may output any information format; we will output HTML to produce websites that work with web browsers.
How PHP Scripts are Accessed and Interpreted
Exploring the Basic PHP Development Process
The basic steps you can use to develop and publish PHP are:
if you are publishing online:
Create a PHP script file and save it to a local disk.
Use FTP to copy the file to the server.
Access your file using a browser, through server address yourserver/path/filename.
OR,
if you are testing on your local server (e.g., XAMPP):
Create a PHP script file and save it to the local server path.
Ensure that your server is up and running.
Access your file using a browser, through server address 127.0.0.1/path/filename or localhost/path/filename.
Given a script on a local server at c:\XAMPP\htdocs\app-one\start.php where c:\XAMPP is the installation path for XAMPP, htdocs is the server web root, the correct URL for this script would be
Online, htdocs is one of the usual web server root names… start here.
Creating a PHP Script File and Saving It to a Local Disk
You can use a number of different editors to create your PHP script files, e.g., Notepad, Notepad++, TextPad, Sublime Text.
The PHP script starts with a <?php tag and ends with ?>.
Between these tags is a single PHP print statement.
<?php
print("Hello, World!");
?>
The script must be placed in a folder that is under the server web root folder.
Accessing Your File Using a Browser
Given that your script is in a folder within the server document root, you must access it with the domain name of the server plus the correct path of the script relative to the server document root, e.g., given a script at c:\XAMPP\htdocs\app-one\start.php where htdocs is the server document root, and the server is local, the correct URL for this script would be
The output will always tell you the origin of the error. Running this file, you should see a “Parse error: parse error in /… on line 4”. Since there is no compilation process, all errors, even syntax errors occur when you run the program. This is your debugging output.
Embedding HTML in a PHP Script
One way to use PHP is to embed HTML within PHP files. For example:
<html> <head> <title>HTML With PHP Embedded</title> </head> <body>
<?php print ("<br> Using PHP is not hard<br>"); ?> and you can learn to use it quickly!
</body>
</html>
Note that to work properly, this must be a .php file, so that Apache sends the php script to the php interpreter.
Using Backslash (\) to Escape Characters within Strings
Sometimes you want to output an HTML tag that also requires double quotation marks. Use the backslash (“\”) character to signal that the double quotation marks themselves should be output: print (“<font color=\”blue\”>”);
The above statement would output: <font color=”blue”>
Of course, it would be wiser to use single straight quotation marks to avoid having to escape the double straight quotation marks… print (‘<font color=”blue”>’);
Using Comments with PHP Scripts
Comments enable you to include descriptive text along with the PHP script. Comment lines are ignored when the script runs; they do not slow down the run-time. Comments have two common uses:
Describe the overall script purpose.
Describe particularly tricky script lines.
<?php // This is a comment ?>
Can place on Same line as a statement:
<?php print ("Hello, World!"); //Output a line ?>
Another example:
<html> <head><title> Generating HTML From PHP</title></head> <body> <h1> Generating HTML From PHP</h1> <?php // Example script to output HTML tags print ("Using PHP has <i>some advantages:</i>"); print ("<ul><li>Speed</li>"); print ("<li>Ease of use</li>"); print ("<li>Functionality</li></ul>"); //Output bullet list ?> </body> </html>
PHP allows a couple of additional ways to create comments:
<?php phpinfo(); # This is a built-in function ?>
Multiple line comments.
<?php /* phpinfo() is a php function that is part of the base php language. It displays information on the PHP version being used and all configured extentions. */ phpinfo(); ?>
Using PHP Variables
Variables are used to store and access data in computer memory. A variable name is a label used within a script to refer to the data.
In PHP, for example:
$cost = 4.25; $months = 12;
Assigning New Values to Variables
You can assign new values to variables:
$days = 3; $newdays = 100; $days = $newdays;
At the end of these three lines, $days and $newdays both have values of 100.
The Names of Variables
You can select just about any set of characters for a variable name in PHP, but they must:
Use a dollar sign ($) as the first character
Use a letter or an underscore character (_) as the second character. Other characters should be alphanumeric.
Select variable names that make your code self-explanatory, e.g., $counter is more descriptive than $c or $ctr.
Combining Variables and the print Statement
To output the value of $x, write the following PHP statement:
print ("$x");
The following code will output “I would like to buy 6 apples.”
$num=6; print ("I would like to buy $num apples.");
The following code will output “I would like to buy $num apples.”
$num=6;
print ('I would like to buy $num apples.');
If you accidentally use a variable that has not been initialized (never was assigned a value), then it will have no value (called a null value). When a variable with a null value is used in an expression PHP, PHP may not generate an error and may complete the expression evaluation. For example, the following PHP script will output “x= y=4”:
<?php $y = 3; $y = $y+$x+1; // $x has a null value print ("x=$x y=$y"); ?>
Writing Complex Expressions
Operator precedence rules define the order in which the operators get executed. For example,
$x = 5 + 2 * 6;
The value of $x is either 42 or 17 depending on order of evaluation. Multiplication and division operations get executed before addition and subtraction. Therefore, the expression must be evaluated to 17.
PHP’s operator precedence rules are as follows, in order:
<html> <head><title>Expression Example</title></head> <body> <?php $grade1 = 50; $grade2 = 100; $grade3 = 75; //learning arrays will be very beneficial! $average = ($grade1 + $grade2 + $grade3) / 3; print ("The average is $average."); ?> </body> </html>
Working with PHP String Variables
Strings are used in scripts to hold data such as customer names, addresses, product names, and descriptions. Consider the following example, where $name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”:
$name="Christopher"; $preference="Milk Shake";
WARNING: Be Careful Not to Mix Variable Types
Be careful not to mix string and numeric variable types, unless this is your intent. For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”:
You can also use double quotation marks to concatenate directly, e.g.,
$firstname="John"; $lastname="Smith"; $Fullname = "$firstname $lastname"; //AND $Fullname2 = $firstname . " " . $lastname; //Have the same effect
Practical Functions for Strings
Function
Description
strlen()
Return the length of the string, e.g.,
$len = strlen($name);
trim()
Removes blank characters from the beginning and end of a string, e.g., $in_name = ” Joe Jackson “; $name = trim($in_name);
strtolower() and strtoupper()
Return the input string in all uppercase or all lowercase letters, respectively, e.g.,
$inquote = “Now Is The Time”;
$lower = strtolower($inquote);
$upper = strtoupper($inquote);
substr()
Return a part of the string, as specified, e.g.,
$part = substr( $name, 0, 5); //return first 5 chars
$part = substr( $name, 2); //return all chars from 3rd
PHP supports both numeric and string variables. String variables use different methods for value manipulation (for example, concatenation) than numeric variables do.
You can use HTML forms to pass data to PHP scripts. HTML form elements include text boxes, text areas, password boxes, check boxes, radio buttons, and selection lists.
PHP scripts can receive form element input values by using a PHP variable name that matches the one specified in the form element’s name argument.
PHP is a great language to develop server-side scripts for data-centric Web applications. PHP can run on all computers and most if not all commercial Web hosting services offer it as part of their platforms.
When studying any coding language, the first thing to learn is the correct syntax to write correct programs in this language. Are instructions separated by newlines or semicolumns? How do we declare variables? How do we set and get values from them? Let’s get started with PHP.
First things first, the development environment is important. Since PHP is a scripting language, we can use any text editor that has proper syntax highlighting for PHP to develop with this language. I like Sublime Text, but there are many editors that provide a great development environment for PHP.
Also part of the development environment is the runtime environment. To this effect, I suggest downloading and installing XAMPP.
Let’s get started
Now that you’ve installed XAMPP (I will assume a default installation on the C: drive of your Windows-run computer) and your favorite text editor, we will write a simple Hello World! program.
First, navigate to C:\xampp\htdocs. This is the root folder where the Apache server instance we will later run will fetch your Web resources. Select all files preinstalled in this folder and delete them. Now create a new file: index.php. In this file, paste the following code:
<?php
echo'Hello World!';
?>
Save your file and now, we will run this script.
Now, let’s start XAMPP: Go to the C:\xampp folder and run the xampp-control.exe program. On the line labeled Apache, click the “Start” button. The Apache label should turn to light green. If it does not, then you are likely to have a port conflict preventing Apache from starting. To find out which program this is, click on the Netstat button on the right.
Assuming Apache is running correctly, we will now run our Hello World! program by starting our favorite browser ant directing it to http://localhost/. You should see “Hello World!” displayed in the browser window.
To explain what’s going on, we have <?php and ?> tags delimiting the PHP code. The echo instruction will output the strings given to it as a parameter. In this case, we are providing the 'Hello World?' string literal.