Code and Coffee

Archive for 'Code Snippets'

Easy MySQL Backups on a Windows Server

Posted on February 27, 2008, under Code Snippets, How To, IIS, Software, Windows.

During the re-launch of BlueCrestStudios we moved to a Windows server. It was part of our initiative to take things back to our roots, and make things simpler. Because we run a fair amount of PHP applications we went with MySQL as our database. MySQL comes with a great little application called "mysqldump" which simply enough dumps your data to a SQL file. This little tool, combined with the free and great 7Zip makes for simple and great database backups. It’s best to dump your database onto a separate drive then where the data is stored, offers a little redundancy.

Now before we get started, I know some of you are thinking there is no need for this if you hosting company does backups. True, yes any good hosting company should do regular backups of all your data. However, I find it good to have a dump of our databases for that oops situation, and not involve the hosting company if we need to recover a database or table or row. In addition, you can schedule dump every other hour, or more regularly then your hosting company does backups.

So here is our script, let’s see what we are doing here:

   1: set ARCHIVE=E:\Backups\MySQL\%DATE%.zip
   2: set FILE=E:\Backups\MySQL\Backup.sql
   3: DEL %ARCHIVE% /f /q
   4: "C:\Program Files\MySQL\bin\mysqldump.exe" --all-databases --user=YOURMYSQLUSER --password=YOURMYSQLPASS > %FILE%
   5: "C:\Program Files\7-Zip\7z.exe" a -tzip %ARCHIVE% %FILE%
   6: DEL %FILE% /f /q

Basically we are dumping the database daily here, to an archive that holds the day of the week. The variable "ARCHIVE" holds to archive for today that will be created. The "FILE" variable holds the temporary dump file before we compress it, it is deleted after the compression just to clean up after ourselves.

  • Line 3, we are deleting the current backup archive just incase.
  • Line 4, we are doing the actual dump. You need to set your mysql user and password , a note do not use root!
  • Line 5, we are doing the actual creating of the archive. SQL dump files compress very well, so this is a space saver step.
  • Line 6, we are deleting the temporary backup file as mentioned above.

The tactics above can be enhanced greatly, as you can do dumps based on database, time, and get very elaborate on this. As an extra step I am using my Windows Home Server to download the dump nightly via FTP. Simple, elegant, fairly robust, and useful.

Popularity: 8% [?]

No Comments



How To: Simple Error Pages With .htaccess

Posted on September 6, 2007, under Code Snippets, How To, Web Hosting.

HTTP error pages are more important than some may think. If you have a visitor or a customer to your site and they reach an error, you want to display a message and give them alternatives to find the content they are looking for. Most graphical control panels from hosting companies give you the option to easily setup error pages, but if you are in a situation where you need to create error pages on your own .htaccess is the way to go. In two easy steps you can have error pages up and running.

Step 1: Create your .htaccess File

Create a file called .htaccess and put the following contents in this file. Then place this file in the root “/” directory of your web server, where your web content goes.

[ftf]

ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

[/ftf]

Step 2: Create Error Pages

Now you  want to create the above HTML files with their respective names. In these files you can put any sort of message to your visitors. It is a standard HTML file, no special rules apply.

Done!

Told you it was easy. Not you should be able to test it out by going to a page that does not exist on your website, and getting to the appropriate page above.

Popularity: 5% [?]

No Comments



How to Make a Password Strength Meter Like Google v2.0

Posted on July 16, 2007, under Code Snippets, Development, How To, Security, Web Design.

Previously, in Part 1 of How to Make a Password Strength Meter Like Google I went over the basics on how to get a password strength meter up and running on your site. I got a lot of feedback on this article, mostly commenting on needing a better algorithm to determine if a password is secure or not. The algorithm I implemented in part 1 was mostly just for show. I did not further build out the algorithm because I wanted to leave it up the end user to determine what they considered a secure password or not. Furthermore, I did not want to make a scenario where a flaw in my code would be present in any sites out there that implement this.

After further research in the area of secure passwords, I am further building out the original code base to better determine a secure password from an insecure password. Here are the parameters used for measuring a secure password in version 2.0:

Password Length:

5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more

Letters:

0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case

Numbers:

0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers

Characters:

0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character

Bonus:

2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters

Password strength is measure by the percent of the above:

>= 90: Very Secure
>= 80: Secure
>= 70: Very Strong
>= 60: Strong
>= 50: Average
>= 25: Weak
>= 0: Very Weak

Implementation of the code should be the same as version 1.0. The next version will have the ability to blacklist common dictionary words. Hope this works out better than version 1.0.

Code: Version 2.0

Popularity: 28% [?]

20 Comments



How to Make a Password Strength Meter Like Google

Posted on June 27, 2007, under Code Snippets, Development, How To, Security, Tools and Services, Web Design.

pass_strength.pngPassword strength meters are becoming more and more popular amongst web services. Google uses one when creating a Google account. One can argue how useful these meters really are, but non-the-less they are fairly cool for users. So how does one go about making one of these meters? Well it’s fairly straight forward.

The basic break down is we add an event handler on your password field that will check the password for every key input the user types. This allows for an updated meter as the user types the password. When you get into the algorithm that actually checks how secure a password is, there are many routes you can go. When researching for this project, I chose to base my code off of the kind folks over at Intelligent Web. There theory is to calculate how many different combinations there are for the password you enter, then determine how many days it would take to crack your password. The algorithm returns a percentage that we then in turn convert to a nice GUI for the end user to see. So let’s take a look at the code:

The JavaScript is fairly straight forward. There are settings at the top for different checks to enable or disable. Here is the JavaScript:

[ftf]
// Password strength meter v1.0
// Matthew R. Miller - 2007
// www.codeandcoffee.com
// Based off of code from http://www.intelligent-web.co.uk

// Settings
// — Toggle to true or false, if you want to change what is checked in the password
var bCheckNumbers = true;
var bCheckUpperCase = true;
var bCheckLowerCase = true;
var bCheckPunctuation = true;
var nPasswordLifetime = 365;

// Check password
function checkPassword(strPassword)
{
// Reset combination count
nCombinations = 0;

// Check numbers
if (bCheckNumbers)
{
strCheck = “0123456789″;
if (doesContain(strPassword, strCheck) > 0)
{
nCombinations += strCheck.length;
}
}

// Check upper case
if (bCheckUpperCase)
{
strCheck = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
if (doesContain(strPassword, strCheck) > 0)
{
nCombinations += strCheck.length;
}
}

// Check lower case
if (bCheckLowerCase)
{
strCheck = “abcdefghijklmnopqrstuvwxyz”;
if (doesContain(strPassword, strCheck) > 0)
{
nCombinations += strCheck.length;
}
}

// Check punctuation
if (bCheckPunctuation)
{
strCheck = “;:-_=+\|//?^&!.@$£#*()%~<>{}[]“;
if (doesContain(strPassword, strCheck) > 0)
{
nCombinations += strCheck.length;
}
}

// Calculate
// — 500 tries per second => minutes
var nDays = ((Math.pow(nCombinations, strPassword.length) / 500) / 2) / 86400;

// Number of days out of password lifetime setting
var nPerc = nDays / nPasswordLifetime;

return nPerc;
}

// Runs password through check and then updates GUI
function runPassword(strPassword, strFieldID)
{
// Check password
nPerc = checkPassword(strPassword);

// Get controls
var ctlBar = document.getElementById(strFieldID + “_bar”);
var ctlText = document.getElementById(strFieldID + “_text”);
if (!ctlBar || !ctlText)
return;

// Set new width
var nRound = Math.round(nPerc * 100);
if (nRound < (strPassword.length * 5))
{
nRound += strPassword.length * 5;
}
if (nRound > 100)
nRound = 100;
ctlBar.style.width = nRound + “%”;

// Color and text
if (nRound > 95)
{
strText = “Very Secure”;
strColor = “#3bce08″;
}
else if (nRound > 75)
{
strText = “Secure”;
strColor = “orange”;
}
else if (nRound > 50)
{
strText = “Mediocre”;
strColor = “#ffd801″;
}
else
{
strColor = “red”;
strText = “Insecure”;
}
ctlBar.style.backgroundColor = strColor;
ctlText.innerHTML = “” + strText + ““;
}

// Checks a string for a list of characters
function doesContain(strPassword, strCheck)
{
nCount = 0;

for (i = 0; i < strPassword.length; i++)
{
if (strCheck.indexOf(strPassword.charAt(i)) > -1)
{
nCount++;
}
}

return nCount;
}
[/ftf]

On the HTML side, I have setup a simple form to display the interaction the user will receive.

[ftf]

Password Strength Meter - Demo

Password:

Password Strength:

 

[/ftf]

The magic lies inside the event handler I spoke about above. The “onkeyup” event passes the current password, and the ID for this input item. The ID is used to reference the below div tags that show the strength meter and text. The ID allows for you to have more than one password meter per form, per page.

[ftf]

[/ftf]The algorithm can be enhanced if you wish to get more complicated with the strength checking. One can also adjust the colors and text for the various strength levels displayed to the user.

[ftf]

// Color and text
if (nRound > 95)
{
strText = “Very Secure”;
strColor = “#3bce08″;
}
else if (nRound > 75)
{
strText = “Secure”;
strColor = “orange”;
}
else if (nRound > 50)
{
strText = “Mediocre”;
strColor = “#ffd801″;
}
else
{
strColor = “red”;
strText = “Insecure”;
}
[/ftf]

Further features could be displaying when a user has not entered a valid password, for example not a long enough length.

Here is a demo of the above code, and download links so you can implement this into your sign up pages. Enjoy!

Password Strength Meter - Demo

Password:

Password Strength:

Right Click to Download:

pwd_strength.js

demo.html

Popularity: 100% [?]

73 Comments

Implementing a Captcha with Ruby on Rails in 10 Minutes or Less

Posted on June 20, 2007, under Code Snippets, Development.

I needed to put together a captcha fifteen minutes before a demo the other day, so I scrambled a researched for five minutes and settled on Simple Captcha. It had the features I needed, and looked like it could be implemented fast. So how did I accomplish this, well simple:

Install ImageMagick:

You can get your hands on the binary releases here, and install them appropriately for your Operating System.

Install RMagick:

On Linux, it was actually as simple as this:

sudo gem install rmagick

Here are the install instructions for OSX and for Windows you will need to get the rmagick-win32 gem.

Install the Simple Captcha Plugin:

From your application root, you can run:

ruby script\plugin install svn://rubyforge.org/var/svn/expressica/plugins/simple_captcha

Done!

In Your Code:

To show a captcha in your view, just use the following tag:

<%= show_simple_captcha %>

There are further formatting options that you can use to configure the captcha image.

In your controller to validate:

—-
if simple_captcha_valid?
end

—-The site has further examples on how to implement a model based approach, but my quick needs this was good. Later on I went back and cleaned it up some, and attached it to a model with further conditions.

If you already have ImageMagick install, getting up and running with Simple Captch will be even quicker. For some Linux distributions, you might have to install ImageMagick from source which might cause some problems for those not too familiar on how to do this.

Simple Captcha Features:

  • Provides eight different style of images
  • Can be implemented as controller based or model based
  • Automated removal of old images(one hour old)
  • Now, we can add customized CSS to the image, lable and the text field
  • Simple Captcha will bypass the functional/unit tests, so the there will not be any mess in our test cases.
  • Provides three levels of distortion of images as low, medium or high… so now, we have three levels for complexities of images.

Popularity: 13% [?]

3 Comments

How To Remove the Nofollow Tag From WordPress Comments

Posted on April 3, 2007, under Blogging, Code Snippets, Development, How To, Spam, WordPress.

Mitchell Harper recently posted an interesting article on the nofollow link in blog comments. If you are not familiar with the nofollow tag, it tells search engines not to count the link back the the users site which in turn increase page rank and all that fun stuff. So your visitors are leaving a comment, but not reaping any of the benefits of it. The reason for this tag is mostly to discourage spam, but it really doesn’t discourage any spam as the spammers still get their URL to the users viewing the comment.

I have been waiting to remove the nofollow tag from my comments here at Code and Coffee until I was comfortable that no spam was getting through. There is no spam here on Code and Coffee, and if some slip through the cracks and make it onto the site it’s removed quickly. My spam solution consists of Akismet and Spam Karma 2, which does a great job of filtering our spam.

So today I removed the nofollow link from the authors URL in the comments, nofollow tags still remain in the URL’s inside the comment text for the mean time. I will keep it this way as long as this does not get abused. So how can one do the same to their Wordpress blog and spread the link love? Easy, here’s the plug in.

[ftf]
/* Plugin Name: Remove Nofollow
Plugin URI: http://www.seopedia.org
Description: This plugin will remove the nofollow attribute from the comment author URL, but will leave the nofollow to any links withing the comment's body.
Version: 1.0
Author: Cristian Mezei
Author URI: http://www.seopedia.org
*/

function remove_nofollow($nofollow)
{
$nofollow = preg_replace("/rel='external nofollow'>/”,”rel=’external’>”, $nofollow);
return $nofollow;
}

add_filter(’get_comment_author_link’, ‘remove_nofollow’);
?>

[/ftf]

Happy commenting!

Popularity: 8% [?]

2 Comments