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

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

Undefined Variable: title

Notice: Undefined variable: title in include() (line…..

I came across the aforementioned issue while developing a custom Drupal template from scratch; I will post a link to the final work later on.

The consequence was that the block’s title was not displayed even if the title has been set in the admin panel. This issue normally arises from block.tpl.php and can be solved by using the following Drupal HTML5-based code (original Drupal block template code):

<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <?php if ($block->subject): ?>
    <h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
  <?php endif;?>
  <?php print render($title_suffix); ?>
  <section class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </section>
</section>

Reference:
https://www.drupal.org/node/1515344

July 14, 2014

Posted In: Information Technology

Tags: , ,

Leave a Comment

Customization of “Submitted by” Node Field

When a user posts a new node content, by default there’s data below the title that provides info on the user who posted the content and the date on which it was posted. For example:

Submitted by Admin on Sat, 11/09/2013 – 21:05

Personally it took me a while to understand how this field could be customized for example to “Posted by Admin on 24 Mar 2014”. The customization involves:

  • template.php
  • a pre-processor function (which is placed in the template.php)
  • PHP date() function – it would be great if you had deeper understanding of this function. Just head over to PHP.NET for more info on this function.

In this case, I used Bartik as my template; the default template for any Drupal 7 installation. The pre-processor function used is the theme pre-processor for the node i.e.

function bartik_preprocess_node(&$variables) {

}

All pre-processor functions are housed either in Continue reading Customization of “Submitted by” Node Field

June 19, 2014

Posted In: Information Technology

Tags: , ,

Leave a Comment

Wi-Fi Repeater

I was recently tasked with boosting the Wi-Fi signal within the office premises. The primary Wi-Fi source was 10 m away from the office and within a separate building. The device was in a small study room and about four walls stood between us and the device hence a low signal reception. Two solutions presented themselves:

  1. Buy a Wi-Fi repeater
  2. Use an existing Wi-Fi router as a repeater

Solution no. 2 seemed better in the long run as it made both economic and scalability sense i.e. the router can be different modes unlike a repeater which, once bought, remains a repeater. I had two Wi-Fi routers, a Cisco Linksys and a TP-Link.

repeaters

The Cisco Linksys E900 was the original router connected to the ISP modem but I replaced it with the TP-Link one since it was more powerful in terms of signal range. The Linksys would therefore act as a repeater. But I would bridge both routers without the use of an Ethernet cable since both devices were located in two separate neighbouring buildings. The solution was to create a wireless bridge as explained in this article.

However, the firmware loaded on the Linksys router did not have the option of creating a repeater. This limitation prompted me to do more research and I come across an open source firmware called DD-WRT for routers and embedded systems; this firmware supports Repeater mode for routers as indicated on this blog article. There’s a database list for supported devices; the E900 is on the list and therefore I followed the instructions at this link.

I followed the instructions to the letter since any mistake would have bricked the device. So ensure that when you’re flashing your router with a new different firmware, your device type/ model is supported.

May 20, 2014

Posted In: Electronics, Information Technology

Tags: , ,

Leave a Comment

Display $tabs based on Role Type

drupal_branding_2012I came across an issue today whereby questions created by a certain user were editable by other users. The ‘view’ and ‘edit’ tabs were visible but the preference was that they would only be visible to the creator of the question. I checked the permissions page (admin/people/permissions) but everything was okay since each role could edit its own content but not all content.

To solve this problem I made use of the following code:

[php]
global $user;
if ($node->;uid == $user->uid || in_array(‘administrator’,$user->roles)){
if ($tabs = render($tabs)): ?>;

<!–?php endif; } ?–>;
[/php]

This code simple says the tabs will be displayed if the current logged in user is the creator of the question node or is the super administrator. This code can be used for other kinds of content types.

April 28, 2014

Posted In: Information Technology

Tags: ,

Leave a Comment