Functions

PHP Functions are extremely useful, and they can save you from writing bunch of redundant code. These are arguably the most power component to any language. It can separate your code to create a sense of logical flow. You can also add parameters, or arguments to functions, where you can see that power at the bottom of this page. Functions have a limited scope, which I believe is an asset. This means that if you define a variable inside the function, you cannot reference that variable outside of the function.

Example

function greetings()
{

echo “Greetings”;

}
greetings();

Result

Greetings

Here, we have a function called greetings. After we define the function, we called the function with greetings();. Pretty simple, huh? Now, let’s make our functions even more useful by adding arguments.

Function Arguments

Example

function sampleFunction($argument1)
{

echo $argument1;

}
sampleFunction(“Something”);

Result

Something

Woot woot! We just used a parameter. A parameter is like a variable of the function that is defined when you call the function later. We can see how it is more useful in the next example.

Example

function addingFunction($parameter1, $parameter2)
{

echo $parameter1 + $parameter2;

}
addingFunction(333,444);

Result

777

This is similar to the last example. At the end, we call our function addingFunction(). We pass in two parameters this time: 333 and 444. Where 333 is being passed into the addingFunction as $parameter1 and 444 is also passed in as $parameter2. Once they are both passed in, we echo the sum of the two parameters. In the result, you can see that echo sent back 777. The final statement that executed was more like echo 777;. Nice job!

Like I said, understanding functions is crucial to your success as a programmer.

Delete File

Deleting files in php isn’t extremely common, but it is sometimes necessary. Always remember that you should hesitate before deleting anything. PHP doesn’t have a special undo for what you delete. Now that I have warned you, let’s burn some files to the ground.

Unlink in PHP

Example
$myFile = "testFolder/sampleDeleteFile.txt";
unlink($myFile) or die("Couldn't delete file");

As you can see, it doesn’t take too much to delete a file. If you run into problems deleting files, try opening and closing the file before you actually delete it. Like so:

Example
$myFile = "testFile.txt";
$myFileLink = fopen($myFile, 'w') or die("can't open file");
fclose($myFileLink);
$myFile = "testFolder/sampleDeleteFile.txt";
unlink($myFile) or die("Couldn't delete file");

I should note that this is more of a hack rather than good practice. Try to always close your files shortly after you open them. All you are doing with the code above is opening the file again to ensure that you actually close it.

If Statements

In PHP, if statements are the foundation of programming logic. If statements contain statements that are only executed when the condition is satisfied. Let’s go through an example.

Simple If Statement

Example
$myVar = 1;
if($myVar==1)
{
    echo "It worked.";
}
Result

It worked.

The if statement simply says, if the variable $myVar is equal to 1, then execute the statements inside of the { } brackets. If our variable had been equal to two, the statements inside of the if would not have been executed.

Comparison Operators

You already used one of these above. It was the ==, which asks if the thing before it is equal to the thing after it. If the answer is yes (true), we execute the statement. However, if the answer would have been no (false), we would not have executed the statement.

Example
$x = 7;
if($x===7)
{
    //this would be . $x
}
if($x==="7")
{
    //Since our variable $x is not a string this would be not executed because === is a strict operator, which makes sure that the variable is set to the correct value and type of the conditional variable.
}
if($x!=8)
{
    //this would be executed because != means that the variable is not equal to the conditional variable
}
if($x>8)
{
    //Since 7 is not greater 8, this would not be executed
}
if($x<8)
{
    //Since 8 greater 7, this would be executed
}
if($x>=7)
{
    //Since 7 is equal 7, this would be executed
}
if($x<=6)
{
    //Since 7 is not less than or equal to 6 this would not be . executed
}

You can see what each one of the comparison operators do above, but what if you wanted to use two of them simultaneously? You can by using the following logical operators.

Example
$x = 7;
if($x>=6 && $x<=8)
{
    //Since 7 is greater than 6 and 7 is less than 8, this statement would be executed
}
if($x==7 || $x>=8)
{
    //This if statement says if $x is equal to 7 or if x is greater than 8, then execute this statement. While x is not greater than 8, $x is equal to 7; therefore, it will execute the statement.
}
if(!($x==6))
{
    //Since $x is equal to 7, not 6, and we are checking to see if its false (with the ! before the condition), this statement would be executed
}

If, Else If, and Else

If statements can be just as simple as the examples above, but they can also be more useful when you combine the if statements with else if and else.

Example
$x = 6;
if($x == 8)
{
    $x++;
    echo "if($x = 8) and now x = " . $x; //This would not be triggered because $x is not equal to 8
}
else if ($x == 7)
{
    $x = 4;
    echo "else if ($x = 7) and now x = " . $x; //This would not be triggered because $x is not equal to 7
}
else
{
    $x = 20;
    echo "else and now x = " . $x; //This would be triggered because the other conditionals were not met
}
Result

else and now x = 20

You might be asking yourself, “What is the point in an else if statement?” Well consider the following examples

Example
$x = 8;
if($x == 8)
{
    $x++;
    echo "if($x = 8) and now x = " . $x; //This statement would be triggered because $x is equal to 8
}
if ($x == 7)
{
    $x = 4;
    echo "else if ($x = 7) and now x = " . $x; //This statement would not be triggered because $x is not equal to 7
}
else
{
    $x = 20;
    echo " else and now x = " . $x;//This statement would be triggered because the other conditionals were not met
}
Result

if(9 = 8) and now x = 9 else and now x = 20

Why did the if($x == 8) and the else both execute their statements? It is best to think of ifs as completely separate conditionals, but else if and else build off of whichever if they follow. So, if you had an if statement that was below another if statement, the first if statement would be separate from the second if statement just like the example above. However, the second if statement in the example above, has an else built onto it. Since the first if statement’s condition is satisfied, it executes its statements. The second if statement’s condition is not satisfied, but the attached else statement’s condition is satisfied. Therefore, $x is incremented in the first conditional, and “if($x = 8) and now $x = ” . $x is displayed on the screen. Also, we have the second if’s else that sets $x equal to 20, and “else and now $x = ” . $x is displayed on the screen.

Uploading Files

Uploading a file in PHP has many great purposes, but it is also one of the biggest places to create a security risk. You absolutely have to make sure you do this correctly. If not, I will hunt you down and upload a script on your site that will make you wish you had. Not really, but you should build it like I might. When uploading a file, we will generally use a form to allow users to find the file they want to upload on their computer.

HTML File Upload Form

Example
<form enctype="multipart/form-data" action="#" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="10000" />
    Choose a GIF file to upload: <input name="uploadedFile" type="file" /><br />
    <input type="submit" value="Upload File" />
</form>
Result
Choose a GIF file to upload:

Now, that is a cool form, but we don’t have any supporting server side code to tell it what to do. We need to craft a PHP file that will process the upload and check it to make sure it is the type of file that we want.

PHP Upload File

Example
<?php
if ($_FILES["uploadedFile"]["size"] < 10000)
{
    if ($_FILES["uploadedFile"]["type"] == "image/gif")
    {
        if ($_FILES["uploadedFile"]["error"] == 0)
        {
            $filePath = "testFolder/";
            $filePath = $filePath . basename( $_FILES['uploadedFile']['name']);
            if(move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $filePath))
            {
                echo "The file ".  basename( $_FILES['uploadedFile']['name'])." was uploaded successfully.";
            }
            else
            {
                echo "A problem occurred while uploading your file, please try again.";
            }
        } 
        else
        {
            echo "Something went wrong...";
        }
    }
    else
    {
        echo "Your file is not a gif filetype..";
    }
}
else
{
    echo "Your file exceeds the maximum size of 10KB.";
}
?>

In our massively packed if statement example, you can see our server side checks. You must check to make sure the file’s attributes are exactly what you want. Here, we only check for file size and file type. We first check the file size by using $_FILES[“uploadedFile”][“size”], where “uploadedFile” is the name of our upload in the HTML form. The 10000 is the file size in bytes, which translates to about 10kb in this example. Next, we only want gif file types. So, we check the $_FILES[“uploadedFile”][“type”], or the file type, to see if it is a gif. Finally, our last check is to make sure no errors have come up by checking if $_FILES[“uploadedFile”][“error”] equals 0.

Now, we come to the heart of the uploading process. We set our folder path with the $filePath variable. Then, we reset it with the folder path and the actual file name with basename( $_FILES[‘uploadedFile’][‘name’]). Finally, we upload the file in an if statement to check for final errors with move_uploaded_file($_FILES[‘uploadedFile’][‘tmp_name’], $filePath). The move_uploaded_file function takes two parameters: the file name, which is $_FILES[‘uploadedFile’][‘tmp_name’], and the file path. This moves the file to a specific location so that we can view it later. See uploading is easy.

Include and Require

Have you ever written some HTML code that was exactly the same across multiple pages, like a header or a footer? Your life is about to get so much easier. These awesome creatures known as PHP Server Side Includes will save you so many headaches and keystrokes later.

It is generally good practice to use the include function when writing code, and then later as you review it to replace it with the require function. Based on their overall purpose, they do exactly the same thing. They both “include” a file such as another PHP file that includes a standard header for your website. This is entirely like writing it out manually on each page. However, the difference between the two functions is that the require function stops executing your code as soon as an error occurs. The include function would still continue executing. Running the rest of the code after an error is usually not a good idea, so use require.

Using Include and Require

Example
//requireExample.php
    <p>HTML Text</p>
    <?php
        echo "PHP Text";
    ?>
//end of requireExample.php

//Your other PHP file
    <?php
        require("requireExample.php");
    ?>
//end Your other PHP file
Result

HTML Text

PHP Text

How freaking cool is that? You can completely put a navigation menu in a file and reference it using a require. I put PHP code and HTML code in my include to show you that it really doesn’t matter. You can include simple HTML files, PHP files, or a crossbreed of them. You can now require headers, footers, navigation bars, and anything else you don’t want to type more than once.

Let me just say a small precautionary note really quick. Don’t go too overboard. I have worked on various sites where I had to go through the requires of 6 pages to correct an error. Try to just have includes for the header, footer, navigations, and a few files with commonly used functions.