How to make $_POST more secured? - php

This is a sample code that i got from Facebook Engineering page.
<?php
if ($_POST['name']) {
?>
<span>Hello, <?=$_POST['name']?>.</span>
<?php
} else {
?>
<form method="post">
What is your name?<br>
<input type="text" name="name">
<input type="submit">
</form>
<?php
}
It says that the above code is not secured because it is open to cross site scripting. the correct way is to pass the $_POST['name'] via htmlspecialchars(). However, they stated that it is poor programming practice.
Is always passing $_POST variable via a htmlspecialchars() inefficient?
I can't thought of any way to make it secure. They introduce XHP which i am reluctant to use.
Reference: https://www.facebook.com/notes/facebook-engineering/xhp-a-new-way-to-write-php/294003943919

the correct way is to pass the $_POST['name'] via htmlspecialchars(). However, they stated that it is poor programming practice.
It's not poor practice in itself. The problem is that when you have to type htmlspecialchars every single time you drop text content into HTML, you are quite likely to forget one, leaving a vulnerability.
What that page is saying, correctly, is that it's better to have a templating language that HTML-escapes by default, so that you don't have to think about it. This is a lesson most web frameworks have learned by now, but raw PHP still doesn't have a convenient way to do that.

Related

$_SESSION variable used to check if form has been submitted

I have a landing page called `index.php' with the following form:
<form action="auto_mail.php" method="post">
<input id="signup" class="span8" type="text" placeholder="Your email" name="signup">
<input type="submit">
<?php
if (isset($_SESSION['got_it']))
{echo "<b>You're all signed up!</b>}
?></form>
In the file auto_mail.php I have:
// code scrubbing user input...
$user_email = $_POST['signup'];
session_start();
$_SESSION['got_it'] = '1';
// code sending me an email when someone signs up.
echo <<<EOD
</b>
<meta http-equiv="refresh" content="0, url=index.php">
</div>
</body>
</html>
EOD;
?>
I've looked at some other SO questions (Using $_SESSION to carry data), but it's not what I'm looking for.
All I want, is for a user to see "You're all signed up" when they enter a valid email; with the email confirm email being sent in the background. This code feels clumsy and awkward. It also flashes the auto_mail.php page briefly.
I tried to set <form action="index.php"..., but it doesn't work because I've set up auto_mail.php such that you can't access it directly.
How can use the code in auto_mail.php, which checks for a valid email address and sends confirm emails, without dealing with both $_POST and $_SESSION, or at least using them better?
If you don't want to have any page reloads whatsoever, you'll have to use AJAX to send the form, instead of utilising the form POST.
If you are using jQuery, or Mootools, they both have built in wrappers to handle ajax calls. Without a helper library, you'll have to look into making an XMLHttpRequest yourself.
Other than that, traditionally, you would redirect the user to a "form submitted" page, or alternatively, have the form action be sent to the same page (in your case, index.php, and have PHP code to handle form data if it is received).
I dont get completely what you want.
I think you try to Verify a Mail Address (after?) that form has been sent. But you cannot access the file via http that does the verification.
Have you thought about including the auto_mail.php?
I think you should consider using one of popular PHP frameworks. I guess you didn't use any in above example. Good framework that also offers MVC structure allows to do operations like this in such a simple way you can't even imagine.
Breaking it down to MVC structure will even make it extremely simple to handle post sending and displaying dependences and results made by it in one action.
Learing good framework at first might look like a waste of time, but believe me - it will pay off very quickly.
For start I recommend you looking at Kohana Framework or, if you're ambitions one - Symfony Framework.

executing a php command inside an `echo("");` comman

I was wondering if it was possible to make a php command echo a whole new php set.
<?php
$phpcmd=$_POST["phpcmd"];
echo "<?".$phpcmd."?>";
?>
<form action="" method="post">
<input type="text" value="<?echo($phpcmd)?>" name="phpcmd">
<input type="submit">
</form>
You could do this using:
eval($phpcmd);
BUT...
I would strongly advise you don't, think about the security risks of something like this, a malicious user could cause an awful lot of damage with a script like this.
As the PHP docs state:
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
Check out this article for more info on the eval() function.

How can i validate if the email is already exist in the database without refreshing the php page?

As of now I am validating my inputs using this type of approach
<form method="post">
<label>Email</label>
<input type="email" name="user_email">
<input type="submit" name="reg">
</form>
if(isset($_POST['reg']){
$result = checkEmail($_POST['email']);
//checkEmail() is my function to check email, if it returns true it has duplicate
if($result){
echo '<p>E-mail already exist!</p>'
else{
//something to do in this..
}
I have seen some website after I type the email it automatically updates and i want to learn how to that without using any frameworks since I am just a starter, i just want a simple code. Any suggestions or advice on how to do it? Thank you :)
You'd have to use Ajax for that. To use Ajax natively is a lot of work though, you'd have to care for different browsers and a lot of ground work which can be taken care of by using a lightweight javascript libraries like jQuery. Using jquery together with an excellent plugin like Validate you can achieve what you're looking for. They have a working example of what you're trying to do at this demo page
I'm sorry but I think you'll need to use some AJAX code, HERE
I found a very interesting code.

PHP_SELF and XSS

I've found an article claiming that $_SERVER['PHP_SELF'] is vulnerable to XSS.
I'm not sure if I have understood it correctly, but I'm almost sure that it's wrong.
How can this be vulnerable to XSS attacks!?
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<!-- form contents -->
</form>
To make it safe to use you need to use htmlspecialchars().
<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>
See A XSS Vulnerability in Almost Every PHP Form I’ve Ever Written for how $_SERVER["PHP_SELF"] can be attacked.
It is indeed a XSS vulnerability. I do understand that you believe it may not harm your website, but this doesn't mean it is not real.
If you do not believe it, try the following:
We assume you have a page such as "registration.php".
We assume you have a form where action is:
<?php echo $_SERVER['PHP_SELF']; ?>
as you put it down indeed:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<!-- form contents -->
</form>
Now simply append the string below
%27%22/%3E%3Cscript%3Ealert(1)%3C/script%3E
It is not actually hard to understand, because PHP_SELF is a reflection of the URL, your application will read whatever you put in the URL and echo it. It is simple as that.
htmlspecialchars should take care of the matter, no reason to dispute the evidence.
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<!-- form contents -->
</form>
However, even this is a first step in stealing a cookie, it's not that it take place automatically. Even if it's quite easy to craft the attack (as the attacker will register on your site and will see how the cookie looks...etc.), a series of other factors must be true to get to the point of having a cookie stealing situation. For instance, the cookie must not be expired. Than it depends of how complex the cookie is. Than maybe you have other precautions in placed on server, it doesn't have to be all authentication based on the presence of cookie!
While I do believe it is rather difficult and really bad programming for all conditions to met (even if yahoo.mail for example had such a vulnerability and if you look on internet you will find even the exploit and the cookie decoder), the XSS is real and who knows what a crafty attacker may do if your site suffer of it. The cure is simple...
The very article you linked gives you:
http://www.example.com/form.php/%22%3E%3Cscript%3Ealert(‘xss attack’)%3C/script%3E%3Cbr%20class=%22irrelevant
what's not clear?
Edit: this is an XSS attack because I can hide a link from my site to yours with some JS added to the URL which sends me your cookies so the moment you click that link, you are pwnd.
You should be using filter_input() to access superglobals in PHP. If you set the filter to FILTER_SANITIZE_FULL_SPECIAL_CHARS it will strip the unsafe characters typically used in XSS. Given your example:
<form method="post"
action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>">
<!-- form contents -->
</form>
The vulnerability is that a user can enter malicious JavaScript codes in the form. To prevent this, htmlspecialchars function is used.
Predefined characters (like >, <, ", ') are converted into entities(> < etc)
htmlspecialchars($_SERVER["PHP_SELF"]) ensures that all submitted form variables are converted into entities.
To read more about this vulnerability, visit: https://www.w3schools.com/php/php_form_validation.asp
Another link that can help you: https://www.google.com/amp/s/www.bitdegree.org/learn/php-form-validation/amp
I am studying this issue about the PHP_SELF variable and the XSS attack. There is something that I still can't understand: PHP_SELF variable is suposed to reference the name of the script file (the script that is running). Then, why does it take its value from the URL? (allowing the XSS problem).

is it right way( safe) to assign post data value directly by name attibute value to a variable in php

i m working in PHP since one year, but now a days i got this way to assign post data value directly using name attribute . i m really curious to know the documentation about it.please refere me link regarding this .
i explain by example
here is my form
<form method="post" action="">
<input type="text" name="userName" id="userName">
<input type="submit" name="doit" value="submit">
</form>
to get the post data i always use
$somevar=mysql_real_escape_string($_POST['userName']);
but now i see another way
$somevar= "userName";
i just want to know that is it safe n easy way??
I think you're looking for the PHP ini directive register_globals. Take a look at Variables From External Sources. However, this directive defaults to "off" and you should probably leave it that way since it is deprecated in PHP 5.3. You would still have to mysql_real_escape_string() it anyway.
You can also use import_request_variables() to register the globals manually:
import_request_variables("p");
echo $userName;
Using Register Globals on the PHP website gives you a good idea as to how it can be unsafe to automatically register HTTP variables as globals.
Personally I like to use an escape function. So I would stick with mysql_real_escape_string()
I've never seen any code where a variable has been assigned from a quoted value. The way I understand it, all you'd be doing is making $somevar contain a string userName
you can better use the below one
$somevar= $userName;
OR
$somevar= $_POST[userName];

Categories