<?php
$_SESSION['csrf_token'] = md5(uniqid(rand(), true));
?>
<?php
$csrf1 = $_POST['csrf_token'];
$csrf2 = $_SESSION['csrf_token'];
if($csrf1 === $csrf2) {
//not executing
} else {
}
?>
javascript
var csrf = "<?php echo $_SESSION['csrf_token']; ?>";
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "success"){
} else {
window.location.replace("login.php");
}
}
}
ajax.send("csrf_token="+csrf);
}
return false;
So, here's some PHP from my code that generates a CSRF token, puts it in session, then checks whether the session value and the POST value are the same. The problem is, the if statement isn't executing. When I echo out the session token right before I send off the request using ajax, the session token is the same. I'm fairly sure that the session token is changing, and I am unsure why.
Edit: I added my javascript. I removed a lot from it, so I hope I didn't mess anything up on it.
A very important piece of information OP failed to provide is that the request goes to the same script that makes his token. Therefore, what is happening is exactly what is supposed to happen. Here is a solution I provided to him on a different website.
<?php
if((isset($_SESSION['csrf_token'], $_SESSION['time']) && time() - $_SESSION['time'] > 60) || !isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = md5(uniqid(rand(), true));
$_SESSION['time'] = time();
}
?>
if($csrf1 === $csrf2) {
change so: if($csrf1 == $csrf2) {
I would echo the contents and visually compare the two to check for identical values. For what it is worth, have you tried strcmp()?
if(strcmp($csfr1, $csfr2) == 0) {
//Got a match
} else {
//No match, look at the two strings for debug purposes.
print("<pre> CSRF1: $csrf1 \n CSRF2: $csrf2 </pre>");
}
Related
I have a problem with cookies. In my login script i have the following line of code:
if($_GET['keep'] == "true"){
setcookie('id',$id,time()+3153600);
}
The problem I'm facing is that the cookies are not saving at all ( not even if i don't quit the browser). I'm quite a beginer in this respect and I think I'm not doing it right.
EDIT:
If i print_r all the Cookies it only gives me PHPSESSID after the cookie is set. I printed on index.php and i set the cookie on login.php
SOLUTION: Cookies are saved by default with the path of the file they were created in. To change the path there is another atribute. So by setcookie('id',$id,time()+3153600,'/'); you make the cookie available for the entire domain.
There is no issue in your code
if($_GET['keep'] = "true"){
setcookie('id',$id,time()+3153600);
}
This will may cause to
No data passing to $_GET['keep']
Or if data passing $_GET['keep'] value in not Matched ("true").
Both Works then $id is empty in setcookie method
Improve your code
if(isset($_GET['keep']){
if($_GET['keep'] == "true"){
if(isset($id))
{
#all perpect
$cokkie_id = 'id';
setcookie('id',$id,time()+3153600);
echo "I'm Set. And My value is ".$cokkie_id;
}
else
{
echo "Opzz My ID is also empty";
}
}
else
{
echo 'Get method is Set. But Value is not "true". Actual value is '. $_GET['keep'];
}
}
else
{
echo 'I cant reach Get method Buddy';
}
I think you miss "=" sign
if ($_GET['keep'] == "true") {
if (!isset($_COOKIE['id'])) {
setcookie('id',$id,time()+3153600);
}
}
use isset or ==
if (isset($_GET['keep']) && $_GET['keep'] == "true") {
setcookie('id', $id,time()+3153600);
}else{
echo 'keep is empty';
}
I am using this if statement to redirect a user if the values in a .txt document is 0 but if it is 1 I want nothing to happen however I'm having some issues with my code.
This is my code currently:
$setup = require('setup.txt');
if ($setup === "0") {
echo '<script type="text/javascript"> window.location = "setup.php" </script>';
}
The setup.txt document currently contains the value 0.
I'd look here as to the proper usage of the require function.
if (file_get_contents('setup.txt') == "0") {
header('Location: /setup.php');
}
Use the header function if you have not already sent output to the browser.
$setup = file_get_contents('setup.txt');
if ($setup == "0") {
header('Location: /setup.php');
}
Since all PHP is executed before the output the site. Use this option first.
You can not use include() / require() to transfer as a variable, like you have. Use file_get_contents() to achieve the results.
try this:
<?php
$setup = file_get_contents('setup.txt');
if (trim($setup) == "0") {
echo '<script type="text/javascript"> window.location = "setup.php" </script>';
}
?>
I'm really lost here while trying to send a session with my jquery ajax post call, here is a simplified example of my code.
File fom which request is sent:
<?php
session_start();
$token = md5(rand(1000,9999));
$_SESSION['contactToken'] = $token;
?>
<script type="text/javascript">
$.post(ContactUrl,{req:"contact_sub",tok:"<?php echo $token; ?>"},function(contactAns){
alert(contactAns); return false;
});
</script>
File request is sent to:
<?php
if(#isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="url"){
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) ){
session_start();
$token = $_POST['tok'];
$sess_token = $_SESSION['contactToken'];
if($token == $sess_token){
echo "sessions match"; exit();
}
else{
echo "sessions does not match"; exit();
}
}
else{echo "error"; exit();}
}
else{echo "error"; exit();}
?>
At first the session was not getting recognized, I made all the checks - made sure it was setup in the first place made sure it was posted, declared session start on both pages, never the less if i tried to do this on the second file:
<?php
session_start();
$token = $_POST['tok'];
$sess_token = $_SESSION['contactToken'];
print_r($_SESSION['contactToken']); exit();
?>
I would get an empty alert. Then I transferred the session start to the top of my script on the second page and started getting a value for the session:
<?php
session_start();
$sess_token = $_SESSION['contactToken'];
if(#isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="url"){
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) ){
$token = $_POST['tok'];
echo "$token, $sess_token"; exit();
}
else{echo "error"; exit();}
}
else{echo "error"; exit();}
?>
And what I'm getting now is that the posted variable changes each time I refresh the page but the $sess_token always gives me the same value: 0589dd536fd043ff3865f8223fef3030
I really dont understand this wierd behavior, can some one please assist me with this?
Your problem here is that you're using a PHP var in an JS script without wraping and echoing it.. Here is your code modified:
You're also trying to contatenate with . in JS. That's from PHP too.
<script type="text/javascript">
$.post(ContactUrl, {
req: "contact_sub",
tok: "<?php echo $token; ?>"
}, function(contactAns) {
alert(contactAns);
return false;
});
</script>
Update
I came back to this answer again today. This is what I did:
FILE: index.php
<?php
session_start();
$token = md5(rand(1000,9999));
$_SESSION["contactToken"] = $token;
?>
<script type="text/javascript">
$.post("myOtherScript.php", {
req:"contact_sub",
tok:"<?php echo $token; ?>"
}, function(contactAns){
alert(contactAns);
return false;
});
</script>
FILE: myOtherScript.php
<?php
session_start();
$sess_token = $_SESSION["contactToken"];
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && ($_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest")){
$token = $_POST["tok"];
echo $token ." - ". $sess_token;
} else {
echo "Not an AJAX request";
}
?>
What I get is the alert where one token is equal to the other and both are refreshed each time I reload the index.php file.
As a conclusion, your problem is not in the code you shared.
first question for the site(i am new to this site)
thought to post my most difficult problem .....
I have Login system in my site after successful login my protected page is displayed only after login i want to add $_SESSION['point'] to store the point of user.and save it to data base and the point will be increased if user click link. I want to store this increased point into my userdb.php. where all sign up information i kept.(i have not used MySql for signup Form I have used userdb.php file)my protected page php code are
<?php
if (session_id() == "")
{
session_start();
}
if (!isset($_SESSION['username']))
{
header('Location: #');
exit;
}
if (isset($_SESSION['expires_by']))
{
$expires_by = intval($_SESSION['expires_by']);
if (time() < $expires_by)
{
$_SESSION['expires_by'] = time() + intval($_SESSION['expires_timeout']);
}
else
{
unset($_SESSION['username']);
unset($_SESSION['expires_by']);
unset($_SESSION['expires_timeout']);
header('Location: #');
exit;
}
}
if (session_id() == "")
{
session_start();
}
if (session_id() == "")
{
session_start();
}
?>
My display.php to show urls
<?php
mysql_connect('Server', 'user', 'passs');
mysql_select_db('add');
$query =mysql_query('select * from addimage');
while( $row = mysql_fetch_assoc($query) )
{
echo '
<div style="min-width:300px;height:100px;border:red 5px;float:left;">'.$row['url']. '</div>';
}
?>
You can write your login PHP like,
<?php
// if PHP > 5.4: if (PHP_SESSION_NONE == session_status()) {
if ('' == session_id()) {
session_start();
}
if (isset($_SESSION['expires_by'])) {
$expires_by = intval($_SESSION['expires_by']);
if (time() < $expires_by) {
$_SESSION['expires_by'] = time() + intval($_SESSION['expires_timeout']);
} else {
session_destroy();
}
}
if (!isset($_SESSION['username'])) {
Header('Location: ' . $_SERVER['REQUEST_URI']);
exit();
}
?>
Then to click on the URLs you could perhaps use jQuery and AJAX. You should declare a class like "link-block" in your CSS, and write the URLs like this
echo '<div class="link-block">'.$row['url'].'</div>';
and add a click handler to those DIVs in the page's onReady Javascript, after including jQuery scripts:
$('.link-block').on('click', function(e) {
$.post('/increase-points.php', { }, function(retval){
if (retval.newpoints) {
$('#point-block').html(retval.newpoints);
}
});
});
The increase-point handler needs to open the session, which is the same code as you have above (so you can put it into an external include "session.php"), and open the database connection (another include...), then:
UPDATE usertable SET points = points + 1 WHERE user_id = {$_SESSION['user_id']};
or if you have a username only (ensure it's properly escaped)
...WHERE username = '{$escapedSessionUsername}';
By the way, I need to add the standard mysql_* deprecation disclaimer.
After which, you might return the current points to be displayed into a DIV with id of "points-block":
You have <span id="points-block"></span> points.
by returning it in JSON after querying them from the database (or you can keep them in session and update both DB and session; it saves you one query)
// This in /update-points.php
$retval = array('newpoints' => $updated_points);
Header('Content-Type: application/json;charset=utf8');
die(json_encode($retval));
You can do this in other ways too, but I saw no anchor in your link div, so I guess you want something dynamic, which mostly means AJAX.
I have some strange issue using jQuery Validation plugin. Firs of all here is my code:
formvalid.js
var v = jQuery("#sendform").validate({
rules: {
/* some other rules */
captcha: {
required: true,
remote: "securimage/process.php"
}
},
messages: {
/* some other messages */
captcha: {
required:"Security code is required",
remote:"Security code is incorrect!"
}
}
});
process.php
<?php
/* I tried with and without session_start().
Both ways works with same probelm (read next)*/
//session_start();
include_once '../securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_GET['captcha']) == false)
echo "false";
else
echo "true";
?>
sendform.php
<?php
include_once 'securimage/securimage.php';
//echo $_POST['captcha'];
$securimage = new Securimage();
//echo "<br/>".$securimage->getCode();
if($_POST['captcha'] && $securimage->check($_POST['captcha']))
{
//do sending
}
?>
So, the problem is when I'm checking security code with AJAX request, ajax works fine, but when I'm send the form, $securimage->check($_POST['captcha']) in sendform.php returns false. Then I tried to disable remote capctha validation and viola $securimage->check($_POST['captcha']) in sendform.php returned true!
As you can see I echo some values in sendform.php and result is:
Case #1: AJAX captcha validation enabled.
Results:
echo $_POST['captcha']; // User_input_value;
echo $securimage->getCode(); // nothing
$securimage->check($_POST['captcha']) // false
Case #2: AJAX captcha validation disabled.
Results:
echo $_POST['captcha']; // User_input_value;
echo $securimage->getCode(); // code from image
$securimage->check($_POST['captcha']) // true (if equals)
Anyone know how to make it work?
Thanks for any advice.
To prevent resetting captch, you should validate yourself without calling check() function in process.php like below code
<?php
include_once 'securimage.php';
if(!isset($_GET['txtcaptcha']))
return 'false';
$securimage = new Securimage();
$securecode = $securimage->getCode();
if (strtolower($securecode) != strtolower($_GET['txtcaptcha']))
echo "false";
else
echo "true";
?>
Almost same question was asked a while ago, it seems that the captcha is resetting after each check.
What I suggest is to have a flag in your session that you would set to TRUE in your process.php after a valid captcha and then checking it instead of $securimage->check($_POST['captcha']) in your sendform.php:
if ($securimage->check($_GET['captcha']) == false) {
$_SESSION['valid'] = FALSE;
echo "false";
} else {
$_SESSION['valid'] = TRUE;
echo "true";
}
And:
if($_POST['captcha'] && isset($_SESSION['valid']) && $_SESSION['valid']) // set it back to false inside this!
Now here are two notes:
Since you are having two separate calls, some one can still change the captcha between the two calls
Since it's only a captcha and you most probably is using it to prevent spam, I wouldn't bother using the technique I posted above! actually I wouldn't even bother doing another captcha check in the sendform.php
Of course someone could spam you, but then and if you really need to use Ajax, then you have to stop processing the captcha in the jQuery plugin and just validate it when you submit your form, just like the original documentation approach.