Category Archives: Tutorials

Function Arguments

In the latest version of PHP there are well over 5000 functions built into the core of PHP these functions range from echoing and printing a string to creating and manipulating files and databases. In this tutorial I will show you how you can create you own functions.

License System

In this tutorial we will be developing a license system which can be used with construction of any scripts you develop.

How the system will work.

First the client or the website script will send off a request to the server using PHP and Curl. This will initiate the response page on the server side it will then retrieve the license from the database using the details provided from the client. The status will then be sent back to the client if unsuccessful an error message will be sent. The client then received the output. Should the license be invalid the script will exit and an error message displayed.

Mathematics Arithmetic

In this tutorial we will be looking in detail into how using the inbuilt functions of PHP we can run the oldest branch of mathematics, Arithmetic.

PHP lets you run simple maths easily, using the in built functions with PHP we are able to do add, subtract, multiply and divide. PHP does also include extra mathematic functions which can be found

http://php.net/manual/en/ref.math.php we will go into more of these functions in later tutorials.

For now lets start by running some simple add and subtract formulas. In our first example we will add the numbers 6 and 10.

First we will create an array in which we can store the numbers we want to add up.
[code='php']$numbers = array("6", "10");[/code}
We have assigned the array to a variable $numbers, this is so we are able to call upon the array further into the script.

Now we need to run the question to add up both numbers.
[code='php']$answer = $numbers["0"] + $numbers["1"];[/code}
Using PHP simple maths functions are as simple as that to run you put the number you need then the symbol and finally the other number. You then assign this to a variable and that will output your answer. It’s that simple.
[code='php']echo $numbers["0"] . " + " . $numbers["1"] . " = " . $answer;[/code}
To finish this off we have echoed the question and the answer. For subtraction you can use the same code as above but change the second line $answer to the following.
[code='php']$answer = $numbers["1"] - $numbers["0"];[/code}
Now we have subtraction you should be getting the format of this

Multiplication

 
[code='php']$answer = $numbers["1"] * $numbers["0"];[/code}
Division
[code='php']$answer = $numbers["1"] / $numbers["0"];[/code}
So now we have mastered the basics, but all we have been doing is adding, subtracting, multiplying and dividing 2 numbers. What if we require doing more than just the 2, well with the array we created previously we are able to add as many numbers as we want for example.
[code='php']$numbers = array("6", "10", "15", "32", "99", "1", "27");[/code}
As we have stored these numbers in an array we will save time by instead of writing out each number we will loop through the array, in this instance we will be adding up the numbers.
[code='php']$question = "0";
foreach($numbers as $value){
$question = $question + $value;
}[/code}
As you may have noticed before running through the foreach we have set $question to 0. This may look stupid but depending on the level of reporting your system is set to leaving this off may produce an error as the first time it loops you would be adding a value to in its case an unset variable.

Once we have set $question using the foreach we loop through the $numbers array assigning each number to $value as it loops, inside the loop we retrieve $question and add the value to it. This is then set to $question so it can continuously add to it.
[code='php']echo "Total sum is: " . $question;[/code}
We have now just echoed the answer to the question. So now you should have something similar to this.
[code='php'] $numbers = array("6", "10", "15", "32", "99", "1", "27");

$question = "0";
foreach($numbers as $value){
$question = $question + $value;
}

echo "Total sum is: " . $question;
?>[/code}
Using the snippet used earlier in this tutorial, this code can be modified to subtract, multiply or divide as well.

I hope my tutorial has provided you with a better insight into using PHP to run arithmetic, and if you need someplace to start messing around with PHP. I now provide web hosting simply visit my website for further details.

Navigation

In this tutorial we will look in detail into how to use PHP to include content into the main homepage. This can be used to as an alternative to an iFrame and can be used to help save disk space and allow easier updating of common areas by only having to edit one page. I will also touch on a simple

So let’s start first we must create an array which will hold all the page locations and page names. The format will be “page_reference” => “page_location”, Which in turn would make the url show as index.php?page=page_reference

$pages = array("homepage" => "main.php", "about" => "about.php", "contact" => "contact_us.php", "404" => "error.php");

So following that format you are able to add as many pages as you want. There is also another advantage of using this method as just referencing the pages directly as if there were no checks to see whether the page is allowed to be public this way then this can be exploited to include other files not authorized so this is vital to help maintain security and lower risks.

Next we will set some variables;

$default_choice

This is used when ?page= in the url is not set. This is the page reference as it will still check the page against the array we created earlier.

$current_choice

Using the $_GET array we will retrieve from the url the ?page= variable and using strip_tags command we will remove any coding tags which could be used to exploit the script and we will also remove any blank spaces at the start or end of the variable using the trim command.

$error_page

This is used in the event of a request of a page that does not exist in the array previously created or the actual page not existing.

Now we have what they mean lets actually put the code in.

$default_choice = "homepage";
$current_choice = trim(strip_tags($_GET['page']));
$error_page = "404";

This is all the variables and settings done with. Next we need to check whether there is a page selected and if there is a page selected whether the page exists. We do this by using the isset function. In simple terms the isset function is used to determine if the string has been set. So we will use this to determine if $current_choice has been set in the url and if the current choice has been set if a page with that reference can be found within the array we created at the start.

if(isset($current_choice, $pages[$current_choice]))
{

Now we have checked if the page exists in the array, we still aren’t sure if the actual file exists on the server. This is done using the file_exists function.

if(file_exists($pages[$current_choice]))
{

Next is to include the actual file that is being requested.

include($pages[$current_choice]);

Once we have confirmed the page exists we need to actually bring it in to the current page we have done this using the include function and using the $pages array we created at the beginning we select the page that the user has selected.

But now we have included the page if the file exists but what happens when the file is unable to be located. Well this is where the 404 reference page comes in.  If the file is not found then we include the error page.

} else {
	include($pages[$error_page]);
}

Finally we finish this tutorial by completing the first if statement. If no page has been selected then we must include a default page which in our case is “homepage”. Although for an extra point you will notice that there is a @ sign before they include function on this part this is because we aren’t running any checks whether the default page actually exists. The @ symbol is used as a silencer. A silencer is used to hide any errors should they occur. This includes any errors such as not being able to locate the file or if there are any errors such as PHP errors on the page that has been included.

You are welcome to add checks for file existing simply copy the format as listed in a previous part of this tutorial.

} else {
	@include($pages[$default_choice]);
}

But now for what it should look like J.

<?php

$pages=array("homepage"=>"main.php","about"=>"about.php","contact"=>"contact_us.php","404"=>"error.php");

$default_choice="homepage";
$current_choice=trim(strip_tags($_GET['page']));
$error_page="404";

if(isset($current_choice,$pages[$current_choice]))
{
	if(file_exists($pages[$current_choice]))
	{
		include($pages[$current_choice]);
	}
	else
	{
		include($pages[$error_page]);
	}
}
else
{
	@include($pages[$default_choice]);
}

?>

A demo of this tutorial can be found at

http://www.peter-kelly.com/downloads/navigation_test_files/

Should you have any further questions about this tutorial or any other tutorials listed on my website or have any other suggestions for tutorials. Please don’t hesitate to contact me. I hope this tutorial helps you and if you have any feedback about how I can improve the tutorials I produce I welcome it.

ZIP Archive Manipulation

In this tutorial we will look in detail into the ZIP functions included in PHP. So what is a ZIP Archive?

DEFINITION
The ZIP file format (.zip) is a data compression and archive format. A ZIP file contains one or more files that have been compressed to reduce file size, or stored as-is.

Creating A ZIP File

First we need some files or information we want to compress into the ZIP. Below are some examples of what I have included in this tutorial. These files should be placed in the directories stated.

test_files/test_text.txt
test_files/test_html.html
test_document.doc

You can download copies of the test files I have used by clicking on the link at the bottom of this tutorial.

So now we have the files we are going to include in the archive, let’s go through the functions we will be using in this tutorial.

OPEN
open(string $filename [, int $flags]); Open is used to open a new ZIP Archive for reading, writing or modifying.

ADDFROMSTRING
addFromString(string $local_file_name, string $contents); addFromString is used to include data into the ZIP Archive that is not already located inside a file. So this function will create a file inside the archive and insert the string contents into that file.

ADDFILE
addFile(string $file_name_archive, string $file_name_local); addFile is used to include an already existing file or folder into the archive.

Now we will start by constructing the string variables.

$zip_archive = "new_zip_archive.zip";
$folder_local_location = "test_files/";
$folder_in_archive = "test_files/";
$file_local_location = "test_document.doc";
$file_in_archive = "test_document.doc";

$zip_archive is the string for setting the filename and location of the ZIP Archive you are creating. E.g “/zips/zipzippyzip.zip” but this archive must be in a directory that is writable or must already exist and have writable permissions.

 

$folder_local_location is the name and location of the folder we are including into the archive that already exists on the server.

$folder_in_archive is the name and location of the folder we are adding into the archive this is useful as you can rename the folder once inside the ZIP Archive.

$file_local_location is the name and location of the file we are including into the archive that already exists on the server.

$file_in_archive is the name and location of the folder we are adding into the archive this is useful as you can rename the folder once inside the ZIP Archive.

Next we must create the ZIP Archive class and open it for creation.

$zip = new ZipArchive;
$open = $zip->open($zip_archive, ZipArchive::CREATE);

In the first line we are starting the ZipArchive class and assigning the class the $zip variable this is so we can implement it in other locations as you will see in line 2.

 

Now we must run an, IF command to check whether the $open has outputted TRUE successfully. This uses a comparison operator of === this means Identical where as == just means Equal. For more information about operators visit the php.net website.

http://www.php.net/manual/en/language.operators.php

if ($open === TRUE) {

Once we have confirmed $open has been successful, we can commence with inserting items into the  ZIP Archive. Using the commands we learnt previously.

 

$zip->addFromString('new_string_file.txt', 'This file has been created via PHP and will be put into the ZIP Archive.');
$zip->addFile($file_in_archive, $file_local_location);
$zip->addFile($folder_in_archive, $folder_local_location);
$zip->close();

After we have inserted the items we must close the archive this finishes the ZIP Archive but as a final check we will see if the ZIP Archive actually exists in the location specified at the start and output the appropriate response.

 

if(file_exists($zip_archive)){
	echo "Created Archive.";
}else{
	echo "Error: Archive Does Not Exist.";
}

And finally the last bit of the code remember the if($open === TRUE){ well we must put the closing bracket and what happens if it doesn’t equal true.

} else {
	echo "Unknown Error.";
}

Now we have completed the tutorial below is the finished product.

 

<?php

$zip_archive = "new_zip_archive.zip";
$folder_local_location = "test_files/";
$folder_in_archive = "test_files/";
$file_local_location = "test_document.doc";
$file_in_archive = "test_document.doc";

$zip = new ZipArchive;
$open = $zip->open($zip_archive, ZipArchive::CREATE);
if ($open === TRUE) {
	$zip->addFromString('new_string_file.txt', 'This file has been created via PHP and will be put into the ZIP Archive.');
	$zip->addFile($file_in_archive, $file_local_location);
	$zip->addFile($folder_in_archive, $folder_local_location);
	$zip->close();
	if(file_exists($zip_archive)){
		echo "Created Archive.";
	}else{
		echo "Error: Archive Does Not Exist.";
	}
} else {
	echo "Unknown Error.";
}

?>

Well now you’ve got through the difficult part of creating and inserting the items into a ZIP Archive. We need to be able to get the items out again. This is where the next part of the tutorial kicks in.

 

Extracting A ZIP File

To extract a ZIP we must first set a few string settings.

$zip_archive = "new_zip_archive.zip";
$extract_location = "new_zip_archive_extract/";

$zip_archive is the location and name of the archive we are going to extract in this case it is set to new_zip_archive.zip.

 

$extract_location is the location of where we want the files in the archive to be extracted to.

Now we must use the same commands as used as when creating the archive by creating a new ZipArchive class and assigning it to $zip then opening it and assigning it to $extract although this time without any flags selected. We must then use an IF statement to see if $extract outputs TRUE.

$zip = new ZipArchive;
$extract = $zip->open($name_of_zip);
if ($extract === TRUE) {

In this next section we will use a new command called extractto

EXTRACTTO extractTo(string $destination, mixed $entries); extractTo is used to export the files from within the ZIP Archive. The $entries can be written as just a single string or as an array. This is used to remove just certain files from the archive.

Now to use this function.

$zip->extractTo($extract_location);
$zip->close();
echo 'Successfully Extracted.';

As again we have extracted the files using the extractTo function and then closed the ZIP Archive. We have then echoed the success message. Once we have done this we must finish off the IF statement we began previously. Although this time we will also output the error message if one is needed.

} else {
	echo 'Error: ' . $extract;
}

So that’s it below is the overall code you should end up with.

<?php

$zip_archive = "new_zip_archive.zip";
$extract_location = "new_zip_archive_extract/";

$zip = new ZipArchive;
$extract = $zip->open($name_of_zip);
if ($extract === TRUE) {
	$zip->extractTo($extract_location);
	$zip->close();
	echo 'Successfully Extracted.';
} else {
	echo 'Error: ' . $extract;
}

?>

Now you have learnt how to create and extract a ZIP Archive using PHP. Please use this as a guide to further your learning but mess about with the functions available at the php.net website and see what you can come up with.

http://uk3.php.net/manual/en/class.ziparchive.php

To download the test files listed above visit.

http://www.peter-kelly.com/downloads/zip_test_files.zip

If you have any further questions on this Tutorial or anything else about myself or the content displayed on my website http://www.peter-kelly.com please don’t hesitate to contact me by emailing me@peter-kelly.me or by visiting my website.

Thank You for Reading.