Composer Does Not Install

Image from Composer website https://getcomposer.org/
Image from Composer website https://getcomposer.org/

Today, I’m trying out a new PHP framework called Slim, a micro-framework. It has a minimal foot print as stated but I will find out by the end of the day. I’m building a simple web app that pulls data from a Piwik instance using the Piwik Repotrting HTTP API. I need to build something quick hence the use of this small framework. The creator’s of the framework say that an afternoon is enough to learn the framework (I hope so). Of course, a good background in PHP is a must.

Composer, a PHP dependency manager, is a first requirement to be able to install Slim. However, as I was installing composer in a folder, I got the following error (I’m developing in a Mac OSX environment):

All settings correct for using Composer

Downloading…

Could not create file /Users/brianbirir/Sites/piwik/composer.phar: fopen(/Users/brianbirir/Sites/piwik/composer.phar): failed to open stream: Permission denied

Download failed: fopen(/Users/brianbirir/Sites/piwik/composer.phar): failed to open stream: Permission denied

fwrite() expects parameter 1 to be resource, boolean given

after writing the following command:

curl -sS https://getcomposer.org/installer | php

Solution:

Just add sudo before curl and php  and composer shall install. Remember composer should be installed in the folder where your project will run from or where the source code is stored.

 

UPDATE One:

Because I need to implement the project ASAP, I decided to move on with CodeIgniter, a framework I’m very familiar with (I’ll learn Slim later, maybe the coming week). But to pull the data from the API, I need to use something that would consume the JSON via HTTP, basically a HTTP client. I decided to use Requests for PHP. It does not rely on cURL and is framework agnostic. There are other PHP REST clients (e.g. Guzzle) but this is the simplest (See page on Why Requests). I will post another blog article on using Code Igniter together with Requests for PHP.

January 13, 2016

Posted In: Information Technology

Tags: , , ,

Leave a Comment

Form Validation – Server Side

Oh! What would we do without web forms? No tweeting, a blank Facebook status update, a blank CV on your LinkedIn profile, or the inability to purchase online that expensive smart phone you have been saving for.

Web forms are an integral part of websites; they allow us to interact with different web systems. We use them everyday for various stuff e.g. business transactions, social interactions. And of course they are vulnerable to various risks such as hacking, wrong information storage or no information at all.

In this article and the next one we will look at form validation. Validation of forms is done to ensure that the correct data has been inserted into the form or required data is not missing from a form input such as the text field. Forms inputs are created using HTML and they are of various types:

  • Text field
  • Text area
  • Radio buttons
  • Select list
  • Check box
  • Submit button

Forms can be validated on the client side or the server side. The client side validation means the form is validated on the web browser before the data is submitted to a web server while in server side validation the form data is submitted to the web server first and validated there. If all is not ok, the server responds with a negative feedback hence prompting the form’s user to insert data again.

In this post we’ll focus on server side form validation; I don’t want to bore you with a very long tutorial 🙂

At the same time we’ll look at sanitizing form data i.e. making sure that any data input by a user is void of characters that may be malicious to the database or the user. User form input can be laced with malicious code (Javascript code) that a hacker can utilize to either insert bad data or redirect a user to another malicious harmful  file.

Server Side Validation

We’ll create a simple form for sending a user’s name, email address and phone number as shown in the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Form Test </title>
</head>
<body>
	<form name="user-form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
		<label>Name</label>
		<input type="text" id="user-name" name="name">

		<label>Email</label>
		<input type="email" id="user-email" name="email">

		<label>Phone No.</label>
		<input type="text" id="user-phone" name="phone">

		<input type="submit" value="Send" name="user-form-btn" id="user-form-btn">
	</form>
</body>
</html>

You will notice that the action attribute for the form has a strange value. We’ll insert the PHP code that will process the form’s data in the same file as the form. The PHP code will be above the HTML code and in the action attribute we will use:

action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”

I will explain later in the article what the above code snippet means. The PHP code should be as follows:

<?php
// define variables and initialize with empty values
$nameError = $emailError = $phoneError = "";
$userName = $userEmail = $userPhone = "";
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["user-name"])) {
        $nameErr = "Missing";
    }
    else {
        $name = $_POST["user-name"];
    }
 
    if (empty($_POST["user-email"])) {
        $addrErr = "Missing";
    }
    else {
        $address = $_POST["user-email"];
    }
 
    if (empty($_POST["user-email"]))  {
        $emailErr = "Missing";
    }
    else {
        $email = $_POST["user-email"];
    }
}
// Beginning of HTML code
?>

PHP Code Demystified

  1. The variables are initially set to empty.
  2. Using an IF statement, we check whether the form has been submitted by the request type. In this case it’s the POST request method.
  3. The empty() function checks if the fields are empty i.e. do not have any data. Does the form have values you can use? If they are empty an error message is displayed using the error variables, otherwise the form data is collected and stored in the variables like the $userName variable.

What is $_SERVER[“PHP_SELF”]?

Since we are submitting data to the page itself, we’ll use the $_SERVER[“PHP_SELF”] super global variable. Remember the PHP code for processing the form data is on the same page as the HTML form.

However, $_SERVER[“PHP_SELF”] can be exploited by hackers to insert malicious code in process called XSS (Cross Site Scripting). To protect our form we make use of the htmlspecialcharacters() function. This is used here to change specific HTML characters to their HTML entity names. For example < and > HTML characters are &lt and &gt entity names respectively. The use of htmlspecialcharacters() is a way of form sanitization.

To further the sanitization process, we can strip off unnecessary characters such as extra space (very common with users) and remove back slashes using the trim() and the stripslashes() functions respectively. These two can be combined with the htmlspecialcharacters() into one function to make our code look more clean. So no need of using htmlspecialcharacters() in the form’s action attribute:

<?php
// define variables and initialize with empty values
$nameError = $emailError = $phoneError = "";
$userName = $userEmail = $userPhone = "";
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["user-name"])) {
        $nameErr = "Missing";
    }
    else {
        $name = input_data($_POST["user-name"]);
    }
 
    if (empty($_POST["user-email"])) {
        $addrErr = "Missing";
    }
    else {
        $address = input_data($_POST["user-email"]);
    }
 
    if (empty($_POST["user-email"]))  {
        $emailErr = "Missing";
    }
    else {
        $email = input_data($_POST["user-email"]);
    }
}
function input_data($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
// Beginning of HTML code

?>

Ensure you follow the proper order of sanitizing form data (trim -> remove slashes -> change html special characters) as shown in the code above.

Hence our form is now secure from villains 🙂

A Better and New Way of Sanitizing Form Data

We can do by  using the filter extension of the most recent PHP version. For example:

$user_name = filter_input(INPUT_POST, ‘user_name’, FILTER_SANITIZE_STRING);

There are various types of sanitizing filters. Check them out here on the official documentation  of PHP.

Finishing

The error message placeholders can now be inserted into the HTML form so that when the validation is negative, an error message is displayed. For example:

can be placed right below the name text field input. We can then style the message, maybe with a block that has a light red background, has padding and is rounded. For example:

Error

.error {
  display:block;
  color: #a94442;
  background-color: #f2dede;
  border-color: #ebccd1;
  padding:15px;
  border-radius:5px;
}

So now our form is complete. You can access the full code (gist), two versions, from my github library as shown below; there are two versions since we have approached two ways of sanitizing the form i.e. using htmlspecialcharacters() differently. On a different note, here’s how you can insert gist in a WordPress post from from a Github repo.

Version One:

Version Two:

In the next article we will look at validating the form from the client side. The client side will be divided into two part: Javascript and HTML5.

Further Reading

February 7, 2015

Posted In: Information Technology

Tags: ,

Leave a Comment

PHP: Types of Arrays

Arrays are means of storing related data (a collection of variables) in programming languages. This article on Java arrays gives a good and simple introduction to arrays. Yeah! It’s a different programming language from PHP but the concept of arrays is the same across different programming languages (the code snippets below are of the PHP language).

Numeric Arrays

They use numbers as access keys i.e.

//Syntax
$variable_name[n]=value;
//or
$variable_name = array(n=>value,...);

//Example
$fruits[0]="Apple";
$fruits[1]="Banana";
$fruits[2]="Orange";
//alternatively
$fruits = array(0=>'Apple',
1=>'Banana',
2=>'Orange');

Associative Arrays

They use descriptive names for id keys i.e.

//Syntax
$variable_name['key_name']=value;
//Or
$variable_name = array('key_name'=>value);

//Example
$persons['Mary']='Female';
$persons['John']='Male';
$persons['Mirriam']='Female';
//Or
$persons=array('Mary'=>'Female',
'John'=>'Male',
'Mirriam'=>'Female');

Multidimensional Arrays

These are arrays that contain nested arrays. They allow programmers to group related data. A good usage of this in real world software is the creation of Drupal custom forms especially in pre-processor functions that are found within the template.php or .module files.

$movies = array(
'comedy'=>array('Pink Panther','Big Momma'),
'action'=>array('Die Hard','Expendables'),
'epic'=>array('The Lord of the Rings'),
'Romance'=>array('Romeo and Juliet')
);

August 1, 2014

Posted In: Information Technology

Tags: ,

Leave a Comment