Is this a safe practice in php?
I am trying to make an online calculater where people can calculate using form in my site, people can POST in form and result is GET by url string. Is it safe ?
html
<form id="form1">
<input type="text" name="user_price" size=2/>
<?php echo form_dropdown('selling', $rates);?>
<input type="submit" value="submit">
</form>
php
<?php
if((int)$_GET['user_price']){
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
}else if((string)$_GET['user_price'] OR (array)$_GET['user_price']){
echo 'enter number not characters';
}else{
echo '';
开发者_如何学Go }
?>
Yes, that's perfectly safe, it just doesn't make sense. (int)$_GET['user_price']
casts a value to an integer, it does not mean "if value is an integer".
You're looking for:
if (isset($_GET['user_price'], $_GET['selling']) &&
is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
...
} else {
echo 'Please enter numbers';
}
You could make it much more concise
if (is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
} else {
echo 'Something went wrong';
}
Here is how I would code that...
$userPrice = isset($_GET['user_price']) ? $_GET['user_price']) : NULL;
$selling = isset($_GET['selling']) ? $_GET['selling'] : NULL;
if (is_numeric($userPrice) AND is_numeric($selling)) {
echo 'Total '. $userPrice * $selling;
} else {
echo 'enter number not characters';
}
Note that a good habit to get into, if echoing user submitted strings back, to wrap them with htmlspecialchars()
.
Perfectly safe, but when using GET and POST you should always declare a variable before you do anything with the form data
精彩评论