PHP Security Attacks: How to prevent these attacks in coding?
Security is major and essential part of any language . If we see PHP then we also need and keep in mind, all security tips and tricks to prevent our code from being attacked by hackers.
Here, i have searched and collected some types of attacks and their cure.
Types Of Attacks:
“Cross-Site Request Forgery” or CSRF attacks are not different from XSS attacks. CSRF attacks usually either exploit the fact that many websites perform actions on HTTP GET requests—deleting blog posts, buying items etc.—or spoof a client request to a resource so that the website believes the request is genuine. Either way, the victim performs an action on a website that trusts him—usually his own—that he did not intend to happen.
Here we will check an example of CSRF attack and then i will tell you its cure.
Mostly websites performs actions such as deleting a record needs a button or link to be clicked. Usually, URL looks like
Here the page delete_record.php will check that the user performing the request is logged in, and if so perform the requested action in this case, deleting the post with the ID 652. However, this method of authentication leaves open a massive security flaw; what if a privileged user—a record moderator, for example—were to be tricked or forced into visiting this URL? The post would be deleted, but that’s not what the moderator wanted. An attacker could even go further—if the URL were entered in an HTML
<img> tag, for example, the privileged user would likely not even know that they had performed the action.
How, then, can we avoid such attacks? There are two methods that, when used together, completely eliminate the possibility of CSRF attacks.
The first is rather simple: never, ever use GET for any critical task. Instead, use a POST form. Such requests are harder to forge and have the added bonus that they are impossible to load into HTML image/script tags, eliminating an attacker’s ability to exploit your site remotely.
The second is to make sure all requests originate from your own forms, eliminating the possibility that the request could have been loaded from a fake form on a different webpage. To do this, we can create a value— known by some as a “nonce”, but here referred to as a “token”—that is created especially for the form, submitted along with it, and checked— along with the usual permission checks—before the action is performed.
if( empty($_POST['token_csrf']) || $_POST['token_csrf'] != $_SESSION['token_csrf'] )
// All fine: delete the post.
delete_post( intval($_POST['post_id']) );
// Unset the token, so that it cannot be used again.
$token_csrf= md5(uniqid(rand(), true));
$_SESSION['token_csrf'] = $token_csrf;
ID to Delete:
<input name="post_id" type="text" />
<input name="token_csrf" type="hidden" value="<?php echo $token_csrf; ?>" />