Tag Archives: php

Generating unique IDs and random strings in PHP

PHP functions covered in this tutorial:

  • uniqid()
  • md5()

This tutorial explains how to create unique ID strings using the uniqid() function and random strings using the md5() function. Warning: The uniqid() function does not create random or unpredictable strings. The uniqid() function should not be used for security purposes. For this purpose, it is better to use a secure string function or create a hash instead. You can create different types of hashes such as md5, sha1 or sha256. We will just look at the md5 hash in this tutorial.

Watch the video below and then scroll down to see the sample PHP code.

Sample PHP code:

<?php
  // Warning: The uniqid() function does not create random or unpredictable strings.
  // The uniqid() function should not be used for security purposes. Use a secure
  // string function instead.

  echo uniqid(); // generates unique ID
  echo '<br>';
  echo uniqid('id'); // generates unique ID with prefix of 'id'
  echo '<br>';
  echo uniqid('id',true); // generates unique ID with prefix of 'id' and increased entropy
  echo '<br>';
  echo md5(time() . mt_rand(1,1000000)); // using md5 to create random string
?>

More data validation in PHP

This tutorial shows some more data validation methods following on from the form data validation tutorial. In this tutorial, you will be shown how to implement the following data validation methods:

  • Limit number of characters that can be entered in a text box
  • Ask the user to enter a password twice and check that both passwords are identical
  • Validate an email address
  • Check that all parts of a form are completed

Watch the video below and then scroll down to see the sample code.

Sample PHP code

There are two files being used in this example which will validate a username, email address and password. The files are form.php and action_handler.php.

The form.php code:

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <h3>Enter a username, email and password to sign up.</h3>
    <p>Username: <input type="text" name="username"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p>Password: <input type="password" name="password"></p>
    <p>Password again: <input type="password" name="password2"></p>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>

The action_handler.php code:

<?php
  if(!empty($_POST['username'])){
    $username = $_POST['username'];
    if(strlen($username) > 30){
      $username = NULL; echo "Username cannot be longer than 30 characters.<br/>";
    }
  }
  else{
    $username = NULL; echo "You must enter a username.<br/>";
  }


  if(!empty($_POST['email'])){
    $email = $_POST['email'];
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
      $email = NULL; echo "Email address is not in the correct format.<br/>";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

  if(!empty($_POST['password']) || !empty($_POST['password2'])){
    $password = $_POST['password'];
    $password2 = $_POST['password2'];
    if($password != $password2){
      $password = NULL; $password2 = NULL; echo "Both passwords must be the same.<br/>";
    }

  }
  else{
    $password = NULL; $password2 = NULL; echo "You must enter your password twice.";
  }

  if(strlen($password) <10 && strlen($password2) <10){
    $password=NULL;$password2=NULL;echo "Password must be 10 characters or longer<br/>";
  }

  if(($username != NULL) && ($email != NULL) && ($password != NULL) && ($password2 != NULL)){
    $passwordLength = strlen($password);
    $hiddenPassword= "$password[0]"."$password[1]".str_repeat("*",($passwordLength-2));
    echo "<h3>Thank you for registering. Here are your details...</h3>";
    echo "Username: $username <br/>Email: $email<br/>Password: $hiddenPassword";
  }
?>

Ignore or strip HTML tags from strings in PHP

This tutorial explains how to use the htmlentities and strip_tags functions in PHP to ignore or strip HTML tags in strings. You may want to do this if you are allowing users to enter data into a form element such as a text box and don’t want the user to be able to mess up the display of your website by adding HTML tags to data.

The first function called htmlentities, is used to ignore HTML tags in strings. The second function called strip_tags is used to completely remove the HTML tags from a string. Watch the video below to see how you can protect your website or web app using these functions with forms and then scroll down to see the sample code.

Sample PHP code:

<!DOCTYPE html>
<html>
<head>
  <title>HTML entities and strip tags</title>
</head>

<body>
  <?php
    if(isset($_GET['string1'])){
      echo "Using htmlentities function: " , htmlentities($_GET['string2']), "<br/>";
      // htmlentities displays HTML tags as they are
    }

    if(isset($_GET['string2'])){
      echo "Using strip_tags function: " , strip_tags($_GET['string2']), "<br/>";
      // strip_tags will strip the HTML tags
    }
  ?>
  <h3>Enter your name below:</h3>
  <form action="" method="GET">
    First string (using htmlentities): <input type="text" name="string1"><br/>
    Second string (using strip_tags): <input type="text" name="string2"><br/>
    <input type="submit">
  </form>
</body>
</html>

Select lists and PHP

Select lists, which are created in HTML code, can be useful when a user needs to select one or more items from a list of different items. This tutorial explains how to add a select list to a form in a web page using some simple HTML code and then how to use PHP code to use the submitted data from the form.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

There are two files used in this tutorial: form.php which creates a select list and collects the user input, and action_handler.php which uses and processes the submitted data.

Here is the code for the form.php file:

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Which countries would you like to visit?</p>
    <select multiple name="countries[]" style="width:100px;">
      <option value="France">France</option>
      <option value="Brazil">Brazil</option>
      <option value="India">India</option>
      <option value="Japan">Japan</option>
    </select>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Here is the code for the action_handler.php file:

<?php
  if(isset($_POST['countries'])){
    $countries = $_POST['countries'];
    echo "You selected the following countries:<br/>";
    foreach($countries as $key => $value){
      echo "$value<br/>";
    }
  }
  else{
    echo "You must select at least one country.";
  }
?>

Date and time in PHP

In this tutorial you will learn how to set the timezone in a PHP program and how to store and display the current date and time like what you see below.

date_time_output

There are a range of different timezones you can use in PHP as well as date/time formats. The links below provide a list of timezones and date/time formats in the PHP manual:

Watch the video below and then scroll down to see the sample code from the video as well as a table containing the most commonly used date/time formats.

Sample PHP code:

<?php
  // set timezone
  date_default_timezone_set('Australia/Sydney');
  
  // display the date and time with a greeting

  function show_date(){
    return date('l, jS F H:i');
  }

  function greeting(){
    $hour = date('H');
    if($hour < 12){
      $greeting = "Good morning!";
    }
    else{
      $greeting = "Good day!";
    }
    return $greeting;
  }

  echo show_date();
  echo "<br/>" . greeting();
?>

List of commonly used date/time formats:

Argument Description Example
Y Year displayed as 4 digits 2016
y Year displayed as 2 digits 16
n Month displayed as 1 or 2 digits 9
m Month displayed as 2 digits 09
F Full name of the month December
M Name of the month as 3 letters Dec
j Day displayed as 1 or 2 digits 3
d Day displayed as 2 digits 03
l Full name of the weekday Thursday
D First three letters of weekday Thu
S Ordinal suffix displayed as 2 letters eg. rd or th or nd
H Hour in 24hr time 17
h Hour in 12hr time 5
i Minutes 30
s Seconds 50
a am/pm lowercase am
A AM/PM uppercase PM

Constants in PHP

This tutorial explains how to define and use constants in PHP. Constants contain a fixed value that cannot be changed after it has been set. Constants are useful for when you want to store data that you need to protect from accidentally being altered.

Constant names follow the same rules as variable names except they don’t start with a $ dollar sign. However, constant names are usually capitalised to distinguish them from variable names. Constants must also be defined using the define() function. Constants can contain alphanumeric values (like strings, integers, and floating point numbers) but can’t store Boolean values or represent a NULL value of an object.

Constants cannot be included in mixed strings when being displayed and must be concatenated instead. Watch the video below to find out how to define and use constants and then scroll down to see the sample code.

Sample PHP code:

<?php
  define('USERNAME','batman');
  echo 'Hello ' . USERNAME;
?>

Form elements (text, text area and password) and PHP

This tutorial explains how to create forms which include a range of form elements include text (textbox), textarea, and password.

  • text – this element is used to get a short amount of text input from the user (a single line)
  • textarea – this element is used to get longer amounts of text input from the user (more than one line)
  • password – this element is used to get password input from a user and will mask any text entered by the user with dots (or asterisks) so that other people cannot see the password

The tutorial will also show how to handle submitted form data using PHP code. Other tutorials have already shown how to use radio buttons and check boxes.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file which will contain the form (eg. form.php) and then copy the following code into it.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Username: <input type="text" name="username"> 
      Password: <input type="password" name="password"></p>
    <p><textarea name="comment"></textarea>
      <input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate file called action_handler.php which will handle the submitted form data. Copy the following code.

<?php
  $username = $_POST['username'];
  $password = $_POST['password'];
  $comment = $_POST['comment'];

  if(empty($username) || empty($password) || empty($comment)){
    echo "You must complete all fields.";
  }
  else{
    echo "Hello there, $username.<br/>";
    echo "Thank you for your comment:<br><i>$comment</i>";
  }
?>

Important note

Please note that this tutorial and sample code only explains how to use different form elements including the password element. It does not explain security or encryption when submitting sensitive information such as passwords. It is important to be aware of security and encryption when working passwords and other sensitive data before you publish a website that allows the user to submit this kind of data.

I will discuss some security methods in future tutorials but do not take any responsibility for the security of your own website.

Check boxes in forms (PHP)

This tutorial explains how to create a form which contains check boxes and how to handle the form data using PHP. Check boxes are used when you want the user to be able to select one or several options (unlike radio buttons which only allow the user to select one option at a time). Watch the video below and then scroll down to see the sample code.

Sample PHP code:

Step 1: Create a PHP file which will contain the form (eg. form.php) and copy the following code into it. This example will ask the user to select a country or multiple countries they would like to visit.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Which countries would you like to visit?</p>
    <input type="checkbox" value="France" name="countries[]"> France<br/>
    <input type="checkbox" value="India" name="countries[]"> India<br/>
    <input type="checkbox" value="Brazil" name="countries[]"> Brazil<br/>
    <input type="checkbox" value="Japan" name="countries[]"> Japan<br/>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate PHP file which will handle the submitted form data and call it action_handler.php – then copy the following code into the file.

<?php
  if(isset($_POST['countries'])){
    $countries = $_POST['countries'];
    echo "You selected the following countries:<br/>";
    foreach($countries as $key => $value){
      echo "$value<br/>";
    }
  }
  else{
    echo "You must select at least one country.";
  }
?>

Checking set values (radio buttons) in PHP

This tutorial explains how to use radio buttons in forms and check set values in PHP to ensure that the user has entered data in the form. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

Step 1: Create a PHP file (eg. form.php) which contains a form with radio buttons by copying the following code. This example will quiz the user on the capital city of Australia.

<html>
<head>
  <title>Form that checks set values</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <p>What is the capital city of Australia?</p>
    <input type="radio" name="capital" value="Sydney"> Sydney<br>
    <input type="radio" name="capital" value="Canberra"> Canberra<br>
    <input type="radio" name="capital" value="Melbourne"> Melbourne
    <p><input type="submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate PHP file called action_handler.php and copy the following code into it. This file will handle the form data.

<?php
  if(isset($_POST['capital'])){
    $capital = $_POST['capital'];
  }
  else{
    $capital = NULL;
  }

  if($capital != NULL){
    if($capital != "Canberra"){
      echo "$capital is incorrect";
    }
    else{
      echo "$capital is correct";
    }
  }
  else{
    echo "You must select an answer";
  }
?>

Form data validation with PHP

This tutorial explains how to validate data that has been submitted by a user in a form. We will look at the following types of data validation:

  • Check that a text field has not been left empty
  • Check only numbers have been entered
  • Check that an email address is in the correct format

We will use the empty, is_numeric, and filter_var functions for data validation in this example. Watch the video below and then scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file (eg. form.php) and copy the following code into that file. This file will contain the form.

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <h3>Enter a postcode and email address.</h3>
    <p>Post code: <input type="text" name="postcode"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>

Step 2: Create a PHP file called action_handler.php and copy the following code into it. This file will handle the submitted form data.

<?php
  if(!empty($_POST['postcode'])){
    $postcode = $_POST['postcode'];
    if(!is_numeric($postcode)){
      $postcode = NULL; echo "Postcode must be numeric.<br/>";
    }
  }
  else{
    $postcode = NULL; echo "You must enter a postcode.<br/>";
  }

  if(!empty($_POST['email'])){
    $email = $_POST['email'];
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
      $email = NULL; echo "Email address is not in the correct format.";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

  if(($postcode != NULL) && ($email != NULL)){
    echo "Email: $email<br/>Postcode: $postcode";
  }
?>

Handling form data with PHP

In this tutorial you will finally get to work with real user input through the use of forms and PHP code. This tutorial will show you how to create a simple PHP form which will ask for the user’s name and then display a simple message back to the user. This is what the form will look like:

Form with text box user input .
Form with text box user input .

The PHP code also includes some basic data validation that checks that the user has entered some value and asks them to enter their name if they haven’t.

Watch the video below and then scroll down to see the sample code.

Sample code

There are two files required – an HTML or PHP file which contains the form (eg. form.php), and a PHP file which handles the form data (eg. form_handler.php).

Step 1 – Create a form.php file and add the following code.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <h3>Enter your name below:</h3>
  <form action="action_handler.php" method="GET">
    <p>Name: <input type="text" name="name"> <input type="submit"></p>
  </form>
</body>
</html>

Step 2 – Create an action_handler.php file and add the following code. The empty function is used to check if a text box has been left empty by the user (if they haven’t entered a value in the text box). Make sure both files are in the same folder/directory.

<?php
  $name = $_GET['name'];
  if(empty($name)){
    echo "You must enter your name.";
  }
  else{
    echo "Hello there, $name.";
  }
?>

That’s it. Now open the form.php file in your browser and try it out!

PHP include and require functions

The PHP include and require functions are used to include other PHP files in a PHP file. For example, a webpage which needs to have a header, content section, and footer can be made into three PHP files – the main file can then include the header and the footer files in it. This is useful if you have PHP code that needs to be included in many pages across a site and can save time coding as well as reducing the risk of human error when repeating code.

The include and require functions work similarly but do have a key difference. The include function will include a file but the rest of the code will not break if the other file can’t be found or loaded. On the other hand, the require function is used when another file is required but will break the rest of the page if it can’t be found or loaded.

Watch the video below and then scroll down to see the sample code.

Sample code

There are a few files involved here. You can also download the background image and CSS code used for the template.

Step 1: Create an index.php file and add the following code.

<html>
<head>
  <title>Home page</title>
 	<meta charset="utf-8"/>
 	<link rel="stylesheet" href="theme.css" type="text/css"/>
<body>
  <?php include 'header.php'
  // can also use require which does the same thing as include
  // however, if using require and the required file is missing,
  // errors will result in none of the rest of the page loading whereas
  // include will not kill the rest of the page.
  ?>

  <div id="content">
 	<h2>Welcome to my website</h2>
 	<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.</p>
 	<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.</p>
  </div>

  <?php include 'footer.php'?>
</body>

</html>

Step 2: Create a header.php file and include the following code:

<html>
<head>
</head>
<body>
 
<div id="header">
 <h1>My website</h1>
</div>
 
<div id="nav">
  <ul>
     <li><a href="index.php">Home</a></li>
     <li><a href="about.php">About</a></li>
     <li><a href="products.php">Products</a></li>
     <li><a href="support.php">Support</a></li>
     <li><a href="contact.php">Contact us</a></li>
  </ul>
</div>
</body>
</html>

Step 3: Create a footer.php file and include the following code.

<html>
<head>
</head>
<body>
<div id="footer">
 Copyright....2015.
</div>
</body>
</html>

Step 4: Create a theme.css file and include the following code. Change the CSS styling as you wish.

#header{
 background-image:url("background.png");
 background-color:#334a94;
 height:80px;
 color:#FFFFFF;
 text-align:left;
 padding-left:20px;
 padding-top:10px;
 font-family:Arial;
}
 
#nav{
 background-color:#334a94;
 height:30px;
 padding:5px;
}
 
#content{
 width:500px;
 padding:10px;
}

h2{
  font-family:"Tahoma";
}

p{
  font-family:"Palatino Linotype";
}
 
#footer{
 background-color:#334a94;
 color:#FFFFFF;
 clear:both;
 text-align:center;
 padding:20px;
}


ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 100%;
    background-color: #334a94;
}

#nav li{
    display: inline;
}

li a {
    
  font-family:Calibri;
  font-size: 14pt;
  font-style:none;
    color: #FFFFFF;
    padding: 8px 16px 8px 16px;
    text-decoration: none;
}

li a:visited {
    background-color: #4CAF50;
    color: #FFFFFF;
}

li a:hover {
    background-color: #786ED4;
    color: #000000;
}

Step 5: Download this image and include it in the same folder along with the three PHP files and one CSS file. You can add more pages (eg. about.php or products.php) and include the header and footer in each file.

Default arguments in PHP functions

This tutorial explains how to specify a default argument in a function, if an argument is expected but has not been provided to the function. Any provided argument will override the default argument, but the default argument will prevent problems from occurring if no argument is given when it is expected.

Providing default argument cam prevent errors from occurring if no argument is provided to a function when the function is called in the program. An argument may not be provided to a function, for example, if a user does not provide some information in a form or from some other method of user input.

Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  function message($greeting, $name = "friend"){
    return "$greeting $name";
  }

  echo message("Hello there, " , "Batman");

  // Default arguments are used when no argument is given to the function.
  // In this example friend will be the default argument if no argument is given for $name.
  // However, if a second argument is provided (eg. "Batman"), then that
  // will override the default argument.
?>

Passing an array into a function with PHP

This tutorial explains how to pass an array as an argument in a function with PHP. The process of passing an array into a function is very much the same as passing a variable into a function. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

<?php
  // create the 'scores' array
  $scores = array(9,7,112,89,633,309);

  // create the 'average' function
  function average($array){
    // set 'total' to 0
    $total = 0;
    foreach($array as $value){
      // adds the value of each item in the array, one by one
      $total += $value;
    }
    // calculate the average and return the result
    return $total/count($array);
  }

  // call the 'average' function and use the 'scores' array as argument
  echo "Average = ", average($scores);
?>