Aptana Studio 3

I finally took the plunge and downloaded Aptana Studio 3. Aptana is an open-source IDE or integrated development environment for web developers. The IDE supports all the latest web technologies including HTML5, CSS3, JavaScript, Ruby, Rails, PHP and Python.

It’s impressive despite having only a couple of hours playing with it. I really like the ‘code assist’ feature that comes with the IDE. I haven’t use all the features yet, but the deployment wizard, git integration, and the built-in terminal, sounds very, very inviting.

The learning curve isn’t steep. It’s just the right level for someone who may be tempted to try using an IDE. Aptana reminds me of Eclipse and a little bit of Textmate. The program does require Java, which my Ubuntu desktop already has installed.

Some people had issues with Git commits and some complaints about the program being resource hungry. I can’t comment on those yet since I’ve only been using it for a couple of hours. My first impression of Aptana Studio 3 is very good.

Str_replace

The str_replace function in PHP, is similar to the find and replace function that you’ll find in most text editors. Microsoft Word, Google Docs, Notepad, WordPad, Gedit, and a gaggle of other text editors, all have the find and replace function. It’s a very neat feature that comes in very handy when doing wholesale changes to a document.

In PHP, I use the str_replace function mostly to filter unwanted characters, like commas, quotes, etc from a certain string. The string can originate from a form or database. It doesn’t really matter. In this example, I have a string called $a. I will use the str_replace function to search for a word ‘foo’ and replace it with the word ‘bar.’

Replace Foo With Bar

$a = 'foo, is a great word.';
$b = str_replace('foo', 'bar', $a);
echo $b;

The result: ‘bar, is a great word.’

Remove Commas

$a = 'foo, is a great word.';
echo $b = str_replace(',', ' ', $a);

The result: ‘foo is a great word.’

Notice I used a shortcut to echo the string $b, while assigning to it the str_replace function. You can use str_replace to filter and replace a character, a word or a group of words from within a string.

Bluefish Blank Document Workaround

Since switching back to Ubuntu 10.04.3 LTS, I had one annoying issue with the Bluefish editor. When I double click on a PHP document, the Bluefish editor should automatically display the file. Instead, Bluefish launches a blank document.

Opening a file inside Bluefish, once it has launched, however, is not a problem. Blaming everything on Bluefish is unfair. The bug may be due to Nautilus. See discussion here. I call it a workaround because it fixes the issue, but it also creates another one. It disables opening up project files when launched.

If you don’t use project files, then by all means, use this workaround. This fix involves editing the command line options for Bluefish. Go to System > Preferences > Main Menu. You will find two Bluefish icons under Programming and Other.

Edit the command line option for the Bluefish icon under Other. Change it from bluefish -n -p %f to bluefish %F. See snapshot below. The two Bluefish icons should now have the same command line options, which is, bluefish %F.

I can now open files in Bluefish by double clicking a PHP file from within Nautilus. It’s no longer a blank document. Once again, this is workaround. It will disable opening up project files. I don’t use it, which is fine by me.

Remove index.php in Codeigniter

If you work with CodeIgniter, you will soon learn fast enough that the CodeIgniter framework, by default, uses the index.php in its URL. Here’s an example of how the URL would look like with the index.php being visible.

CodeIgniter URL

http://example.com/index.php/news/article/my_article

.htaccess

To remove the index.php from the URL, you will need to add mod rewrite rules to the .htaccess file in your main CodeIgniter directory. Use this code. Change the rewrite base to your own settings.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /ci/
 
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
 
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
 
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>

config.php

In addition, you will need to edit the /application/config/config.php file. Make sure to remove index.php reference within the file.

$config['index_page'] = '';

Adding Javascript Confirmation To Forms

One feature worth implementing when designing websites is to add confirmation to forms. A simple popup message saying “Are you sure?” can greatly enhanced the user experience. It gives users a chance to confirm or escape out of a certain function. This is particularly feature is valuable after users click the Save, Delete or Submit button.

Unfortunately, both HTML and PHP languages lack the feature to add confirmation to forms. We turn our attention to Javascript the popup confirmation message we need in our forms. Below, you will see a simple, plain vanilla, submit button inside a HTML form.

HTML Form

<input type="Submit" name="submit" value="Submit" />

To add a confirmation to our submit button, we will use Javascript’s onclick event to detect if the input object has been clicked. Here’s how we add the onclick event in our simple form.

<input type="Submit" name="submit" value="Submit"
onclick="return confirmation();" />

Javascript Confirmation

Where’s our Javascript function? Well, here it is. Now that we have added the onclick event to our submit button, we will now add our Javascript function that you can place anywhere on your page. Here it is:

<script>
function confirmation()
{
var answer = confirm("Are you sure?")
 if (answer)
 {
  return true;
 } else {
  if (window.event) // True with IE, false with other browsers
  {
   window.event.returnValue=false; //IE specific
  } else {
   return false
  }
 }
}
</script>

The if statement with window.event is for the IE browser since it doesn’t play nice like the other browsers. You can call the Javascript function multiple times on the same page every time you need a popup confirmation. So there you have it, a simple popup confirmation you can add to your forms.

Display On WordPress Single Pages Only

I recently had to display some content on my blog, only when my blog is displaying a single article or a single post. The content does not appear on the home page or any other page. Since my blog is powered by WordPress, there are several WordPress functions that I can use to detect if the current page is a single post, a home page or a WordPress Page, e.g. the About page. Here’s the code:

Single Posts

<?php if(is_single()) : ?>
My single post content goes here!
<?php endif; ?>

Home Page

<?php if(is_home()) : ?>
My home page content goes here!
<?php endif; ?>

Pages

<?php if(is_page()) : ?>
My Page content goes here!
<?php endif; ?>

The content located between the if and endif statements will be displayed only if the conditional is true. You can use this code to customize the content of your blog. You can place this code in your WordPress theme files such as index.php, home.php, single.php, and page.php.

Sanitize Your Input In PHP

Here’s a quick and tiny PHP function that I’ve used on many projects to sanitize my input forms. As you are aware of, HTML forms are one source for injecting malicious code in programs to manipulate databases or traverse server directories. To make your programs much more secure, you’ll need to sanitize your inputs before doing anything, especially when dealing with databases. One function I’ve used repeatedly in my scripts is called sanitize(). Here’s the code:

The Code

// Sanitize input
function sanitize($in) {
 return addslashes(htmlspecialchars(strip_tags(trim($in))));
}

The addslashes function returns a string with backslashes to single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte). This is particularly helpful when escaping special characters when dealing with database queries. The htmlspecialchars function converts special characters to HTML entities. For example & (ampersand) becomes &amp; and ‘”‘ (double quote) becomes &quot. This function prevents user-supplied text from containing unintended HTML markup.

The strip_tags function strips HTML and PHP tags from a string. It suppresses unwanted HTML markups from being displayed and prevents malicious PHP code from being executed. The trim function strips white space from the beginning and end of a string. For example, the string ” apple ” with white spaces will become “apple” without white spaces when the trim function is applied.

Usage

You can use the sanitize function to clean up the $_GET, $_POST, $_REQUEST and $_COOKIE input variables. In this example, we will use the sanitize function to clean up the form input called $_POST[‘name’].

$name = sanitize($_POST['name']);

Database Use

Before you can query, insert or update the database, you can use mysql_real_escape_string to escape special characters within your SQL statement to prevent SQL injections.

$name = sanitize($_POST['name']);
$name = mysql_real_escape_string($name);

There you have it. Two short and deliciously simple functions to sanitize your input and prevent malicious code from wrecking your programs. Let me know what you think.

PHP: Generate Random Alphanumeric Keys

Occasionally, you might need to generate a random alphanumeric key in your project or within your script. This article will show you how to generate a random key using several PHP functions such as: mt_rand(), in_array() and the staple while and foreach loops.

The mt_rand() function generates a random key based on the characters supplied to it. mt_round() is a direct replacement for the original rand() function. The mt_rand() function is recommended since it’s considerably faster (4 times faster) than rand().

The in_array() function checks to see if the value is already in array. in_array() prevents duplication of the randomly chosen characters within the script.

Let’s get started.

Assign Characters

In this code, several alphanumeric characters are assigned to the variable $characters. I omitted all vowels and will use both uppercase and lowercase alpha characters. In addition, I’m using numbers 1 through 9 only. I ommited zero since it can be confused with the letter O, although I’m not using the letter O in this example.

// Random characters
$characters = array("B","C","D","F","G","H","J","K","L","M","N",
"P","Q","R","S","T","V","W","X","Y","Z","b","c","d","f","g","h",
"j","k","l","m","n","p","q","r","s","t","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9");

Set The Array

We will set the variable $keys as an array.

// set the array
$keys = array();

Set The Key Length

This is the length of the random key. It’s originally set for 7 characters and can be changed to a length of your choosing.

// set length
$length = 7;

Generate The Random Key

This is main code that generates the random key. The code loops 7 times and assigns a random character to the variable $x. If $x is not in the array, it will assign the value of $x to the array called $keys[].

// loop to generate random keys and assign to an array
while(count($keys) < $length) {
       $x = mt_rand(0, count($characters)-1);
       if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}

Display The Random Key

We will use the foreach loop to display the random key stored in the $keys array. We will loop and extract each key and assign it the $random_chars variable. Finally, we will echo the $random_chars variable to display our random generated key.

// extract each key from array
foreach($keys as $key){
   $random_chars .= $characters[$key];
}
 
// display random key
echo $random_chars;

The Script

All together now. Here’s the entire script pieced together.

// Random characters
$characters = array("B","C","D","F","G","H","J","K","L","M","N",
"P","Q","R","S","T","V","W","X","Y","Z","b","c","d","f","g","h",
"j","k","l","m","n","p","q","r","s","t","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9");
 
// set the array
$keys = array();
 
// set length
$length = 7;
 
// loop to generate random keys and assign to an array
while(count($keys) < $length) {
	$x = mt_rand(0, count($characters)-1);
	if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}
 
// extract each key from array
foreach($keys as $key){
   $random_chars .= $characters[$key];
}
 
// display random key
echo $random_chars;

There you have it, a random generated key based on the assigned characters and length that we indicated in our tiny PHP script. I hope you find this short article useful on future projects. By the way, you can also use this script to generate random passwords.

Display PHP Arrays

One of the big challenges when working with any programming language is working with arrays. In this article, I will give out an example how to display arrays and how to assign variables to them. These variables can be used later on for other purposes such as storing to a database, etc.

Simple Array

In this example, we will use an array containing the following values:

$a = array('one','two','three','four');

Using Print_r

We can output the array using the print_r() function. I’ve encapsulated the output using HTML <pre> markup for readability purposes. You don’t have to use <pre>, but it just makes it easier to read especially when debugging.

echo '<pre>';
print_r($a);
// echo your closing pre tags

Output

This is the output from the code above:

Array
(
    [0] =&gt; one
    [1] =&gt; two
    [2] =&gt; three
    [3] =&gt; four
)

Using Foreach

Another way of displaying an array is using foreach. I’m using HTML <br/> break for readability purposes.

foreach($a as $b ) :
  echo $b ."&lt;br/&gt;";
endforeach;

Output

This is the output from the code above:

one
two
three
four

Variables

In addition, you can also use the following variables to display its values.

echo $a[0];     // one
echo $a[1];     // two
echo $a[2];     // three
echo $a[3];     // four

So, there you have it. A simple article explaining how to display arrays and how to assign variables to them. The fun really starts when dealing with multidimensional arrays. I will have a follow up article in the next couple days to detail multidimensional arrays.

PHP Explode

The PHP explode function can break apart variables into several smaller pieces. You can specify the splitting parameter, and the result will be returned in an array which can be echoed or use for other purposes within your script. If I have a variable called “$string” that contains a very long string, I can use PHP explode to break it apart into smaller pieces. In this example, I have a variable that contains both the directory and filename. I will use PHP explode to break them apart.

Example:

$string = "thisisalongstring/breakmeapart.php";
$shorten = explode("/", $string);

The Result:

echo $shorten[0];    // thisisalongstring
echo $shorten[1];    // breakmeapart.php

PHP explode is a fun little function.