PHPVirtualBox is a web-based program that allows you to control a remote Virtualbox GUI. PHPVirtualBox is ideal for systems that don’t have remote GUI access. Access is done via a browser. Remote virtual machines can be started and stopped, shutdown, and rebooted. In addition, snapshots can be taken, deleted and restored remotely via the browser. Howtoforge.com goes over the installation of PHPVirtualbox in this short article.
Category Archives: PHP
Validate IP Addresses in PHP
Let’s say you were given a task to validate an IP address in a custom script. One approach is to use regular expressions and use pattern matching to see if user input is correct or not. In this example, we will use a regular expression below to validate IP addresses.
We assume user input is done via a form. First things first, we need to sanitize the input. Once sanitized, we can then test the input against the regular expression using a PHP function called the ereg().
// the regular expression for valid ip addresses
$reg_ex = '/^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$/';
// sanitize input from form
$ip_address = addslashes(htmlspecialchars(strip_tags(trim($_POST['ip_address']))));
// test input against the regular expression
if (ereg($reg_ex, $ip_address)) {
// ip address is valid
} else {
// ip address is not valid
}
The result is, we now have a facility to check the validity of IP addresses. We can now perform additional steps when the IP address is valid, or display errors if the IP address is invalid.
MySQL mysql_connect new_link
I want to share a database connection access problem I had last week, while working with a custom PHP script inside WordPress. I had created this WordPress Page Template containing some PHP code that needs access to the database. The problem was that the database connection for my custom script overwrote the WordPress database connection that was previously establish, causing certain parts of WordPress to not display properly.
It took me a while to figure out that it was the newer database connection of my custom PHP script that was causing the previously established WordPress database connection to disappear. Hence, certain parts of the WordPress page were not displayed. Little did I know, that the fix was quite simple. So, here’s a sample of my mysql_connect code. Prior to this line, I’ve already set the variables.
Mysql_connect
$db=mysql_connect($host,$username,$password);
The Fix
Simply add a fourth parameter called new_link and set it to TRUE.
$db=mysql_connect($host,$username,$password,TRUE);
What this does is basically telling mysql_connect to establish a new connection, while keeping the older mysql_connect connection around, in case we need to access it at a later time. It’s amazing how one little switch in a command can make a huge difference to this seemingly simple code. Anyways, adding a fourth parameter and setting it to TRUE was the solution.
Calculating Dates in PHP
Displaying dates in PHP is a no brainer. You simply echo the date() function to display the current date. For example, echo date(‘Y-m-d’) will display the current date in the ISO date format of ’2012-02-27.’ However, calculating dates in the past or in the future is a tiny bit more tricky. For accuracy, I recommend that you use mktime(), which converts time to Unix timestamp. You can then perform date calculations in Unix timestamp which is much more accurate. You do have the option to change the format back to ISO, if you desire. Here are a few examples.
Display the current date:
echo date('Y-m-d');
Output: 2012-02-27
Convert to mktime:
$t = mktime(0, 0, 0, date(“m”), date(“j”), date(“Y”))
Display the start of the current month:
echo date('Y-m-d', mktime(0, 0, 0, date("m"), 1, date("Y")));
Output: 2012-02-01
Display the end of the current month:
echo date('Y-m-d', mktime(23, 59, 59, date("m")+1, 0, date("Y")));
Output: 2012-02-29
Display the start of last month:
echo date('Y-m-d', mktime(0, 0, 0, date("m")-1, 1, date("Y")));
Output: 2012-01-01
To display the end of last month:
echo date('Y-m-d', mktime(23, 59, 59, date("m"), 0, date("Y")));
Output: 2012-01-31
Display the start of next month:
echo date('Y-m-d', mktime(0, 0, 0, date("m")+1, 1, date("Y")));
Output: 2012-03-01
Display the end of next month:
echo date('Y-m-d', mktime(0, 0, 0, date("m")+2, 0, date("Y")));
Output: 2012-03-31
This code is very flexible. If you like to display the dates to any other format, you can change the date format to any format that you like. Check out all the different date formats. I hope this was helpful.
Demand For Mobile Developers
The number of users accessing the Internet will double by 2016. The driving force behind the numbers are the emerging markets. Most of these new users will access the web via mobile phones.
Currently, there are 3 billion Internet users, according to Google. There are 200 million new Internet users every year. About 80% of the new users access the web via mobile phones.
What this means is, there are plenty of opportunities for mobile developers. Remember the good old days when blocks of ice were sold by the thousands by ice manufacturers. They made a handsome profit back then.
But, the arrival of the refrigerator forever changed the landscape. Companies simply folded and moved on to something more profitable. It will be the same story for many technologists today.
The shift is on. Mobile development will be on the rise. There will be a huge demand for mobile developers. It’s time for many of us to change gears.
CodeIgniter Form_Dropdown
I had a little problem using CodeIgniter’s form_dropdown the other day. Form_dropdown produces an output similar to HTML’s form select option. I was trying to retrieve data queried from a database and display the result in a form. Well, after several test and trials, I finally got the script to work. Here’s how I did it.
Form_Dropdown
The form_dropdown function typically has 3 options. The first option is the fieldname. The second option is the option data usually laid out in an array. The third is the selected data.
form_dropdown(‘name’, array(’1′=>’one’,’2′=>’two’,’3′=>’three’),1);
This produces:
<select name=’name’>
<option value=”1″ selected=”selected”>One</option>
<option value=”2″>Two</option>
<option value=”3″>Three</option>
</select>
CodeIgniter
In CodeIgniter, I have a simple script that stores bookmarks. I categorize my bookmarks using tags. When adding bookmarks, I call on the get_dropdown_tags function in Models to retrieve all the tags and display them in array that I can use with form_dropdown. Here are my CodeIgniter entries.
Controller:
$data['tags'] = $this->links_model->get_dropdown_tags();
Models:
function get_dropdown_tags()
{
$tags = $this->db->query(‘select distinct tag from links’);
$dropdowns = $tags->result();
foreach ($dropdowns as $dropdown)
{
$dropdownlist[$dropdown->tag] = $dropdown->tag;
}
$finaldropdown = $dropdownlist;
return $finaldropdown;
}
Views:
In views, I’m simply calling the form_dropdown function using the $tags array passed on by the controller. It’s a pretty neat way to recall data from a database and outputting them in form_dropdown.
<?=form_dropdown(‘tag’,$tags);?>
Finally, a dropdown list that works.
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'] = '';