how to use php sessions in embeded files?

I have a site https://one.com/go.php that (for example) contains :

session_start();
$_SESSION['id_ad'] = 123456;
header('Location: https://two.com/index.php');

and on https://two.com/index.php user click and go to https://three.com/index.php that contains :

<script type="text/javascript" src="https://one.com/2.php"></script>

and finally 2.php is:

 <?php
session_start();
header("Content-Type: application/javascript");
?>
alert("<?=$_SESSION['id_ad']?>");

can i access $_SESSION['id_ad'] in 2.php ? I tested only on firefox works.

////////EDIT//////

thank you to @Dimash to mention my mistake, but the main question still exists

1 answer

  • answered 2017-08-12 09:48 Dimash

    It works, you just return javascript wrongly. Firefox for some reason works, but other browsers fails.

    Here is working code:

    <?php
    session_start();
    header("Content-Type: application/javascript");
    ?>
    alert("<?=$_SESSION['id_ad']?>");
    

    Please note, that code was tested.

    expect javascript file, not php with tag, you need return reall js file, so you need add header content type, telling that it is js file + remove script tag, as it is not html but regular js file.