Gaming Nation
Welcome to Gaming-Nation Guest. We are developing more things each day. Come help out the community. Join today!

PHP In A Not-So-Nutshell

View previous topic View next topic Go down

PHP In A Not-So-Nutshell

Post by Hesitate on Sat Jul 14, 2012 4:30 pm

PHP In a Not-So-Nutshell... Created by KnightMaire

NOTE: Due to HTML, Line breaks in examples are meant to be shown
as <br />. I have went through this tutorial and changed
what i noticed, but if i missed one, point it out to me.


Table of Contents:



Introduction

PHP is a universal website programming language famous for the speed in which it can easily create web applications.
While being the most popular also means it is the least secure. Make sure to use safe practices when dealing with input.
PHP currently is a recursive acronym for "PHP: Hypertext Preprocessor" although this was retrofitted from its first acronym "Personal Home Page". Although this scripting language is more commonly known in web applications from ".php" pages and such, it can be used as a machine language, you can visit php.net to learn more about it.
I have been working with PHP for the past 4-5 years and hope to pass a snippet of my knowledge unto you.
Enjoy. Smile


Declare PHP

The first thing to know is how to declare a block of PHP code:
Code:
<?php // Starts PHP

// Ends PHP
?>

Simple enough... however, the extremely common shortcut used to do the same thing is:
Code:
<?
// differs from <?php

?>


Print to Page Part 1

In order to print something to the page, you can use "echo" and "print".
They both do the same exact thing:
Code:
<?
echo "This is printed ";
print "to the page.";
// Notice the semi-colon after the line
?>

The echo is the more commonly used between the two.
Also make sure that every line is ended with a semi-colon. The
semi-colon tells the PHP parser to end the current action and move on to
the next. The only exception to this would be the curley braces "{" and
"}" which hold blocks of code.

Although those two are on two different lines, they are still displayed
as on one line. This is because everything between the quotations are as
you would type it in something like NotePad.

If you want it to appear on two separate lines, use the line break in HTML:
Code:
<?
echo "This is now on <br />";
echo "two separate lines.";

// Simplified:
echo "This is now on<br />
two separate lines.";
?>


Comments

As with any other programming language, PHP includes a couple formats where you can comment and annotate your codes.
There are three popular types of comments:

The line and pound comments:
Code:
<?
// This entire line will be commented out.
# This pound does the same exact thing.
?>

As explained in the comments above, both the line and the pound comments achieve the same goal.

The block comment:
Code:
<?
/* Everything inside
the asterisks are
considered comments */
?>

As stated above, everything that you put inside the asterisks will be commented and won't appear onto the page.


Variables

Variables are strings that can contain information. If you have every
taken a basic course in algebra, you will remember variables. If someone
had asked you what y equaled in the equation y=5x when x was equal to 2
(x=2), you'd know the answer was 10. In this instance, the "x=2" is the
variable declaration, where "x" is the variable and "2" is the
declaration (set value).
It is a similar method in PHP, except PHP variables can hold numbers as
well, but also letters, boolean (true/false), and arrays (we'll
get into arrays later).

In order to call and/or declare a variable, prefix the string with the dollar sign ($):
Code:
<?
$myVar = "apple";
echo $myVar;
// In a sentance:
echo "My favorite fruit is the " . $myVar;
//Notice the period
?>

In the example above, I set "apples" to the variable $myVar. From then
on, whenever I reference $myVar, I mean "apples". The output above would
be "My favorite fruit is the apple".
The period in that example performs a concatenation (add on).
It is very similar to JavaScript's "+":
Code:
document.write("My favorite fruit is the" + "apple");

When a variable is a number (ie: $myVar = 5;) you can use increments to increase (or decrease) its value.
In order to do this, you use the ++ or -- suffixes:
Code:
<?
$myVar = 5;
// Increments
$myVar++;

// De increments
$myVar--;
?>

By default, the increment is by 1. Therefore, if we were to echo $myVar after the increment, it would become 6 or 4.
The increment interval can be changed by adding a number:
Code:
<?
$myVar = 5;
// Increments of 5
$myVar++5;
?>

If we were to echo out the variable then, we would get 10.

To see the last sections in action, the [Video Tutorial].


Print to Page Part 2

There are two other functions that PHP uses to print things to the page.
sprintf() - prints to the page with more security.
print_r() - prints the characteristics of a variable onto the page.

The sprintf() function provides a more secure way of printing variables
to a webpage because it is harder to have it injected (unwanted input
that compromises PHP code) than echo or print.

Code:
<?
$var1 = "apples";
$var2 = "bananas";
sprintf("My favorite fruits are %s and %s.",$var1,$var2);
// Output: My favorite fruits are apples and bananas.
?>

In this sprintf() function, the %s refers to the variable inside the
parameters. The first %s references the first variable $var1 and the
second %s references the second variable $var2... and so on.
%s is the sprintf() operator for strings.

NOTE: The %s is one of many inputs for the sprintf() function. To learn the others, search for sprintf().


The print_r() function is a troubleshooting and debugging tool. It will display the characteristics of a variable.
Mostly used to view how a variable is storing array information. We'll get into arrays later.
Code:
<?
$var1 = "Regular String";
$var2 = array("apples","bananas","tomatoes");
print_r($var1);
echo "<br />";
print_r($var2);
?>

The output will look like:
Code:
Regular String
Array ( [0] => apples [1] => bananas [2] => tomatoes )

As you see, the first variable is displayed as expected.. however the
second variable, which is an array, is displayed with all the keys and
values that are stored in that array.
print_r() is a useful tool when handling array information that is
constantly changing, and want to know if it is being stored correctly.


Conditional Statements

A conditional statement is a command that compares two or more arguments
and executes a certain command depending on if that condition is true
(or false).
There are three types of conditional statements: The if, if..else, if..elseif, and the inline if.

The if statement:
Code:
<?
$var1 = 5;
$var2 = 10;
if($var1 < $var2){
echo "$var1 is less than $var2";
}
?>

This conditional will compare to see if $var1 is less than $var2. Think about this as talking.
If the first variable is less than the second variable, then echo this.

The if..else statement:
Code:
<?
$var1 = 5;
$var2 = 10;
if($var1 < $var2){
echo "$var1 is less than $var2";
}else{
echo "$var1 is not less than $var2";
}
?>

If the first variable is less than the second variable, then echo this, otherwise echo this.

The if..elseif:
Code:
<?
$var1 = 5;
$var2 = 10;
if($var1 < $var2){
echo "$var1 is less than $var2";
}else if($var1 > $var2){
echo "$var1 is greater than $var2";
}else{
echo "$var1 is not less than or greater than $var2";
}
?>

If the first variable is less than the second variable, echo this,
but if the first variable is greater than the second variable, echo
this... otherwise, just echo this.


The inline if is an if..else statement declared to set a variable within one line.
The syntax (how to write) this is:
Code:
$variable = (<conditional>) ? <if TRUE> : <if FALSE>;

The "?" starts the true false recognition and the ":" acts as the "else" in the if..else statement.

Example:
Code:
<?
$myVar = "bananas";
$output = ($myVar == "apples") ? "likes" : "does not like";
echo "This person $output apples.";
?>

This would output: This person does not like apples.

You can view the conditional video tutorial HERE.


Loops

In PHP, whenever you need to execute the same lines of code over and over again, use loops.
There are three types of loops I will go over: while, for, and foreach.

The while loop:
Code:
<?
$var1 = 5;
$var2 = 10;
while ($var1 < $var2){
echo "This will never stop printing...<br />";
}
?>

That while loop checks to see if the first variable is less than the
second variable, if it is true, then it will continue to loop. Since it
does not change it will continuously loop off towards infinity.
In order to stop this, you will need to increment that first variable (See Variables).
Code:
<?
$i = 5;
$var2 = 10;
while ($i < $var2){
echo "This is line: $i.<br />";
$i++; // New line
}
?>

Now this time, every time the loop runs, the variable $i gets
increased... until it gets to 10, then the loop will finally stop. If
you were to go as far as this, you minus well use the for loop.

The for loop is a loop that lets you declare a variable, compare, and
set an increment to the variable all inside the parameters.
The syntax for the for loop is:
Code:
for(<variable>,<comparison>,<increment>){ <code> }

Example:
Code:
<?
for( $i = 0, $i < 10, $i++){
echo "This is line: $i.<br />";
}
?>

This for loop will print "This is line: xxx." ten times down the page.

The foreach loop is a loop that is mostly dealt with using arrays.
What this loop does is cycle through an array and execute a code for each part of that array.
Code:
<?
$myVar = array("apples","bananas","tomatoes");
foreach($myVar){
echo "I like: $myVar.<br />";
}
?>

This loop will go through the array and print each part.
This foreach is good loop for creating a directory listing of files on your server:
Code:
<?
$files = glob("./images/*"); // Described below
echo "Files in /images/ directory:<br />";
foreach($files as $file){ // "as" described below
echo "<a href='./images/$file'>$file</a><br />";
}
?>

The first thing that is new here is the glob(). This grabs all the files from the folder you select and places it in an array.
The second thing is the "as". You got lucky on this one because I was
lazy and didn't feel like changing the variable $files to $file. That is
what the "as" clause does, it temporarily changes the variable to one
you specify. Notice in the loop i did not use $files but used $file.
This was a semi-automatic change for me adding the "as" in there. This
didn't make sense to me: "for each files..." so i just changed it so it
would be "for each file"...

Anyways... nice little educational detour.

If there is ever a situation and you need to stop the loop prematurely, you can use the break function.
The break function breaks out of the loop.

This example is a little redundant because you can use the for loop, but this is just an example.
Break out of loops:
Code:
<?
$i = 0;
$max = 999;
while ($i < $max){
echo "This is line: $i.<br />";
if($i == 10){
break;
}
}
?>

In this instance, the while loop will loop until $i equals 999. However,
the if tells the loop to stop when $i equals 10 using the break.
You will also notice this break is used in switches to stop the current case.


Switches and Cases


A switch in PHP is what you would think of it when you think of
switches. It turns on, or it turns off. Which switch turns on depends
directly on what is placed inside the parameter.
Code:
<?
$myVar = "apples";
switch($myVar){

case "apples":
echo "I like apples.";
break;

case "bananas":
echo "I like bananas.";
break;
}
?>

The switch in the example above uses the $myVar as a switch reference
(apples) and then goes down the case list and checks to see if one
matches. If it found a match, it would echo appropriately. Now you may
be thinking, what if it doesn't match any of them?
To maintain good practice, you should always use the default case:
Code:
<?
$myVar = "apples";
switch($myVar){

case "apples":
echo "I like apples.";
break;

case "bananas":
echo "I like bananas.";
break;

default: // New case
echo "I don't like apples or bananas.";
break;
}
?>

So now if you ever have a switch evaluate something that isn't one of the cases, it will always execute the default case.
In this instance, if we changed $myVar to equal "tomatoes", the output would be: I don't like apples or bananas.

View the video tutorial on switches
HERE. You may want
to stop and read the next section when I start talking about functions.


Functions

I probably should have covered this topic sooner, but one section flowed
into another, but its due time for me to interrupt and get this in
here. This is one of the most important topics to cover, for if you work
in PHP, you will always use these.

A function is a block of code that is labeled by a function name. When
that function name is called, the code inside that function will
execute.

Example:
Code:
<?
function newFunc(){
echo "This function prints to the page.";
}
newFunc();
?>

In the code above, the function name (newFunc) is prefixed by "function"
so the PHP parser will know that the function name is a function to
begin with. Everything inside the parenthesis are the parameters of the
function. Inside the braces is the code that the function will execute
when called. and the last line "newFunc()" is calling the function.
To change this code around, there is a term in PHP where you just "return" something back to where it is being called.
If we echo the newFunc and return just what is supposed to be echoed, it would look like this:
Code:
<?
function newFunc(){
return "This function prints to the page.";
}
echo newFunc();
?>

When you want to place something dynamic into the function, you place
what is called a parameter. If you remember what I mentioned previously,
everything within the parenthesis are a parameter.
You can set a new variable withing the function's parenthesis which will
be the placeholder for the parameter inside the function.
Take a look at this example, it is somewhat tough to explain:
Code:
<?
function newFunc($param){
echo $param;
}
newFunc("The parameter goes here.");
?>

If you take a look at the function call, inside the parenthesis there is
a string. When the funciton is called, that string will now be placed
into the variable $param which is used inside the function. Therefore
when we simply echo the $param, whatever we placed in the
function_call's parenthesis will be displayed on to the page.
I go a little bit more in depth into functions in my
Video Tutorial.
When you watch that video, go back and watch the switches one where you
may have left off.


Arrays

In previous sections I have been using arrays an an example, but I have
not really explained them to you. Arrays is one of the harder topics to
understand (and to explain). However, once you understand the concept,
it is a useful tool.

*Think of an array as a cluster of values that all branch off from one variable.

Let's a vision a tree. The variable is the trunk, and the array is where
the trunk splits off to become a branch. Another array is when the
branch splits into a twig. This is actually considered a
multidimensional array, where there's an array within an array... but
we'll cover that later. There are three types of arrays: The numeric,
associative, and multidimensional arrays.

The numeric array is the simplest to understand. Using the print_r() example:
Code:
<?
$var1 = "Regular String";
$var2 = array("apples","bananas","tomatoes");
print_r($var1);
echo "<br />";
print_r($var2);
?>

If you remember the output looked like:
Code:
Regular String
Array ( [0] => apples [1] => bananas [2] => tomatoes )

Taking a look at this, You can see apples is the first value, bananas the second, and tomatoes the third.
If you want to call the tomatoes part of the array, you call the value
it is associated with. When using arrays, you will use square

brackets "[" "]".
Code:
<?
$var1 = array("apples","bananas","tomatoes");
echo $var1[2];
?>

The output would be tomatoes.

NOTE: In programming, the first value always starts with ZERO!

In an associative array, each array value is associated with a key (usually a string).
Let's change the print_r() example around so become a associative array:
Code:
<?
$var1 = array(
"first" => "apples",
"second" => "bananas",
"third" => "tomatoes"
);
print_r($var1);
echo "<br />";
echo $var1["first"];
?>

The output is:
Code:
Array ( [first] => apples [second] => bananas [third] => tomatoes )
apples

As you see from the print_r(), instead of each value being assigned to a
numeric value, its now assigned to first, second, and third. When "echo
$var1" is called, it chose the value associated with "first". Therefore
you see it printed apples to the page.

Now that we have went over what an array is, a multidimensional array is simply and array which has another array as its value.

Multidimensional array:
Code:
<?
$var1 = array(
"apples",
"bananas",
array("tomatoes","carrots","broccoli")
);
print_r($var1);
echo "<br />";
echo $var1[0]."<br />";
echo $var1[2][1]; //Notice second bracket
?>

I spread the array out so it was easier to understand.

Notice the last echo, where we call the third in the array, then the second in that array.

Take a look at the output, more specifically the print_r():
Code:
Array ( [0] => apples [1] => bananas [2] => Array ( [0] => tomatoes [1] => carrots [2] => broccoli ) )
apples
carrots

So the last echo selected "2" in the first array, which is associated
with the second array. Then from that second array, "1" was selected. In
the second array, the "1" is associated with "carrots".

Please note that the POST and GET methods are arrays themselves.
I don't have a video tutorial for arrays because I find them the most difficult to talk about.

GET an POST Methods

The GET and POST methods are both form processors.
I'll start with the Get method.
Have you every been to a website where after the page name you see a question mark with something after it?
Example:
Code:
website.com/news.php?article=1

In this instance, the page is using the URL to grab data to use. After
the parenthesis, notice how it looks similar to how a variable is
assigned: page.php?=

In order to grab this, use the GET method:
Code:
<?
$output = $_GET['article']; // Since article is the variable name in the URL.
//Notice the ['article']. Its part of an array.
echo $output;
?>

The output will show "1" on the page.

This is how the GET method is mostly used. However you can get form data from an HTML page to put its values into the URL.

In order to this you need to have the method set in the form:
Code:
<form action='process.php' METHOD='get'>

What you should know is that inside a form, the "name" is what the name of the variable will be in the URL.
Code:
<input type='text' name='text1' />
If this was submitted... the URL would become:
Code:
website.com/process.php?text1=<input value>

This is a simple concept. However, what is an even easier concept is
POST. The POST method is simply the GET method... except invisible and
therefore more secure.
Code:
website.com/news.php?article=1
With this URL, you can simply change "1" to "2" and it will change what article is shown.

With POST however, you cannot change this by the same means, which makes the data submitted more secure.
The way to grab the data is the same as you would with GET:
Code:
<?
$output = $_POST['article'];
echo $output; // Outputs 1
?>

I explain these two more efficiently in my Video Tutorial.


Combine GET, Switches, and Functions

Now let's side track for a moment. I want to show you an efficient way to use all three of those in the title.

It would be best just to watch the video on it.

I'm not going to explain it here... it's a miniature project that shows
you the scope of what can be done. Not fit for this post.


Super Globals

I did not mention previously, but the $_POST and $_GET methods are
considered part of the super globals. A super global is a variable that
is recognized throughout every PHP page, no matter where you go.
There are a couple more important super globals I want to show you, they are COOKIE and SESSION.
A cookie is a bit of information that is stored on your computer so a website can access them at a later date.

In order to set a cookie in PHP, use this syntax:
Code:
setcookie("<name>","<value>","<expiration>");

By default, if no expiration is set, the cookie ends when you close your browser.

Here's how to set a cookie equal to my name that will last a week:
Please note the time() is in seconds.
Code:
<?
$expire = time()*60*60*24*7;
// 60 second in a minute/hour, 24 hours in a day, 7 days.
setcookie("name","Chris",$expire);
?>

In order to call that cookie at a different page, for example... you use $_COOKIE[''];
Code:
<?
$name = $_COOKIE['name'];
echo "Welcome, ".$name."!";
?>

This will find the cookie titled "name" and grab the value for that.

The similar super global to cookie is SESSION. This is a variable that is stored depending on a Session ID.
A session is temporary and is removed when you close the browser.

In order to start a PHP session and assign a new SESSION variable:
Code:
<?
session_start(); // Start Sessions
$_SESSION['name'] = "Chris";
?>

This session variable "name" will now be remember on every page as long as you start up sessions again.
Code:
<?
session_start();
echo "My name is: {$_SESSION['name']}.";
?>

The curly braces wrap the super globals so PHP knows its a variable and
not text. If you have a SESSION set when someone logs in, make sure you
remove a session when someone logs out by:
Code:
session_destroy();

As a quick tip, use the isset() function whenever you need to check to
see if a super global is set, if not, it will output error.
Code:
<?
$cookie = $_COOKIE['name'];
if(isset($cookie)){
echo "Cookie is set.";
}else{
echo "Cookie isn't set.";
}

The isset() outputs only "true" or "false".

NOTE: There is another important $_FILE super global which deals with uploading files. Look for my upcoming tutorial on this.
Okay, that's enough of super globals...

PHP and MySQL Database

MySQL (pronounced My-S-Q-L or My-Sequel) is a type of database. A
database can be though of a spreadsheet (like MS-Excel) that holds
columns and rows of information. In Excel, you can retrieve data from a
certain cell by calling the row and the column (ie. A1 or F6) that data
resides in. You can do the same in PHP. Values retrieved by the database
is placed into an array.
Let's say we wanted to grab my name in the database, where my ID is 1 and the table column is called "name".
Code:
<?
$sql = mysql_query("SELECT name FROM table WHERE id='1' LIMIT 0,1");
$sql = mysql_fetch_array($sql);
echo end($sql);
?>

Every line here should be new to you if you are new to MySQL databases.
On the first line, the "mysql_query()" function has a parameter of the database query.
In this case, we are selecting a value from the table "table" where
column name is "name" and the row's ID is 1. LIMIT 0,1 simply selects
how many to look for (LIMIT offset,amount). In this case, we only need
1.
One the second line, the "mysql_fetch_array()" places the data retrieved from the database in an array.

Some people may argue that it is better to use "mysql_fetch_assoc()" for
an associative array, but that can be added to a parameter like so:
Code:
mysql_fetch_array($sql, MYSQL_ASSOC);
However, the second parameter is not needed. mysql_fetch_array() will suffice.

On the third line, we use "end($sql)". The "end()" function selects the
last value in the array. Now you could echo out the resulting variable
and it will contain the string from the database, which happens to be
the username.


Miscellaneous Functions

Include and Require
Reference: Video Tutorial.

Code:
<?
include("someCode.php");
// Includes the entire page into the current php page.
require("someCode.php");
//Must have this page included, or output error.
?>

Date

Code:
<?
echo "Today is: ".date("m/d/Y");
// m = month (01-12)
// d = day (01-31)
// Y = year (in four digits)
?>

File Upload

Code:
<?
$temp = $_FILES["uploader"]["tmp_name"];
$name = $_FILES["uploader"]["name"];
move_uploaded_file($temp,"./uploads/".$name);
echo "File stored at: ./uploads/$name";
?>

Email

Syntax:
Code:
mail(to,subject,message,headers,parameters);

Usage:
Code:
<?
mail("XYZ@someSite.com","Read this!","I can do PHP!");
?>


Look out for future project tutorials.
Note: if anyone is interested, I do have a Captcha tutorial on PHPAcademy.org, just search the forums for "captcha" and "knightmaire" and it will show up.

Enjoy.


Last edited by Hesitate on Sat Jul 14, 2012 4:46 pm; edited 1 time in total (Reason for editing : Added extra content in Introduction)

_________________
I work on PHP, if you want any assistance, PM me Smile
avatar
Hesitate
Rookie
Rookie

Posts : 6
Join date : 2012-06-29
Age : 24
Location : Massachusetts

Back to top Go down

View previous topic View next topic Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum