PHP - Introduction - City of Bath College Moodle

advertisement
PHP
Background
The “PHP Hypertext Pre-processor” (PHP), formally known as Personal Home Page, is a
programming language that allows web developers to create dynamic content that can also
interact with databases, although it can be used simply as an addition to HTML when creating
web pages. When using databases, PHP can produce a web page based on a SQL (Structured
Query Language) query.
PHP is basically used for developing web based software applications. Examples of software
applications using PHP include content management system (CMS) such as Wordpress, which
allow websites/blogs to be created with a MySQL database at the backend. Other CMS’s
which can be used instead of WordPress include Joomla and Drupal. The CMS’s can be easily
downloaded and installed; web hosts often provide a free CMS which account holders can
install.
PHP can, for example: handle forms, collect data from files, save data to a file, email and
send data, return data to the user. Using PHP, you can restrict user access to web pages.
3 ways of inserting PHP into the HTML source code:
<?php PHP code goes here ?>
<?
PHP code goes here ?>
<script language="php"> PHP code goes here </script>
Testing PHP
Install a testing server, database and PHP
software to test PHP scripts without needing
to go online. Setting up a web server is
simple if using installation packages such as
WAMP or XAMPP (MAMP and LAMP for Apple
and Linux). For example installing the WAMP
server provides a testing server in the www
folder inside the WAMP folder on the C: drive
Variables $
All variables in PHP are denoted with a
leading dollar sign ($). Variables do not need
to be declared (i.e. as an integer, a string, a Boolean, etc.). Variable can be just stated, e.g.:
$a = 10;
$name= "Smith";
$number=45;
echo $name, $number
Echo()
Echo is a language construct and therefore may be used with or without parentheses
(brackets). Echo outputs one or more strings, or variables; it can write the value of the string
or variable, including HTML tags.
echo "This is a better place"
echo ("This is a better place")
echo ("This is a <b>better</b> place")
If you want to pass more than one parameter to echo, the parameters may be separated by a
comma:
echo "This is a better place"," over ",$number," degrees heat. "
Separating each parameter on a separate line has the same effect:
echo "This is a better place",
” over “,
$number,
” degrees heat.”
Note that PHP does not recognise whitespaces unless specified, e.g.” “
Comments
/* This is a multi
line comment used
by PHP
*/
# This is a comment on a single line
// This is a comment on a single line
Semicolons (;)
Statements in PHP are expressions and are ended by a semicolon (;). However a single
statement or the end statement in a list doesn’t need it. It’s better to use them nevertheless,
otherwise the script may not work.
echo
echo
echo
echo
echo
'<br/>';
"Hello ", $name, ". You have ", $number, " minutes.";
'<br/>';
"This is a better place";
'<br/>'
Expressions are combinations of tokens:
The smallest building blocks of PHP are the simplest tokens, such as numbers, strings,
variables, constants, and the special words that make up the syntax of PHP such as if, else,
while, for and so forth.
Print()
The print() function outputs one or more strings.
Like Echo(), the print() function is not a function, so parentheses are optional. Print() is
slower than Echo()
Exercise: Experiment with PHP using variables, language
constructs such Echo
Copy and edit lines of PHP code below and examine how the same
output can be created using different approaches, for example with
or without brackets. HTML can be included in the statements; PHP
knows to read it as HTML. Experiment using your own examples.
<?php
$name = "Smith";
$number = 45;
echo $name, $number, "<br/>";
echo "$name ", "$number", "<br/>";
echo "Hello ";echo $name; echo ". You have ";echo $number; echo "
minutes.";
echo '<br/>';
echo "Hello ", $name, ". You have ", $number, " minutes.";
echo '<br/>';
echo "Hello $name. You have $number minutes.";
echo '<br/>';
echo "This is a better place";
echo '<br/>';
echo("This is a better place");
echo '<br/>';
echo "This is a better place - over ",$number," degrees heat.<br/>";
echo ("This is a <font size='7'><b>better</b></font> place<br/>");
echo "This is a <font size='7'><b>better</b></font> place<br/>";
$word = "discovery";
print("The first statement<br/>");
print("The first $word<br/>");
print("Another statement <br/>followed by a line break.<br/>")
?>
Save your examples.
When speech marks are nested in each other, it will be necessary to use single speech marks
inside the doubles so they are not mixed up.
Concatenation
The concatenation operator (.) joins string values together.
Try these examples, make up your own examples.
echo “A period links the first statement “.” to the second<br/>”;
echo “Lots can be linked “.”together ”.”like “,”this<br/>”;
$a=31;
$b=”July”;
echo $a.”st ”.$b;
Save any work or examples
Gettype
e.g.
<?php
$age="44 years";
gettype ($age, "integer");
echo $age;
?>
The variable age has been changed from a string “44 years” to an integer 44.
Gettype finds out the data type of a variable, e.g. integer, Boolean, double/float, and string.
Exercise - try these examples
$age=44;
echo gettype ($age);
echo '<p/>';
$name="Smith";
echo gettype ($name);
echo '<p/>';
$number=3.14;
echo gettype ($number);
?>
Settype
e.g.
<?php
$age=”44 years”;
echo settype ($age, integer);
?>
Settype sets the data type of a variable, e.g. integer, Boolean, double/float, and string, using
the initial characters.
Exercise - try these examples
$age=44;
echo gettype ($age);
echo '<p/>';
$name="Smith";
echo gettype ($name);
echo '<p/>';
$number=3.14;
echo gettype ($number);
?>
Save copies of your files
The $_POST Variable
The predefined $_POST variable is used to collect values from a form sent with
method="post".
Information sent from a form with the POST method is invisible to others and has no limits on
the amount of information to send.
Exercise - creating a form and applying PHP to output the form
Create a HTML web page, save this as testform.html and create a form between the
<body> tags:
<form action="welcome.php" method="post">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit">
</form>
Create a new file. Insert the following in between the <body> tags and Save this as
welcome.php:
<html>
<head>
<title>Test form</title>
</head>
<body>
Welcome <?php echo $_POST["name"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Open welcome.html and test it.
Save copies of your files
The PHP $_REQUEST Variable
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and POST
methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>!<br>
You are <?php echo $_REQUEST["age"]; ?> years old.
Array
An array can hold many values under a single name, and you can access the values by
referring to an index number.
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
$cars=array("Volvo","BMW","Toyota"); or the index can be assigned manually:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates an indexed array named $cars, assigns three elements to it,
and then prints a text containing the array values:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]
. ".";
?>
Date
Here is an example of a date using PHP. The date is taken off the server on which the PHP
page is hosted, not on the client PC. You may need to set the default timezone (see next
examples).
<?php
echo date("d/m/Y") . "<br>";
echo date("d.m.Y") . "<br>";
echo date("d-m-Y");
?>
Here are some of the characters used:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional
formatting
Other characters for the date include:
j - The day of the month without leading zeros (1 to 31)
F - A full textual representation of a month (January through December)
Y - A four digit representation of a year
e.g.
<?php
echo "Today is ", date('j F Y');
?>
A list of the different paramters for the date() function can be found from:
http://www.w3schools.com/php/func_date_date.asp
date_default_timezone_set()
The date_default_timezone_set(timezone) function sets the default timezone used by
date/time functions. This may be required if the phpinfo.php shows this.
Here is a link to time zones: http://www.php.net/manual/en/timezones.php
e.g. Europe/London
<?php
date_default_timezone_set("Europe/London");
echo date_default_timezone_get();
?>
Exercise
Create some PHP scripts for a web page using the date() function. Try to format it so it is
readable.
e.g.
<?php
echo "The time is "; echo date("H:i:s");
echo " and the date is ", date("j F Y");
echo
echo
echo
echo
echo
echo
?>
"<p>";
"The time is "; echo date("H:i:s");
"<p>";
" and the date is ", date("j F Y");
"<p>";
date("l jS \of F Y h:i:s A");
Save copies of your files
PHP Conditional Statements
Statements such as “if”, “else” and “switch” are used to perform different actions depending
on the outcome of a comparison between variables.
Here are some logic statements:
if
if...else
if...else if
switch
executes some code only if a specified condition is true
executes some code if a condition is true and else something else if false
selects one of several blocks of code to be tested/applied
selects one of several listed blocks of code to be applied
The double == is a comparison operator which means “eqal to”
A triple === is like == except it means ‘identical to’
Other comparitors are :
Example
!= not equal
! not
> greater than <= less than or equal
&& and
|| or
<?php
$name='Adam Smith';
if ($name=='Adam Smith')
{
echo 'You\'re Adam Smith';
}
else
{
echo 'You are not Adam Smith';
}
?>
The backslash “\” is an escape character which means the character after the backslash is
treated as a character and not as part of the PHP language construct; note that single, not
double, quotes are used around the text.
Exercise
Try some conditional statements, changing the variables and testing:
<?php
$name='Adam Smith';
$age=50;
if ($name=='Adam Smith' && $age==49)
{
echo 'You\'re Adam Smith';
}
else
{
echo 'You are not Adam Smith';
}
?>
Try changing the code above, such as changing the age to 50, or removing the backslash
character in “You’re”.
Here is an example using if and else:
<?php
$name='Jon';
$age=80;
if ($name=='John'){
if ($age>=45 && $age<=60)
{
echo $name,' you\'re aged between 45 and 60 <p>';
}
else if ($age>=60)
{
echo $name,' you\'re over 60 <p>';
}
else{
echo $name,' you\'re age is below 45 <p>';
}
}
else{
echo 'You\'re not John!';
}
?>
In the above code, the if and else statements check to see if the name of the person is John,
then checks to see what age is John and returns the correct answer. If $name is changed to
someone else, e.g. Joe, then a statement will specify John is no longer the person. If the age
is changed, e.g. to 20, then the conditional statement will check and return a different
answer.
Save copies of your files
String to lower case
In the example above, a form input may give the name as John in all lower case (e.g. john)
but the script will not work because “john” and “John” are different variables, even though
they mean the same person.
To avoid accidental differences in the case and to yield the correct result, use the statement
strtolower(), i.e. strtolower($name) converts “John” to “john” (all lowercase)
If ($name == ‘john’) becomes
if (strtolower($name)=='john') etc…
Further information on PHP
http://www.tutorialspoint.com/php/php_variable_types.htm
http://www.w3schools.com/php/default.asp
http://www.codecademy.com/tracks/php
http://thenewboston.org/list.php?cat=11
http://www.php.net
Download