Darren Nolan Computer Tech… and stuff

3Sep/103

Email Contact Forms

Yet another awesome service from google. reCaptcha. More on that later.  But firstly, sending from the right address.

Helping out a friend at her new(ish) job and their contact form simply sucked.  Suppose it takes a bit of a background in both PHP web coding and more so in understanding Mail protocols than anything else.

The first thing people really need to get out of the habit is trying to send emails as the person who wishes to contact you.  Take in this small example;

1
2
3
4
5
6
7
<?php
	$to = 'contact@mydomain.com';
	$subject = 'Website Contact Form';
	$message = $_POST['formMessage'];
	$headers = 'From: ' . $_POST['formEmailAddress'] . "\r\n";
	mail($to, $subject, $message, $headers);
?>

Without getting hooked up on using raw entries from $_POST, basically the above code will take your contact details and attempt to send it to yourself.   You write into the headers that this email is coming from whatever address the user entered when filling in the form.

THAT'S A BIG NO NO.  More and more mail servers today (including your own, which is where some of the issue comes) checks the IP and/or domain name of where an email is being sent from, in this case it's your webserver, and looks up that domain to see if that domain or IP address is allowed to pretend to be sending mail.  I promise no one has added in your domain details to allow to send email as them.  Certainly not the bigger dogs like Bigpond, Optus etc.

This is just one method that checks mail servers use today to check the authenticity of mail getting into people's boxes.  Otherwise you can basically be sending mail out as Google or even PayPal.

Here's what you should have done when coding your contact form.


So how's this work now?  Basically, we're saying this email we're going to get is from our OWN domain.  However when you hit the reply to start a conversation with the user that filled in the contact form, your email client will use the details in the Reply-To.  Adding the X-Mailer section there is to let severs know that yes indeed this message has been sent from a PHP script.

Because your script is now sending from your website as your own email (typically where your mailserver resides) this solves some of the more common 550 errors in emails (Email error: 550 SPF: x.x.x.x is not allowed to send mail from ...)

Doing things properly you shouldn't stop there guys.  The really good and neat way of sending mail out of your web scripts is to connect to your mail server directly, and send it from there.  Need pear with it's mail modules installed for PHP

If you don't already have this, you should lightly slap yourself and then quickly install it.
On Ubuntu

sudo apt-get install php-pear
sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime

Here's how our example would work now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
	include "Mail.php";
 
	$to = 'contact@mydomain.com';
 
	$headers['From']		= 'webmaster@mydomain.com';
	$headers['To']			= $to;
	$headers['Subject']		= 'Website Contact Form';
	$headers['Reply-To']	= $_POST['formName'] .
							'<' .$_POST['formEmailAddress'] . '>';
 
	$smtpinfo['host']		= 'localhost';
	$smtpinfo['port']		= '25';
	$smtpinfo['auth']		= true;
	$smtpinfo['username']	= 'my_mail_username';
	$smtpinfo['password']	= 'my_mail_password';
 
	$mail_message = $_POST['formMessage'];
 
	$mail_handler =& Mail::factory("smtp", $smtpinfo);
	$mail_handler->send($to, $headers, $mail_message);
?>

Naturally I'd expect you to validate your data and not just use raw data sent from the browser, but this will connect up to a SMTP server and send it off via that server (which lets your messages get signed by a range of other anti-spam measures in place today).

If you require an SSL connection to your mail server (for example, google handles your mail for you (like it does for me)) you can change the host to "ssl://hostname" and the Mail package will work it out from there.  Sadly it's not shown on the documentation about that handy little trick on the Pear page.

Another alternative is using sockets directly, which is fantastic and awesomes (and doesn't require Pear/Mail), and you can find a heap of PHP Libraries out there to give you access to do so.  Personally I'm a bit of a fan of CodeIgniter and has these sorts of things built in already.  Epic win.

GETTING SIDE TRACK HERE, but hopefully you'll start to use a neater way of sending your contact form messages out now.

Google reCaptcha adds that (sometimes) annoying little image to forms before you get to fill them in.  Basically ensuring you're human and not some spam bot with insecurities about it's epen requiring extensions (CWOTIDIDTHAR?).

It's actually really to get set up and working on your site, for anything really - not just contact forms (although it works quickly there too).  Basically you sign up for a Private and Public Key over at google and then download the quick library to use it.

After you've put it somewhere with your code files, you include the file, add some lines of code, and volia.  How easy is that.  See below;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
	require_once('recaptchalib.php');
	$privatekey = "your_private_key"; // Change this to your Private Key
	$publickey = "your_public_key"; // Change this to your Public Key
 
	if (isset($_POST['login'])) {
		// Do some validation stuffs here!
 
		// Check the Captcha
		$resp = recaptcha_check_answer ($privatekey,
		$_SERVER["REMOTE_ADDR"],
		$_POST["recaptcha_challenge_field"],
		$_POST["recaptcha_response_field"]);
		if (!$resp->is_valid) {
			// reCaptcha failed. Do stuffs
 
		} else {
			// reCaptcha all good. Do whatever else
 
		}
	}
?><html>
<head></head>
<body>
	<form method="POST" action="<?=$_SERVER['PHP_SELF'];?>">
		<input type="text" name="username" /> <br />
		<input type="password" name="password" /> <br />
		<?=recaptcha_get_html($publickey);?>
		<input type="submit" name="login" />
	</form>
</body>
</html>

You can change the "look" or theme of reCaptcha by adding a small snippet of javascript before the element appears;

1
2
3
4
5
<script type="text/javascript">
	var RecaptchaOptions = {
		theme : 'clean'
	};
</script>

The element appears in a div with the ID of "recaptcha_widget_div" so if you want to adjust margins or padding for that div it appears in (being as lazy as me and NOT wanting to have more container divs than I can poke a stick at) you can change that in your own CSS stylesheets.

And that's about it for the moment. Hope I killed loads of your time and you wish for it back.  ^_^

23May/100

Using Redmine on a cPanel server – Silly .htaccess rules

It's not nearly has hard when you know what the hell you're doing.  Oh by the way, that's not the case with me <_<  Find an installation guide elsewhere (or even adapt the actual installation guide from Redmine).  This guide is manually how to setup rewrite rules properly so you can use Redmine as ether a proper subdomain entry (redmine.yourdomain.com) or even slightly more tricky, as a subdomain entry (www.yourdomain.com/redmine).  Sadly cPanel htaccess rules generated from their interface ... suck.  Pretty badly >_>  No idea why.

MOVING ON.

Bit 1
Go into cPanel -> Ruby on Rails
Create a new application by entering the application name.  Be happy with the default location it will store your application (/rails_apps/redmine for example)
Ensure it's going to start when someone reboots the server on you (sif they'd do that anyway).  Tick "Load on Boot".
Don't bother starting the application yet.
Find out which port you've been assigned - click "URL" and you should be taken to a page that can not be displayed - you'll see something like http://yourdomain:PORTNUMBER - the portnumber folks is important.

Bit 2
Go into cPanel -> MySQL databases
Generate a new database, a new username/password and ensure you assign the new user to the database we just created.

Bit 3
Get into shell or FTP (whatever is available to you) and remove everything that's pre-generated under ~/rails_apps/redmine
Extract the latest redmine application source and put it in that folder we just cleaned out.
Copy config/database.yml.example to config/database.yml
Edit that file, change the stuff about production and what your MySQL details are (seek the real installation for more info - http://www.redmine.org/wiki/redmine/RedmineInstall)Also following that installation guide, ensure you do the following parts
Get into shell as your cpanel user and enter the following funky stuffs;
cd ~/rails_app/redmine
RAILS_ENV=production rake config/initializers/session_store.rb
RAILS_ENV=production rake redmine:load_default_data

Bit 4
In cPanel -> Ruby Applications, you can go ahead and start the server now.

Now here comes the main part of this little installation guide (there are more completed installation guides out there on the web guys.

THE IMPORTANT HTACCESS REWRITE BIT
Wherever your "public" html access is, go there and create a .htaccess file.  For example if redmine is being put in your main domain's location, your location will be ~/public_html/.htacces - if it's a subdomain it's typically ~/public_html/subdomain/.htaccess unless you specified otherwise (which I always recomment... shoving subdomains under another domains document root is tacky, especially when dealing with .htaccess)

For "Whole" domain/subdomain (http://redmine.yourdomain.com) installations, put in the following text in the htaccess file

[sourcecode language="plain"]
RewriteEngine on
RewriteCond %{HTTP_HOST} ^redmine.yourdomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.redmine.yourdomain.com$
RewriteRule ^.*$ "http\:\/\/127\.0\.0\.1\:12001%{REQUEST_URI}" [P,QSA,L]
[/sourcecode]

The two RewriteCond(itions) there are limiting this to the subdomain redmine.  If you aren't playing with a subdomain you can actually remove those two lines.
This htaccess example is "pretty much" what cPanel generates at time of writing, minus the "^.*$" part, for whatever reason they're still having ? inserted in there which naturally, causes headaches.

Now the uber tricky part.  You want it to be http://www.yourdomain.com/redmine - a "directory".
First up - edit ~/rails_apps/redmine/config/environment.rb and at the very end of the file (even after the "end" part) add the following
Redmine::Utils::relative_url_root = "/redmine"

In your htaccess file, you'll want to do the following.

[sourcecode language="plain"]
RewriteEngine On
RewriteRule ^redmine$ http://localhost:12002/$1 [P,QSA,L]
RewriteRule ^redmine/(.*)$ http://localhost:12002/$1 [P,QSA,L]
[/sourcecode]
Again, ignoring the Rewrite conditions if you aren't setting up /redmine on a subdomain.

Notice where the 12001 part is in the htaccess files, you'll want to change that to whatever port number cPanel has set your redmine application to.

Edit: Updated htaccess rule for the subdirectory. It appears that despite my efforts redmine would only work if there was a trailing slash. Without it, it wasn't working. Then I got it working the other way around.... and now... I have two rules... not ideal but it's working again. \o/

8May/102

Getting back to development

And it starts with Notepad++, because it's lightweight, awesome, sexy, and did I mention awesome.  I am a bit of a fan of Textmate on the Mac - using a combination of the font Monaco (which you'll need to source for yourself) and the VibrantInk theme created by Tyler at impoverishedgourmet.com - you too can have a nice dark scheme for your coding box.

Next up will be finding a similar solution for Netbeans.

In order to install this theme, simply go place the file into %APPDATA%\Notepad++ replacing the existing theme (I like to make backups of this shit in case I ever start to hate the contrast).

http://www.darrennolan.com/wp-content/uploads/2010/05/stykers.xml

Font is then changed in Notepad++ by going to Settings -> Style Configurator, ensure you have Global Styles (Global override) selected, and change the font to Monaco.