3

How come when I create a session from an iframe within a domain and then try access the session from another iframe it works fine but when I try access the session through ajax it does not work?


Example:

Website (iframe.php):

<?php 
header("Access-Control-Allow-Origin: *");
session_start();
if(isset($_POST['session'])){
    $_SESSION['session'] = $_POST['session'];
    echo "created session";
}else if(isset($_GET['want'])){
    //for ajax request
    die($_SESSION['session']);
}
?>
<form action="iframe.php" method="post">
SESSION VAL:<input name="session" value="<?php echo $_SESSION['session']?>" type="text"/><br>
<input type="submit"/>
</form>

HTML

<iframe src="iframe.php">

</iframe>
<br>SESSION FROM AJAX:
<div id="AJAX"></div>

AJAX

window.setInterval(function(){
    $.get( "iframe.php?want", function( data ) {
        $( "#AJAX" ).html( data );
    });
},1000);

See Fiddle

maxisme
  • 3,974
  • 9
  • 47
  • 97

1 Answers1

3

Look up about how to do CORS. Shortly, to make browser send session with ajax you have to add some fields to your xhr:

$.ajax({
  url : "https://crypter.co.uk/iframe.php?want",
  xhrFields : {
    withCredentials : true // <-- this
  },
  success : function( data ) {
    $( "#AJAX" ).html( data );
  }
});

And you'd have to allow such request serverside, see this answer.

Community
  • 1
  • 1
Serge Seredenko
  • 3,541
  • 7
  • 21
  • 38