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

Please! I Stopped Designing Websites

Yes! I’ve had enough. Its been a good learning opportunity but I won’t go far or grow in my career if I continue dabbling in this field of I.T. I don’t think I can do much with where I am. I need to do more and meaningful stuff (from a personal perspective). How can I use technology for business and socio-economic development? That’s where I’m heading.

Maybe SUPER complex web applications with DEEP business value. That I can do. Value for users and with better monetary returns (read Massive!) 😛

So, please! If you need a website, I can give you referrals or simply go to Upwork.

Have a happy and productive 2016! Cheers!

Happy 2016!
Happy 2016!

 

December 31, 2015

Posted In: Information Technology, Random Stuff, Science & Technology

Leave a Comment

$ is not a function – jQuery

Once in a while, as a web developer working on a project that is based on a Drupal, you may come across this issue especially when utilizing the jQuery javascript library:

TypeError: $ is not a function

The simple solution is to create a wrapper so that Javascript is compatible with other libraries other than jQuery. As stated in the drupal.org website:

This wrapper is an anonymous closure that provides state throughout the page’s lifetime and ensures your code does not unintentionally create/override global variables.

It also explicitly imports the global jQuery variable so that your code can use the local $ variable instead of the jQuery global. This is essential because Drupal loads jQuery with noConflict() compatibility so the jQuery library does not setup the normal $ as a global variable.

 

Reference:

  • http://drupal.stackexchange.com/questions/97061/getting-typeerror-is-not-a-function-with-or-without-jquery-update-install

March 13, 2015

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

Top 100 Sci-Fi Fantasy Books

Being a fan of Sci-Fi, I came across this interesting list.

http://www.npr.org/2011/08/11/139085843/your-picks-top-100-science-fiction-fantasy-books

Update (30/12/15):

I read ‘The Left of Darkness‘ by Ursula K. Le Guin. Weird science stuff but a great read. Imagine a world where the beings, human in nature, can change their gender biologically based on the time period of the year.

Sips coffee. Moving on!
Sips coffee. Moving on!

February 4, 2015

Posted In: Random Stuff, Science & Technology

Leave a Comment

Adventures in Farming: Onions

This year I took the risk of doing serious farming. I had postponed for a long time to participate in this venture but decided this was the year. Life is short so let’s take hold of every opportunity accorded to us.

To start off, I did a pilot project of onions on quarter an acre. I used Jambar F1 seeds from Seminis (cost around Ksh. 6800) of which were planted on this portion of the land. I planted them in Njoro, Nakuru county since I had access to water for irrigation just in case the rains did not do well. I planted the crop around May and harvested them in November.

Onions in Nets
Onions in Nets

Continue reading Adventures in Farming: Onions

December 26, 2014

Posted In: Agriculture

Tags: , ,

4 Comments

Adventures in Farming: The Beginning

As I await for my second phase of  tomato seeds to germinate at my front yard, I’m beginning a new series on farming, a passion I’ve been neglecting and postponing for a long time. This may be my holy grail, the pot of gold at the end of the rainbow. He! He!

DSC_0931
Waiting for the second generation of seeds to germinate

I started farming back in high school for educational purposes; the biggest potato I harvested was the size of a normal new born baby. Seriously, quite big but some dude decided to steal it to get a boost in his marks for his final exam (insert angry face here). But still I was number 3 in terms of the total harvest for the final practical examination. Continue reading Adventures in Farming: The Beginning

December 4, 2014

Posted In: Agriculture

Tags: ,

Leave a Comment

Java: Static Methods and Instance Methods

Static Methods

They are class methods. They are not associated with a particular object. Simply put, you don’t have to declare a new object based on a class to use this method.

Example:

String t = String.valueOf(n);

Instance Methods

This operates on an object (an instance of a class). They utilize the instance variables of that object. Simply put, you need to create a new object to make use of this kind of method.

Example:

String s = new String("Coding is an awesome career!");
int n = s.length();

Further reading:

  1. http://www.dummies.com/how-to/content/what-is-the-static-keyword-in-java.html
  2. http://www.leepoint.net/notes-java/flow/methods/50static-methods.html

 

August 29, 2014

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