I start to learn php and create a code to learn how to use the GET/POST
in php code. So I heard an unsafe code can be executed through the input, so I create a checker using the htmlentities()
function.
<?php
if (isset($_POST['firstname'], $_POST['lastname'], $_POST['pwd']) or isset($_GET['firstname'], $_GET['lastname'], $_GET['pwd'])) {
txt_check();
$fname = $_GET['firstname'];
$lname = $_GET['lastname'];
$pwd = $_GET['pwd'];
if ($fname == 'Or' and $lname == 'Halimi' and $pwd == 'password') {
print 'Welcome master';
} else {
print 'You are not my master!';
}
echo format('<br/> <br/> {} {}', array($fname, $lname)); # like format in python
}
function txt_check() {
foreach ($_GET as $name => $string) {
$_GET[$name] = htmlentities($_GET[$name], ENT_QUOTES, 'UTF-8');
}
foreach ($_POST as $name => $string) {
$_POST[$name] = htmlentities($_POST[$name], ENT_QUOTES, 'UTF-8');
}
}
?>
The problem is my function txt_check()
not working, but when I put echo htmlentities($fname, ENT_QUOTES, 'UTF-8') #fname=<script>
i get <script>
at the end of the code. Maybe I can't edit $_GET
? I come from python so I don't know if $_GET
is special in someway.
Edit:
I want to understand if i can change the global $_GET\$_POST
like I did and if its good to doing so' because i don't know if the code inside txt_check()
working for me. If not, there is a better way to protect the input I get? Because i want to make a standard level of protecting, even if i dont even know the most risks that's hanging out there.
And why htmlentities()
its not so good for this case? I use basic tutorial about php security to make it.
If you are trying to remove HTML tags, i would recommend you to use the strip_tags
...not the htmlentities
.
<?php
$mytext = "hello<br><script>alert('everybody');</script>";
$allow = "<br>";
echo strip_tags($mytext,$allow);
?>
That will remove only the script
tag.