jquery post ajax call session doesnt work - php

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.

Related

PHP Captcha Form

I have a Google App Engine PHP website. I have a page with the following recaptcha form:
<?php
ob_start();
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//verify captcha
$recaptcha_secret = "6LfkBQMTAAAAABN5yEqoqxoLqKOBKIvoCHZ-3vP3";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
while (ob_get_status())
{
ob_end_clean();
}
if($response["success"] === true)
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=register.php">';
exit;
}
else
{
echo "Please try again";
}
}
?>
Once the user types in the correct recaptcha they are sent to 'register.php'. This all works fine and the user is sent correctly. But the problem is the user can just type 'register.php' into the URL and access it. I am trying to make it that the user can only access this page if the recaptcha has been entered. (The recaptcha is on a different page to 'register.php').
I am using sessions, when the user is logged in, so have this on register.php and this needs to stay there:
<?php
session_start();
if ( !isset($_SESSION['username']) )
{
header("Location:error.php");
exit();
}
?>
Is there a way to do something like:
<?php
session_start();
if ( !isset($_SESSION['username']) )
{
header("Location:error.php");
exit();
}
and ($response["success"] === false)
header("Location:error.php");
exit();
}
Seems like you're looking for the Or logical operator, save the value before the redirect:
if($response["success"] === true)
{
$_SESSION['success'] = true;
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=register.php">';
exit;
}
And now add a new check:
<?php
session_start();
if ( !isset($_SESSION['username']) || $_SESSION['success'] != true )
{
header("Location:error.php");
exit();
}
?>
If any of those expressions is true then the error block will be executed.

How to condition a user to fill the form than to oppen an specific site up

i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)

Anti-CSRF not working correctly

<?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>");
}

PHP error message trigger ajax jquery displaying of error message - form validation

I've done this before where if a field isn't filled out the PHP validation "echos" an error like this:
if(empty($_POST['formfield'])) {
echo "Error";
die();
} else {
...
}
then triggered a msg with jquery validation like this (this is pseudocode):
success: function(data) {
if (data=="Error") {
$("#Error").html('ERROR MSG HERE').show();
} else {
$("#Success").html('SUCCESS MSG HERE').show();
}
I have recently had to set up some pages with a simple log in for a vendor to download files. Again, this is simple!
<?php
$username = "foo";
$password = "bar";
if ($_POST['username'] != $username || $_POST['password'] != $password) {
?>
<!DOCTYPE>
<html>
<head></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" >
</body>
</html>
<?php
}
else {
?>
<!DOCTYPE>
<html>
<head></head>
<body>Logged in user sees this content</body>
</html>
<?php
}
?>
so my issue is this
I can't seem to figure out how to echo a message that will then trigger an error message on the form as I have done in the first 2 code blocks.
Obviously
<?php
$username = "foo";
$password = "bar";
if ($_POST['username'] != $username || $_POST['password'] != $password) {
**echo "Error";**
?>
just prints "Error" on page load. I need to figure out a way to simulate data being returned from the server - this form submits to itself - and show appropriate message (Username and/or Password are incorrect") if someone logs in with an incorrect username or password.
I apologize for this being so long, and I truncated all the js stuff as I know it works.
Thanks!
PHP is processed before Javascript. This gives you the ability to have PHP write out the Javascript that you want to display. Something like this should do what you want:
if ($_POST['username'] != $username || $_POST['password'] != $password) {
?>
<script>
$(document).ready(function() {
$("#Error").html('ERROR MSG HERE').show();
});
</script>
<?php } ?>

Redirecting cookieless sessions in PHP without clicking a link

I've been fighting with the cookieless sessions solution. Of course cookieless sessions solution is amazing. I have a trouble in implementing it because I can't read the session information after redirecting to another page.
Here's my test code in testcode.php
<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **cannot read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
header('location: testcode.php?pagecode=' . session_id());
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
As you can see this code doesn't work. but if i redirect to another page by clicking a link it works well. Here's the code in testcode.php:
<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **able to read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
echo 'Click here to continue';
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
How can I get this to work without clicking a link?
ini_set('session.use_trans_sid', '1');
You have to have this on every single one of your PHP pages - you can't do it just within the session handling script. If it's not on when PHP generates a page, it won't insert the session ID into forms and urls on that page. As such, it'd be better if you put this into your php.ini, or at least httpd.conf/.htaccess (as a php_value) to make it a global option for all scripts.
PHP function for this is :
function append_sid($link) {
if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) {
if(strpos($link, "?") === FALSE) {
return $link . "?PHPSESSID=" . session_id();
} else {
return $link . "&PHPSESSID=" . session_id();
}
} else {
return $link;
}
}
Javascript Function for this is:
function append_sid(link) {
<?php if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) { ?>
var session_id = '<?php echo session_id ?>';
if(link.indexOf('?') == -1) {
return link + '?PHPSESSID=' + session_id;
} else {
return link + '&PHPSESSID=' + session_id;
}
<?php } else { ?>
return link;
<?php } ?>
}
A caveat – passing session id by URL requires the session.session.use_trans_sid tio be set to 1.
php_value session.use_trans_sid = 1 in the .htaccess file. You can also try the function:
ini_set('session.use_trans_sid', '1')

Categories