Beginning PHP Part 2: Learn PHP Functions and Security

Getting a basic familiarity with PHP is not difficult, but if you don’t understand a few key elements you will find it difficult to work with. This beginning PHP series is meant to help you learn PHP. In this tutorial we take it to the next level and get down and dirty with PHP functions and take a look at basic PHP security.

This beginning PHP tutorial is part two in the series. Take a look at part one of the Beginning PHP series if you haven’t already.

Beginning PHP Tutorial Assumptions

It is assumed that the reader has a basic understanding of HTML. Previous programming experience is a huge plus, but it is not a requirement. If you have any kind of programming background, you should already know a lot of these core concepts.

http://www.montanaprogrammer.com/wp-admin/edit.php

PHP Variables

Earlier we went through PHP arrays and talked about how to work with PHP variables. If you do not have a basic understanding in how to work with PHP variables, then I suggest going through that tutorial. This tutorial assumes that you know how to work with variables….which allows us to take things to the next level. 🙂

PHP Functions

PHP Functions allow you to easily create code that you re-use in different occasions. This is a very fundamental understanding that will help you move onto the more advanced object oriented programming paradigm and other methodologies.

There are two types of functions: pre-defined functions that are a core element of the PHP language and user defined functions. We will go through both.

If you are writing the same code over and over again on a website, it is a good idea to create a function to handle that code. Or if there is a function in PHP that does what you are looking for, there is no need to create your own code to do the same thing.

Pre-defined PHP Functions

There are many pre-defined functions in the PHP language. Some functions return a value that you can use in PHP, or they print a value to the screen. Many functions have arguments that you can send to them to customize their behavior.

So to start our discussion on PHP Functions, take a look at this example using the date() function.

<?php
$today = date("d/m/Y");
echo $today;
?>

If you look at the documentation for the date() function on php.net, you will notice that this pre-defined PHP function can take two arguments.

Note: Do not be afraid to reference php.net! It is an excellent resource, and there are always going to be new functions you discover that will be very useful.

For this example, go ahead and change the $today variable to equal: date() . It should either give you an error message or a blank screen (which it will do if your server is set to not display PHP errors). For the date() function, it requires that you send one parameter, but you can send up to two parameters. In the example above, since we only sent one parameter, it will use the current date/time of the server in the dd/mm/yyyy format. If you take a look at the php.net documentation, you will notice that there are many options in how you can have the date formatted.

So moving on…the current date is assigned to the $today variable. We then print that date to the screen.

What if we wanted to display yesterdays date? We still need to use the date function, but we also have to use mktime() to create the correct timestamp to send to date(). Now I realize that this may be confusing if you do not have any experience working with functions…but bear with me and work with the code on your end!

<?php
// First create the values to send to mktime...
$month = date("m"); // grabs the current month value
$yesterday = date("d") - 1; // we grab the current day value and subtract 1
$year = date("Y"); // grabs the current year value

// Create the timestamp...
$yesterday_Timestamp = mktime(0, 0, 0, $month, $yesterday, $year);

// Create the date value and display it to the screen...
$yesterdateDate = date("d/m/Y", $yesterday_Timestamp);
echo $yesterdateDate;
?>

Lines #3-5: Define the values that we will send to mktime();

Line #7: Since the date function needs to take a timestamp value to produce the date that we want, we will need to first create the timestamp. We use the mktime() function which takes 6 arguments to do this.

Line #11: Output yesterdays date in the specified format.

As the above code will work fine, below is a more condensed version of the same thing.

<?php
$yesterday_Timestamp = mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
$yesterdateDate = date("d/m/Y", $yesterday_Timestamp);
echo $yesterdateDate;
?>

User Defined Functions

Why would you want to create your own functions?

  • Easier to re-use code.
  • If you wanted to change the code, you would only have to change it in one file.
  • Saves time and you don’t have to write as much code…which equals more profitability.

So let us jump in by creating a simple function that takes a date value in the format dd-mm-yyyy format, and converts it into a timestamp.

<?php
/*
 * Takes a date value in the format dd-mm-yyyy and 
 * returns a string in the format Month Day, YYYY.
 */
function chrisConvertDte($date)
{
	// take out any extra white spaces from the end of the value
	$date = trim($date);
	
	// split up the date value
	$splitDte = explode('-', $date);
	
	if(count($splitDte) > 0)
	{
		// spliteDte is now an array...but let us assign them to
		// more friendly variables...
		$day = (int)$splitDte[0];
		$month = (int)$splitDte[1];
		$year = (int)$splitDte[2];
		
		// if any of the date values are not numbers, than they did 
		// not give us a date value in a valid format...
		if($day < 1)
			return false;
			
		if($month < 1)
			return false;
		
		if($year 

Line #6: We define the name of our function, along with the parameters it will accept. In this case we are only taking one parameter ($date) and it is a required parameter. If we did not want to require the parameter, than we could put $date = ”…which says that if the parameter is not defined, it defaults to an empty string.

Line #12: We call the PHP function explode() which takes a string and separates the string based on a divider (in this case: -) and puts the separated values into an array.

Lines #18-20: We take the values that we split up from the $date parameter, and we “cast” them as integers. Basically this tells PHP to convert the value to an integer if it is not one already. If any of them were strings, they would get an integer value of 0. This would trip the fail safety of the function.

Line #25, 28, 31, 40, 44: Some functions are designed to return a value. In this case I designed the chrisConvertDte function to return either false (boolean) when the function fails, or return the formatted date if there are no problems. The keyword “return” stops the function from where it is at and PHP goes back to where that function was called. Every function does not have to return a value (which could be boolean, string, numeric or an array). But it usually is a good idea to return some indicator that the function was successful or if it failed.

Line #49: This is where we call the function we created. If the function returns false, the if statement on line #52 will be false and it will display our specified error message

We actually did not need to create the function above to do what we were wanting. We could have simply used strtotime(), but it was a good function to go through. Sometimes this will happen…just remember there is value in writing code (even when there is a simpler way). But often times you don’t have this luxury because you need to meet deadlines.

If you are like me, the best way to learn is to work through more complicated code. I re-wrote the above function to be more flexible and to use less code.

<?php
/*
 * Takes a date value in any human readable format and 
 * returns an array that contains the day, month and year
 * value, along with a string in the format Month Day, YYYY.
 */
function chrisConvertDte($date = '')
{
	if(empty($date)) // default to the current date/time value
		$timestamp = time(); 
	else 
	{
		// Convert the $date value to a timestamp.
		// If it is not a valid format, return false.
		if(!$timestamp = strtotime($date))
			return false;
	}
	
	// define the values in the array that we will return
	$returnDte = array();
	$returnDte['day'] = date("j", $timestamp);
	$returnDte['month'] = date("m", $timestamp);
	$returnDte['year'] = date("Y", $timestamp);		
	$returnDte['fullDte'] = date("F j, Y", $timestamp);
	
	return $returnDte;
}

// Call our user defined function
$getDate = chrisConvertDte('22-02-2010');

// If there were no errors, print the date to the screen
if($getDate)
{
	echo '<pre>';
	print_r($getDate);
	echo '</pre>';
}
else
	echo 'The date value is not in a human readable format!';
?>
</pre>

This is what the above code would output.

<pre class="brush: php;">Array
(
    [day] => 22
    [month] => 02
    [year] => 2010
    [fullDte] => February 22, 2010
)

Additional Resources on PHP Functions

If you still do not understand how to work with functions, take a look at these links:

Basic PHP Security

When it comes to PHP security, other than settings in the php.ini file and server settings, there are a few things to keep in mind:

#1. Never trust web users

If you are working with a form, never assume that the user is going to enter correct values.

  • If you expect a value to be an integer, cast it as an integer. This prevents hackers from posting a form to your processing script and getting somewhere with it.
  • If there are only a few options that you want to give a user in a form, make these options form selects, check boxes or radio buttons.
  • You should never allow visitors to upload files on your website. There should be some kind of login/admin system where only specific users can do this.
  • Always password protect any kind of administration area. The last thing you need to happen is for your admin to get indexed by the search engines.

#2. Prevent SQL Injection

This simply requires using the mysql_real_escape_string() function with values in a MySQL database. Even if you think the value you are working with is an integer, it is always safe to use this function.

Post in the comments if you have any questions.

5 thoughts on “Beginning PHP Part 2: Learn PHP Functions and Security

  1. Good read Chris.

    Maybe for

    if($day < 1)
    return false;
    if($month < 1)
    return false;
    if($year < 1)
    return false;

    That could have been a good place to introduce the logical OR operator.

    if ($day < 1 || $month < 1 || $year < 1)
    return false

    PHP can be a very ugly coding language because of how loose it is. Maybe you can do an article on good programming practices to create cleaner code.

    Like

    • I wanted to keep the first example more simple, but that is a good tip. I think if statements will be a separate post.

      Code readability would be a good post. I’ll make a note of that. Thanks. 🙂

      Like

  2. Beginning PHP Part 2: Learn PHP Functions and Security…

    Getting a basic familiarity with PHP is not difficult, but if you don’t understand a few key elements you will find it difficult to work with. This beginning PHP series is meant to help you learn PHP. In this tutorial we take it to the next level and g…

    Like

Comments are closed.