PHP Guide (Abridged)This is a
very abridged introduction to the basics of PHP, touching on some of the fundamentals to building a PHP file. Unlike HTML or XHTML, PHP is a
server-side programming language. PHP is typically focused on communicating with databases (typically mySQL, among others) to load and handle data for the page before the page is generated. The PHP file extension is exclusively
.php.
Getting StartedSource filesSource files are basically the PHP page itself. However, you may also use HTML pages as a functioning PHP page in some cases, though it may prove to be a bad practice to some.
Any PHP content should be surrounded an opening tag (
<?php) and a closing tag (
?>). For an exclusively PHP file (.php), these should appear at the top and bottom of the document, respectively.
In the event of a PHP-enabled HTML page, the most common uses I've seen of PHP being included in the page include
Session handlers and
Inclusion of other pages into that page.
For Session handlers, the PHP opening tag should appear at the top of the file with no lines above it, thus forcing the PHP source to be parsed prior to the HEADERs being sent.
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
For inclusion of other pages into a PHP-enabled HTML page, the PHP opening tag can appear anywhere you want the content to appear. You would simply use an
Include function. This function will be explained later as it is often used and necessary to keep files clean.
<body>
<?php include('content-pages/body.html'); ?>
</body>
Some BasicsHere are a few things you absolutely should know before starting to attempt PHP. Every line of processed code is read as-is, until it hits an end character "
;" which tells the processor to stop and begin a new line. The handler does not recognize line breaks as a means of separating code and will read it as if it were on a single line - causing a fatal error and preventing the page from being processed.
Also, the methods of displaying content I use most often are:
echo "string";
echo("string");
echo $variable;
print "string";
print("string");
print $variable;
From what I've heard, this is typically a coder's preference, because there isn't always a noticeable difference in using either of them.
IF-ELSEIF-ELSE (conditional) statements are a must-have for PHP coders. IF this statement is true, do this. Otherwise, (else)IF this statement is true, do this. Otherwise, do this.
function findValue($a)
{
if ($a == 2)
{
return "WIN";
} elseif ($a == 5)
{
return "ALMOST";
} else
{
return "FAIL";
}
}
findValue(2); // returns "WIN"
findValue(5); // returns "ALMOST"
findValue(1); // returns "FAIL"
Another big one to mention is the difference between single quotes (
') and double quotes (
"). While double quotes generally mean a string of text, they also enable the use of inclusive variables and special characters, such as \n (newline) and \r (carriage return). Single quotes are typically used for numbers or within SQL statements to denote data to be searched.
$text = "hello";
$otherText = "$text world";
echo $otherText; // displays "hello world" on page
VariablesPHP variables are set much like other languages, but is prepended with a leading '
$' to signify it is a variable. These variables can either be Local or Global, depending on how you need them in your use. Further, variables can be given a TYPE to limit what type of data can be saved to that variable. However, PHP does not require TYPE declaration and automatically gives variables a TYPE when set, based on the data saved. The default is a STRING.
Setting VariablesW3Schools wrote:
Naming Rules for Variables
- A variable name must start with a letter or an underscore "_"
- A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
- A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)
Standard naming etiquette says spaces should be removed altogether and the first letter of each word following the first word should be capitalized. This method will be utilized in this guide.
PHP variables can be set using either
$textVariable = "Data to save";
$numericVariable = 1;
or
var $textVariable = "Data to save";
var $numericVariable = 1;
though prepending 'var' is not necessary for setting the variable.
It is also possible to set variables using a simplified IF-ELSE statement
$a = 1;
$textVariable = ($a == 1) ? "WIN" : "LOSE";
In this case, it checks if $a is equal to int(1). If this is
true, the variable is set to "WIN." Otherwise, the variable is set to "LOSE."
Note that while it is expected to set a numeric variable without quotes, it is required to surround strings of data in single (
') or double (
") quotes or it will cause a fatal error.
Variable TYPEsVariable TYPEs, though unnecessary for setting most PHP variables, since they're generated automatically based on the content received, can be useful in maintaining integrity of values. This is especially true when calling data from a database where numbers may be saved and retrieved as strings but need to be read as a number.
For the purposes of this guide and being an abridged version, the only TYPE we will worry about is the INTEGER. As stated, it may be necessary to convert a string to a number in any number of cases, so the easiest method I've seen is to simply use the following:
$textVariable = "1";
$numericVariable = (int) $textVariable;
or
$numericVariable = (int) "1";
By including the (int) or (integer) infront of the content to be forced into INTEGER format, it actually changes the content to reflect a numeric number and will return as int(1) in the example. This method is called
Casting.
Local VariablesVariables are set in the scope by which they are expected to be used. In the case of local variables, these variables are generally called from within functions and are disposable, which is to say they're only useful when data is passed through a function and into the variables. For instance, the following example sets a local variable.
function helloWorld()
{
$variable = "Hello";
echo $variable;
}
helloWorld();
echo $variable;
The first instance of
echo would return a value of "Hello" while the second instance would return a NULL value. This demonstrates how data saved in a local scope is only available within the limits of its scope.
Global VariablesGlobal variables can be called throughout PHP files (granted they're within the same file throughput) by using the
global identifier, declaring the variable outside of a local scope, or by using the $GLOBALS array.
$variable = "Hello";
echo $variable;
This will cause "Hello" to be displayed on the page.
$variable = "Hello";
$anotherVariable = "Goodbye";
function helloWorld()
{
global $variable;
$byeVariable = $GLOBALS['anotherVariable'];
$worldVariable = "World";
$variable .= $worldVariable;
$variable = str_replace("Hello",$byeVariable,$variable);
}
helloWorld();
echo $variable;
This should cause "GoodbyeWorld" to be displayed on the page. Note the use of the $GLOBALS array - variables are treated as array keys.
OperatorsOperators are used when changing the value of variables and in conditional statements. At this point it is worth pointing out that a '
.' in PHP signifies a combination of elements.
W3Schools (Abridged) wrote:
Arithmetic Operators - + => Addition => x=2; x+2; => x=4
- - => Subtract => x=2; 5-x; => x=3
- * => Multiply => x=4; x*5; => x=20
- / => Division => x=15; x/5; => x=3
- % => Modulus => x=5; x%2 => x=1
- ++ => Increment => x=1; x++; => x=2
- -- => Decrement => x=1; x--; => x=0
[Variable] Assignment Operators - = => x=y => x=y
- += => x+=y => x=x+y
- -= => x-=y => x=x-y
- *= => x*=y => x=x*y
- /= => x/= => x=x/y
- .= => x.y => x=x.y
- %= => x%y => x=x%y
Comparison Operators - == => is equal to
- != => is not equal
- <> => is not equal
- > => is greater than
- < => is less than
- >= => is greater than or equal to
- <= => is less than or equal to
Logical Operators - && => and => x=6; y=3; (x<10 && y>1) returns true
- || => or => x=6; y=3; (x==5 || y==1) returns false
- ! => not => x=6; y=3; !(x == y) returns true
FunctionsSince functions have already been used within the guide, it seems necessary to include their basic structure in this guide. I feel the most effective way to show this to a novice is to demonstrate the creation of functions while also touching on a few library (included with PHP installs) functions which are used frequently.
Creating your own functionFunctions all follow the same basic structure, regardless of what they end up doing within.
function functionName($data)
{
/** This is where you would include
* all of your fantastic, original code
*/
}
functionName();
functionName('this will be passed into $data for use within the function');
All functions begin with the 'function' identifier. The function naming dynamic generally follows the same standard of captalization as variables, but is typically only alphabetical. The $data within the parenthesis is optional, whereas the parenthesis are not. When you call the function, any variables named within those parenthesis will both be
expected and set locally to their respective values as per the function's call. Because these variables are required (disregarding them will cause an error), you may set a default.
function functionName($data=null)
{
/** This is where you would include
* all of your fantastic, original code
*/
}
functionName();
functionName('this will be passed into $data for use within the function');
This way, the function will already have a value for $data, though it will be overrode by any data passed through the function. This function would be called using either of the two methods shown at the bottom of either example.
Frequently Used Library FunctionsThe PHP library has a huge selection of functions already built in which can be found at
http://www.php.net. Here are a few commonly used functions with a short explanation of their use.
str_replace($needle,$replacement,$haystack);
str_replace("happy","sad","What a happy guide!"); // returns What a sad guide!
This is the String Replacement function. It works by finding the
Needle in the
Haystack and replacing it with the
Replacement.
include('file location');
include('../filesToInclude/necessary.html');
The include function basically places the contents of a page into another page at the point where the function is called. The file location
must be within your domain, for safety reasons. Therefore, there should never be a "http://" or "www.domain.com" anywhere in there. This is particularly useful when using a common PHP file among many PHP pages. Rather than having duplicates of a function on every page, you can simply
Include a page containing that function and it will be processed as if it were always a part of that page.
It's worth mentioning that in PHP, the "
.." is regarded as one layer up in respect to the current directory. So if a file is in
http://www.runevillage.com/files/secrets/ and you call "../file.html", it will look for "/files/file.html". In the case of only using "/file" it should look for "http://www.runevillage.com/file.html."
switch('example')
{
case 'text':
echo "Text case";
break;
case 'example':
echo "Hello World";
break;
case '':
default:
echo "What";
break;
}
The switch function is considered to be slow, but is utilized extensively on RV as the best method of deciphering page content. Within the switch's parenthesis is the data passed through the switch - it is typically a variable with a string value. Each case looks for the processed string to be equal to the value within the single quotes while the "break;" is used to stop the PHP code within that case to flow over. In the last case, the lack of a "break;" shows that this behavior should be used as both the default and whenever the processed data is an empty string.
header("Location: http://www.RuneVillage.com/");
This function sends a header to the browser basically telling it where it should be. If the page happens to not be the specified location, you're quickly redirected to the appropriate page. This is useful for limiting access to pages and acting as redirects within PHP codes incase of user data errors.
Further InformationFor further information, I would suggest checking both
http://www.w3schools.com/php and
http://www.php.net as they're comprehensive and show standards and often have examples of function uses.
Special ThanksRazick - Additional information / Technical jargon