Reputation: 1214
What's the best way to display a person's height with feet and inches as a string and also prevent sql injection as well as ensure proper input format? Ideally, I'd like to display it like 5'11" as an example.
$height = $_POST['height'];
$height = stripslashes($height);
The problem with this is, although in MySQL its stored as 5'11", when it outputs on the page it displays it as 5'11 without the double quote at the end.
Is there a better way to do this? I am also considering trying to separate the height into two separate textfield inputs, one for feet and one for inches.. then combining the two to display as one.
Suggestions?
Upvotes: 0
Views: 269
Reputation: 7870
You can filter the content with a little creativity to make it all consistent. In this example I'm converting everything with htmlentities, but it's not necessary to store them in the database that way. You'll want to make sure that you're using something like mysqli_real_escape_string() or quote() for PDO prior to db injection.
<?php
//$height = $_POST['height'];
$heights = array('5\' 6"','5ft 6in','5 feet 6 inches','5.5\'','5\'6"','5 1/2\'','3 foot 5 inches','2ft 8in','3 1/4in','3 1/4ft');
$patterns = array(
//Double Quotes
'!"!',
'!“!',
'!”!',
'!“!',
'!”!',
'!″!',
'!″!',
'!in(ch(es)?|\.)?!',
//Single Quotes
'!´!',
'!‘!',
'!&#[0]?39;!',
'!’!',
'!‘!',
'!’!',
'!′!',
'!′!',
'!f(oo|ee)?t\.?!',
//Conversions
'!( 1/2|\.5)'!',
'!( 1/4|\.25)'!',
'!( 1/3|\.3(3(3)?)?)'!',
'!( 3/4|\.75)'!',
//cleanup
'! (&)!',
'!;([0-9])!',
//fraction to decimal inch conversions
'! 1/2!','! 1/4!','! 1/3!','! 3/4!',
);
$replacements = array(
'"','"','"','"','"','"','"','"',
''',''',''',''',''',''',''',''',''',
'' 6"','' 3"','' 4"','' 9"',"$1","; $1",
'.5','.25','.33','.75',
);
echo "<pre>";
foreach($heights as $value){
$value = htmlentities($value,ENT_QUOTES);
echo "$value becomes ".preg_replace($patterns,$replacements,$value)."\n";
}
echo "</pre>";
?>
Output looks like
5' 6" becomes 5' 6"
5ft 6in becomes 5' 6"
5 feet 6 inches becomes 5' 6"
5.5' becomes 5' 6"
5'6" becomes 5' 6"
5 1/2' becomes 5' 6"
3 foot 5 inches becomes 3' 5"
2ft 8in becomes 2' 8"
3 1/4in becomes 3.25"
3 1/4ft becomes 3' 3"
Upvotes: 0
Reputation: 11138
To display the quotes you need to escape them:
echo "5\' 11\"";
Will output:
5' 11"
You can use addslashes to escape all characters (that need to be escaped) prior to inserting into the database. Then, for added security you should look into prepared statements.
Upvotes: 1