在同一个php文件中访问会话变量

时间:2018-03-07 04:22:55

标签: javascript php jquery session-variables

我有index.php我通过电子邮件和密码登录,电子邮件ID存储在会话变量中。登录后,隐藏的div可见,当点击它时,我希望电子邮件的会话变量显示在同一页面上。我在form-login.php中保存这样的会话:

$_SESSION['userEmail'] = $email_signin;

其中$email_signin是从index.php中的表单中捕获的电子邮件ID的登录信息。

当我回复此会话时,我可以看到该电子邮件显示在此文件中。

我希望在我的index.php中访问此会话。我使用了<?php echo $_SESSION['userEmail']; ?>,但它给了我空白值。

我在必要时使用了session_start()。请帮忙!

形状的login.php `

<?php
session_start();
try {
if(isset($_POST)){
    //echo("inside isset function");
$email_signin=$_POST['email2'];
}
    $_SESSION['userEmail'] = $email_signin;
    echo $email_signin;
    $_SESSION['logged'] = "yes";
    print_r($_POST);
    echo "Welcome $email_signin. Your session is set.";
    var_dump($_SESSION);
}
catch (Exception $e) {
    $_SESSION['login_error'] = $e->getMessage();
}

`

的index.php `

<?php 
session_start();
if(!isset($_SESSION['userEmail'])){
  $email_signin = $_SESSION['userEmail'];
  echo $_SESSION['userEmail']; 
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri().'/style.css'; ?>">

<script>
  //Global variable to hold the JSON object
  var g_objJSON;

        /** setJSON - Create JSON object
        * Returns - Nothing
        **/
        function setJSON() {
            var v_aJSON = [];
            var v_hObject = {};
            var v_hTempHash = {};

            var v_sKey = document.getElementById("user_email").value;
     // v_sKey = $_SESSION['user_email'];
            var v_sValue = document.getElementById("user_password").value;

            try {
                v_hObject[v_sKey] = v_sValue;

                document.getElementById("user_email").value = "";
                document.getElementById("user_password").value = "";

                if (g_objJSON == undefined) {
                    v_aJSON.push(v_hObject);
                } else {
                    v_hTempHash = mergeHashOb(g_objJSON[0], v_hObject);
                    v_aJSON.push(v_hTempHash);
                }
        g_objJSON = v_aJSON;
        alert("JSON created!");
        for (var item in g_objJSON[0]) {
            console.log("Email: " + item + "\nPassword: " +   g_objJSON[0][item]);
            $.ajax({
              url: '<?php echo get_stylesheet_directory_uri().'/json.php'; ?>',
              type: 'POST',
              data: {json: JSON.stringify(g_objJSON)},
              dataType: 'json'
            });
        }
            } catch (x) {
                alert(x.message);
      }
    }
    /** mergeHashOb - Merge a new JSON object with the global JSON object
               * @prm_hObj - Existing Hash object
               * @prm_hObj2 - New Hash object
               * Returns - A new Hash object contains the merged Hash objects
               **/
               function mergeHashOb(prm_hObj, prm_hObj2) {
                       var v_hObj = {};
                       /*for (var item in prm_hObj) { 
                               v_hObj[item] = prm_hObj[item]; 
                       }*/
                       for (var item in prm_hObj2) { 
                               v_hObj[item] = prm_hObj2[item]; 
                       }
                       return v_hObj;
               }

  function getJSON() {
    var v_hNewHashObj = {};
    var v_aJSON = [];
    var v_sKey = document.getElementById("signin_email").value;
    console.log('signin email: ' + v_sKey);
    var dataString = 'email2='+ v_sKey;
    var v_sValue = document.getElementById("signin_password").value;
    for (var item in g_objJSON[0]){
      if(item == v_sKey) {
        $.ajax({
          type: "POST",
          url: '<?php echo get_stylesheet_directory_uri().'/form-login.php'; ?>',
          data: dataString,
          success: function(result){
            alert(result);
          }
        });
        v_hNewHashObj[item] = g_objJSON[0][item];
        //console.log('getJson: ' + $_POST['signin_email']);
        alert("Welcome "+ v_sKey +". You are logged in.");
        $('#loginModal').hide();
        $('#myModal').hide();
        $('.modal-backdrop').hide();
        $('#openday_events').show();
        break;
      }
      else{
        alert("Login details incorrect");
      }
    }
    v_aJSON.push(v_hNewHashObj);
    g_objJSON = v_aJSON;
  }

  function setEventJSON() {
            var v_aJSON = [];
            var v_hObject = {};
            var v_hTempHash = {};

        //if(isset($_POST)){
          //$v_sKey = $_POST['signin_email'];
         // $_SESSION['userEmail'] = $v_sKey;
        //}

        //var v_sKey = '';
        var v_sKey = '<?php echo (isset($_SESSION['userEmail'])) ? $_SESSION['userEmail'] : ''; ?>';
        //echo $_SESSION['userEmail'];
        //var dataString = 'email2='+ v_sKey;
        console.log(v_sKey);

        //console.log('setEventJSON: ' + $v_sKey);
        var v_sValue = $("div.product-description").attr("data-name");
            //var v_sValue = $("p.product-price").attr("data-name");
            try {
                v_hObject[v_sKey] = v_sValue;

                //$("div.product-description").attr("data-name") = "";
                //$("p.product-price").attr("data-name") = "";

                if (g_objJSON == undefined) {
                    v_aJSON.push(v_hObject);
                } else {
                    v_hTempHash = mergeHashOb(g_objJSON[0], v_hObject);
                    v_aJSON.push(v_hTempHash);
                }
        g_objJSON = v_aJSON;
        alert("Events JSON created!");
        for (var item in g_objJSON[0]) {
            console.log("Email: " + item + "\nEvent Name: " +   g_objJSON[0][item]);
            $.ajax({
            url: '<?php echo get_stylesheet_directory_uri().'/json-2.php'; ?>',
            type: 'POST',
            data: {json: JSON.stringify(g_objJSON)},
            dataType: 'json'
        });

        }
    alert('saving event');
    $('#my_banner').show();
    $('html,body').animate({
      scrollTop: $("#my_banner").offset().top},
      'slow');

    } 

  catch (x) {
                alert(x.message);
      }
      //console.log($(this).serializeArray());
      //event.preventDefault();
    }

</script>
</head>
<body class="landing-page">
    <button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#myModal" style="margin-right: auto; margin-left: auto; margin-top: 1em; display: block;">Create Day Plan</button>

<div id="myModal" class="popup--register modal" role="dialog">
    <div class="popup__content">
            <h3>Create your own plan</h3>
    <!--<span onclick="document.getElementById('myModal').style.display='none'" class="close" title="Close Modal">&times;</span>
    -->
    <form accept-charset="UTF-8" class="" data-remote="true" action="" id="new_user" method="post">

          <ol class="form-list">
                <li class="form-list__item--full">
                        <input class="mko-signin-capture" id="user_full_name" mko-label="FirstName" name="user[full_name]" placeholder="Full Name*" type="text" required>
                </li>
                <li class="form-list__item--full">
                        <input class="mko-signin-capture" id="user_email" mko-label="Email" name="user[email]" placeholder="Email*" type="text" value="" required>
                      </li>
                <li class="form-list__item--full">
                            <input id="user_password" name="user[password]" placeholder="Password*" type="password" required>
                          </li>
                <li class="form-list__item--full">
                                <input autocomplete="off" id="user_password_confirmation" name="user[password_confirmation]" placeholder="Confirm password*" type="password" required>
                              </li>
                <li class="form-list__item--full">
                                    <div class="selector fixedWidth" id="uniform-user_lead_type_id">
                                        <select class="mko-signin-capture" id="user_lead_type_id" mko-label="Lead_Type__c" name="user[lead_type_id]" required><option value="">I am... *</option>
                              <option data-slug="School Leaver" value="1">A secondary school student</option>
                              <option data-slug="TAFE Student" value="2">A TAFE student</option>
                              <option data-slug="University Student" value="3">A university student</option>
                              <option data-slug="Employed" value="4">In the workforce</option>
                              <option data-slug="Parent" value="5">A parent</option>
                              <option data-slug="Other" value="6">Other</option></select></div>
                                  </li>
                                  <li class="form-list__item--full">
                                        <div class="selector fixedWidth">
                                            <select class="mko-signin-capture" mko-label="Campus__c" id="campus_id">
                                          <option value="">Select a campus...</option>
                                          <option value="Melbourne Burwood">Melbourne Burwood</option>
                                          <option value="Geelong Waterfront">Geelong Waterfront</option>
                                          <option value="Geelong Waurn Ponds">Geelong Waurn Ponds</option>
                                          <option value="Warrnambool">Warrnambool</option>
                                        </select></div>
                                      </li>

    <li class="form-list__item--full">
            <button class="button create-account-button create-account-main" name="button" id="" onclick="setJSON();">CREATE AN ACCOUNT</button>
          </li>
            </ol>
    </form>
    <div class="popup-links">
            <span>Already a member?</span>
            <a href="#" class="popup-link day-plan-login-link" data-toggle="modal" data-target="#loginModal" data-dismiss="#myModal">Login</a>
          </div>
    </div>
</div>
<!-- Login popup-->
<div class="popup--login modal" role="dialog" id="loginModal">
  <div class="popup__content">
   <!-- <a href="#" class="close-popup mobile">×</a>-->
    <h3>Create your own plan</h3>
    <form accept-charset="UTF-8" action="" class="new_session" data-remote="true" id="new_user" method="post"><div style="display:none"><input name="utf8" type="hidden" value="✓"></div>

<!-- Hidden field to store selected info session -->
<input class="new_session_info_session" id="user_info_session" name="user[info_session]" type="hidden">

<ol class="form-list">
<li class="form-list__item--full">
<input class="session_email" id="signin_email" name="signin_email" placeholder="Email*" type="text" value="">
<!--<span class="greeting active">Cool!</span>-->
</li>
<li class="form-list__item--full">
<input class="session_password" id="signin_password" name="signin_password" placeholder="Password*" type="password">
<!--<span class="greeting active">Nicely done!</span>-->
</li>
<li class="form-list__item--full">
<button class="button day-planner-main-login" name="button" type="submit" id="login" onclick="getJSON();">Login</button>
</li>
</ol>
</form>
    <div class="popup-links">
      <a href="#" class="popup-link be-a-grey-link forgotten-pass-link" data-target="popup--reset" data-close="popup--login">Forgotten password?</a>
      <a href="#" class="popup-link create-account-link" id="create-account-popup-link" data-toggle="modal" data-target="#myModal" data-dismiss="#loginModal">Create an account</a>
    </div>
  </div>
  <div class="popup__overlay"></div>
</div>
<!-- Events information-->
<div class="open-day-index-wrap container" id="openday_events" style="display: none;">

  <div class="open-day-index">
    <ol class="open-day-list">
      <li class="open-day-list__item open-day-list--warrnambool">
  <a class="open-day-list__link warrnambool" href="#" id="wrnmbool_events">
    <!--<span class="open-day-list__link warrnambool">-->
    <div class="open-day-image"></div>
    <h5 class="open-day-title" style="color: #fff;">Warrnambool</h5>
    <div class="open-day-date-time-wrap" style="color: #fff;">
      <span class="open-day-date">
        <span class="open-day-date__day">06</span>
        <span class="open-day-date__month">Aug</span>
        <span class="open-day-date__year">2018</span>
      </span>
      <span class="open-day-time"> 9:00 AM -  3:00 PM</span>
      <span class="plan-my-day full-width">
        <span class="plan-my-day__text warrnambool">
          See Events<i class="fa fa-chevron-right"></i></span>
      </span>
    </div><!--endDiv open-day-date-time-wrap-->
    <!--</span>-->
  </a>
</li>
<li class="open-day-list__item open-day-list--geelong-waurn-ponds">
  <a href="/campuses/geelong-waurn-ponds" class="open-day-list__link geelong-waurn-ponds">
    <!--<span class="open-day-list__link geelong-waurn-ponds">-->
    <div class="open-day-image"></div>
    <h5 class="open-day-title" style="color: #fff;">Geelong Waurn Ponds</h5>
    <div class="open-day-date-time-wrap" style="color: #fff;">
      <span class="open-day-date">
        <span class="open-day-date__day">20</span>
        <span class="open-day-date__month">Aug</span>
        <span class="open-day-date__year">2018</span>
      </span>
      <span class="open-day-time"> 9:00 AM -  3:00 PM</span>
      <span class="plan-my-day full-width">
        <span class="plan-my-day__text geelong-waurn-ponds">
          See Events<i class="fa fa-chevron-right"></i></span>
      </span>
    </div><!--endDiv open-day-date-time-wrap-->
    <!--</span>-->
  </a>
</li>
<li class="open-day-list__item open-day-list--geelong-waterfront">
  <a href="/campuses/geelong-waterfront" class="open-day-list__link geelong-waterfront">
    <!--<span class="open-day-list__link geelong-waterfront">-->
    <div class="open-day-image"></div>
    <h5 class="open-day-title" style="color: #fff;">Geelong Waterfront</h5>
    <div class="open-day-date-time-wrap" style="color: #fff;">
      <span class="open-day-date">
        <span class="open-day-date__day">20</span>
        <span class="open-day-date__month">Aug</span>
        <span class="open-day-date__year">2018</span>
      </span>
      <span class="open-day-time"> 9:00 AM -  3:00 PM</span>
      <span class="plan-my-day full-width">
        <span class="plan-my-day__text geelong-waterfront">
          See Events<i class="fa fa-chevron-right"></i></span>
      </span>
    </div><!--endDiv open-day-date-time-wrap-->
    <!--</span>-->
  </a>
</li>
<li class="open-day-list__item open-day-list--melbourne-burwood">
  <a href="/campuses/melbourne-burwood" class="open-day-list__link melbourne-burwood">
    <!--<span class="open-day-list__link melbourne-burwood">-->
    <div class="open-day-image"></div>
    <h5 class="open-day-title" style="color: #fff;">Melbourne Burwood</h5>
    <div class="open-day-date-time-wrap" style="color: #fff;">
      <span class="open-day-date">
        <span class="open-day-date__day">27</span>
        <span class="open-day-date__month">Aug</span>
        <span class="open-day-date__year">2018</span>
      </span>
      <span class="open-day-time"> 9:00 AM -  3:00 PM</span>
      <span class="plan-my-day full-width">
        <span class="plan-my-day__text melbourne-burwood">
          See Events<i class="fa fa-chevron-right"></i></span>
      </span>
    </div><!--endDiv open-day-date-time-wrap-->
    <!--</span>-->
  </a>
</li>

    </ol>
  </div><!--endDiv open-day-index-->
  <br>
  <ul class="nav-list--login">
      <li class="nav-list__item">
        <a href="/open day planner/welcome.php" class="nav-list__link border-link planner-link">My Planner <span class="planners_counter">0</span></a>
      </li>
      <li class="nav-list__item">
        <a class="nav-list__link log-out" data-method="delete" href="/open day planner/logout.php" rel="nofollow">Log out</a>
      </li>
  </ul>
</div>

<div id="site" style="display: none;">
    <header id="masthead">
        <h1>Events</h1>
        <ul class="nav-list--login">
                <li class="nav-list__item">
                  <a href="/open day planner/welcome.php" class="nav-list__link border-link planner-link">My Planner <span id="planners_counter"></span></a>
                </li>
                <li class="nav-list__item">
                  <a class="nav-list__link log-out" data-method="delete" href="/open day planner/logout.php" rel="nofollow">Log out</a>
                </li>
            </ul>
    </header>
    <div id="content">
        <div id="products">
            <ul>
                <li>

                    <div class="product-description" data-name="Finding Accomodation" data-price="Warrnambool">
                        <h3 class="product-name">Finding Accomodation</h3>
                        <p class="product-price" data-price="Warrnambool" id="event-location" data-name="Warrnambool">Warrnambool</p>
                        <p class="product-desc">Ipsum qui id ipsum reprehenderit irure in esse pariatur commodo Lorem. Do exercitation nostrud pariatur minim qui deserunt laboris Lorem dolore. Minim labore aliquip cupidatat in anim aliquip ut cillum ipsum excepteur commodo exercitation aliquip. Ad pariatur consectetur fugiat officia laborum incididunt nostrud ex eiusmod.</p>
                        <!--<p class="product-price">10:00 am</p>-->
                        <form class="add-to-cart" action="" method="post">
                                <label for="qty-1">Time</label>
                                <input type="text" name="qty-1" id="qty-1" class="qty" value="10" />
                            <p><input type="submit" value="Save event" class="btn" onclick="setEventJSON();"/></p>
                        </form>
                    </div>
                </li>

                <li>
                    <div class="product-description" data-name="Money Matters" data-price="Warrnambool">
                        <h3 class="product-name">Money Matters</h3>
                        <p class="product-price">Warrnambool</p>
                        <p class="product-desc">Ipsum qui id ipsum reprehenderit irure in esse pariatur commodo Lorem. Do exercitation nostrud pariatur minim qui deserunt laboris Lorem dolore. Minim labore aliquip cupidatat in anim aliquip ut cillum ipsum excepteur commodo exercitation aliquip. Ad pariatur consectetur fugiat officia laborum incididunt nostrud ex eiusmod.</p>

                        <form class="add-to-cart" action="" method="post">
                                <label for="qty-1">Time</label>
                                <input type="text" name="qty-2" id="qty-2" class="qty" value="10" />
                            <p><input type="submit" value="Save event" class="btn save" /></p>
                        </form>
                    </div>
                </li>

                <li>
                    <div class="product-description" data-name="Pathways to Deakin" data-price="Warrnambool">
                        <h3 class="product-name">Pathways to Deakin</h3>
                        <p class="product-price">Warrnambool</p>
                        <p class="product-desc">Ipsum qui id ipsum reprehenderit irure in esse pariatur commodo Lorem. Do exercitation nostrud pariatur minim qui deserunt laboris Lorem dolore. Minim labore aliquip cupidatat in anim aliquip ut cillum ipsum excepteur commodo exercitation aliquip. Ad pariatur consectetur fugiat officia laborum incididunt nostrud ex eiusmod.</p>

                        <form class="add-to-cart" action="" method="post">
                                <label for="qty-1">Time</label>
                                <input type="text" name="qty-3" id="qty-3" class="qty" value="12" />
                            <p><input type="submit" value="Save event" class="btn save" /></p>
                        </form>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div>

<div class="banner dayplanner-page campus-page" style="display: none;" id="my_banner">
                <div class="container">
                  <h2 class="banner__title">My Planner</h2>
                </div><!--endDiv container-->
        <div class="campus-planner__bar">
                <div class="container">
                  <div class="bar-links">
                    <a href="javascript:window.print()" class="print-plan"><i class="fa fa-print"></i>Print</a>
                    <a href="#" class="popup-link email-my-planner-link" data-toggle="modal" data-target="#email_popup"><i class="fa fa-envelope-o"></i>Email</a>
                  </div><!--endDiv bar-links-->
                </div><!--endDiv container-->
              </div>
              <div id="site">
              <div id="content">

              <form id="shopping-cart" action="" method="post">
                  <table class="shopping-cart">
                    <thead>
                    <tr>
                      <th scope="col">Event</th>
                      <th scope="col">Location</th>
                      <th scope="col" colspan="2">Time</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                  </table>

                  <ul id="shopping-cart-actions">
                    <li>
                      <input type="submit" name="delete" id="empty-cart" class="btn" value="Empty planner" />
                    </li>
                    <li>
                      <a href="" class="btn">Continue browsing</a>
                    </li>
                    <li>
                      <a href="logout.php" class="btn">Logout</a>
                    </li>
                  </ul>
                </form>

                </div>

                </div>

<script  type="text/javascript" src="<?php echo get_stylesheet_directory_uri().'/jquery-3.2.1.min.js'; ?>"></script>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri().'/custom.js'; ?>"></script>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri().'/bootstrap.min.js'; ?>"></script>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri().'/jquery.shop.js'; ?>"></script>
<script>
  $("#wrnmbool_events").click(function(){
    //alert('event clicked');
    $('#site').show();
    $('html,body').animate({
      scrollTop: $("#site").offset().top},
      'slow');
  });
</script>
</body>
</html>

`

4 个答案:

答案 0 :(得分:0)

您只需在index.php文件中调用session_start(),然后调用您想要的会话变​​量$_SESSION['{your_key}']

答案 1 :(得分:0)

在index.php中只需写下两行

session_start();
$variablename = $_SESSION['userEmail'];

确保在使用前启动会话。

答案 2 :(得分:0)

$ _ SESSION在php中是全局的,您只需要在将数据设置到会话之前在login.ohp文件中启动session_start(),之后您就可以在脚本中的任何位置访问会话。

答案 3 :(得分:0)

将你的session_start()放在php文件的第一行。