Tag: RPS

Test a Form Entry Against a CSV File.

The simple way.

<?php
/**
* Test for post; check against list; return error if bad.
*/
function check_data($input){
	//if the input is null, go no further;
	if(empty($input))
		return 'Please enter a valid code.';
	//if the input isn't 6 alphanumeric characters, go no further
	if(!preg_match('/[A-Za-z0-9]{6}/i',$input))
		return 'The code provided is not valid.';
	//finally, test against the list
	$filepath = dirname(__FILE__).'/data/datafile.csv';
	if (($list = fopen($filepath, "r")) !== FALSE) {
		while (($data = fgetcsv($list, 1000, ',')) !== FALSE) {
			if($input == $data[0]){
				header('Location:'.$data[1]);
				die();
			}
		}
		fclose($list);
	}
	return 'The code provided is not valid.';
	}
if($_POST)	
$error = check_data($_POST['code']);
?>