PHP Strings
In this post we will explore:
- Prebuilt string functions
- Regular Expressions
- Escaping strings
- echo vs print
- printf and sprintf
First of all what is a string?
Strings are variables, they contain characters (Variable characters). They could also be considered as a type of array.
Prebuilt String Functions
PHP provides excellent support for strings: http://php.net/manual/en/ref.strings.php. The string functions we will focus on in this post are:
- strlen
- strrpos
- explode
- Implode
String functions in practice
$test_string = "Toby Harris"; if(!strlen($test_string)) { echo "Name required."; } else echo strlen($test_string);
What’s happening?
This snippet is testing for the existence of a string – common in a lot of forms. In fact the best way to demonstrate how strings are used and validated is to do precisely that – build a form!
A simple contact form
What we will do is build a form and using string functions manipulate the data input. We can also use the form to discuss common techniques in string validation such as regular expressions.
We will structure the form as follows:
- Controlling script (index.php)
- Contact form (contact.php)
- Error view (errors.php)
- Received (received.php)
You could put all the code in one file and that is just as vaalid but I am a great believer in factoring out code to specific views, models and controllers not necessarily in a strict MVC way but just enough to make the code easier to manage and maintain.
Let’s start with the controller code:
include_once 'functions.inc.php' $error_flag = 0; //Note use of isset — Determines if a variable is set and is not NULL if(!isset($_POST['firstname'])) { include 'contact.html.php'; } else { $recordData['firstname'] = $_POST['firstname']; $recordData['lastname'] = $lastname = $_POST['lastname']; $recordData['email'] = $_POST['email']; $recordData['username'] = $_POST['username']; $recordData['password1'] = $_POST['password1']; $recordData['dateRecorded'] = time(); $password2 = $_POST['password2']; //$recordData['tel_no'] = $_POST['tel_no']; $email_regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/"; $password_regexp = "/[0-9]/"; if(!$recordData['firstname']) { $errors['firstname'] = "First name is required!"; $error_flag++; } if(!$lastname) { $errors['lastname'] = "Last name is required!"; $error_flag++; } if($email_flag = checkemail($recordData['email'])) { $errors['email'] = "Please provide valid email address"; $error_flag++; } if($recordData['password1'] && $password2) if (strcmp($recordData['password1'],$password2) == 0) { if(!preg_match($password_regexp, $recordData['password1']) ) { $errors['password'] = "Password requires at least one digit!"; $error_flag++; } } else { $errors['password'] = "Passwords do not match!"; $error_flag++; } else { $errors['password'] = "Please enter password!"; $error_flag++; } if(!$recordData['username'] || strlen($recordData['username']) < 6) { $errors['username'] = "User name must be six characters or more"; $error_flag++; } if($error_flag) { include 'errors.html.php'; } else { $recordData['firstname'] = ucfirst($recordData['firstname']); $recordData['lastname'] = ucfirst($recordData['lastname']); foreach($recordData as $row) { echo $row . "<br>"; } } }
What's happening?
Ok, there is a lot to take on here so let's break it down. What we are looking at here is what I would regard as the controller code and would exist in something like index.php. There is a functions.inc.php file at the top. We will look at this later but that is designed to store common functions we will need for form validation.
Snippet 1
$error_flag = 0; //Note use of isset — Determines if a variable is set and is not NULL if(!isset($_POST['firstname'])) { include 'contact.html.php'; }
Here we are setting an error flag to 0. If it remains zero at the end of the validation send the form. If not alert user of errors. We are also checking for the required field firstname if the name is not present then display the form else start to validate the rest if the form.
Snippet 2
else { $recordData['firstname'] = $_POST['firstname']; $recordData['lastname'] = $lastname = $_POST['lastname']; $recordData['email'] = $_POST['email']; $recordData['username'] = $_POST['username']; $recordData['password1'] = $_POST['password1']; $recordData['dateRecorded'] = time(); $password2 = $_POST['password2']; $email_regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/"; $password_regexp = "/[0-9]/"; if(!$recordData['firstname']) { $errors['firstname'] = "First name is required!"; $error_flag++; } if(!$lastname) { $errors['lastname'] = "Last name is required!"; $error_flag++; }
Ok so the first name has been set so now we can start capturing the rest of the data and we do this using PHP's global array $_POST. There are also a couple vars I have defined to check that emails are in the correct format and a password at least has a number in it. Notice also that we start checking for the existance of vars and if they are not present we increment the error flag and store the error message in an associative array called errors.
Snippet 3
if($recordData['password1'] && $password2) if (strcmp($recordData['password1'],$password2) == 0) { if(!preg_match($password_regexp, $recordData['password1']) ) { $errors['password'] = "Password requires at least one digit!"; $error_flag++; } else { $errors['password'] = "Passwords do not match!"; $error_flag++; } else { $errors['password'] = "Please enter password!"; $error_flag++; }
In this snippet we making use of some classic PHP inbuilt string functions:
strcmp = compares the length of one string against another preg_match = compares string patterns against a predefined format often referred to as a regular expression
Formatting data this way is a great way of securing your application. The more validation you have the harder it is for bad guys to circumvent your application. You can never have too much validation!
Ok so that is the 'controller' code nailed - let's explore the rest of it.
View code
<form name="contact_frm" action="index.php" method="post"> <ul> <li><label>First name</label><input type="text" name="firstname" id="fname" /></li> <li><label>Last name</label><input type="text" name="lastname" id="fname" /></li> <li><label>Email address</label><input type="text" name="email" id="fname" /></li> <li><label>Enter username</label><input type="text" name="username" id="username" /></li> <li><label>Enter password</label><input type="password" name="password1" id="password" /></li> <li><label>Retype password</label><input type="password" name="password2" id="confirm_password" /></li> <li><label>Telephone no</label><input type="text" name="tel_no" id="tel_no" /></li> <li><input type="submit" value="send" /></li> </ul> </form>
What's happening?
This is pretty standard fair for an HTML form but two attributes of note here is the method POST. This tells the header what we want to do with the form - we could use GET but that's a bad idea given the data will be present is the URL and thus sensitive info such as passwords will be visible - not great!. The other attribute is the action - in this case we are posting our form to a processor called index.php.
Utility functions
function checkEmail($e) { $email_regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/"; if(!preg_match($email_regexp, $e) ) { return TRUE; } else return FALSE }
What's happening?
Our functions file only has one function in it (checkEmail) so arguably a bit overkill. But in a normal application you would have a lot of these types of functions and it is good practice to store them in a central location so they can be accessed by all parts of the app that need them.
What we are essentially doing here is checking if the email is valid. If not return true and add 1 to the error total. Else return false (zero).
What would the next steps be for a form like this?
Once the form has passed validation you then have what is referred to as a record set which could be committed to a database and stored for future reference. In this case we have created a simple sign-up form so in this example committing to a DB would be the way to go.
echo, print, printf
It would be remiss of me, in a post that introduces PHP strings to not mention the big three in terms of PHP in-built functions. Especially given you will be using these the most!
echo = this function echo's or prints data directly to the viewport print = does the same as echo but can return true or false. It will return true of successful. printf = this function allows you to format the string before pushing to the viewport
Some useful links
This is a great article by nutt.net that explains the differences really well between the three. (old but still a good one!)
To find out more about the types of formatting that can be used in print_f php.net has an excellent resource for this.
And finally print_r
print_r is a great tool for your toolbox - it is used mostly in debugging - at least that's what I use it for! It simply prints the contents of the variable to the viewport. So for example if you were trying to find out if a VAR had anything in it to help trace an issue through you can use print_r as a break point to track the progress of a VAR. Used in combination with exit() and you have a breakpoint that stops at that point - ideal for complex debugging scenarios.
What have we explored?
We have explored:
- Prebuilt string functions
- Regular Expressions
- Escaping strings
- echo vs print