Second Sighting Logo

301 Redirect PHP

Posted in PHP by Tom on the January 23rd, 2012

How to do a 301 redirect in PHP. Remember to add right at the top of your code, before anything is sent to the browser.

<?php
header( "HTTP/1.1 301 Moved Permanently" );
header( "Location: http://www.secondsighting.co.uk" );
?>

This tells the visitor’s browser, and any search engine that visits the page, that it has moved permanently to the specified URL.

Sending HTTP Post Data Without Using a Form

Posted in PHP by Tom on the May 9th, 2008

I always forget how to do this and it’s really useful… http://www.faqts.com/knowledge_base/view.phtml/aid/12039/fid/51

Using Stored Values With Select Elements

Posted in PHP by Tom on the January 9th, 2008

Heres how to use regular expressions to transform a plain HTML select element into one that autoselects based on a previous choice. You could use this to retrieve a value from a database and automatically select the correct option in a dropdown menu. The select element in the example below is called occupation and it is stored in an array called $user_data.

search for:

<option value=”(.*)”>.*</option>

replace with:

<option value=”$1″<?php if ($user_data['occupation'] == “$1″) { echo ‘ selected=”selected”‘; } ?>>$1</option>

Make sure to rename the fields accordingly for your situation.

Simple UK Phone Number Validation

Posted in PHP by Tom on the August 2nd, 2007

This is a simple solution which should help a lot with accidental errors, but it’s still very easy for someone to enter a fake number if they want to. The first line of code removes anything thats not a number from a submitted post variable called ‘phone’. The second line checks the number begins with a 0, followed by 1-9 (’00′ is not allowed as it’s the UK dialling prefix for international calls), followed by 8 or 9 other digits. The example below works with PHP 5.2.0 & above.

$phone = ereg_replace('[^0-9]', '', $_POST['phone']);
if (!filter_var($phone, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^0[1-9][0-9]{8,9}$/")))) {
echo 'Please enter your phone number correctly';
}

Simple Email Validation

Posted in PHP by Tom on the July 3rd, 2007

Starting with PHP 5.2.0 there is a really easy way to validate email addresses – namely the filter_input function. The example below takes a submitted POST variable called ‘email’, validates it against the email format, and returns FALSE if the filter fails or the value of the variable on success.

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

Thats all there is to it.