Невозможно сохранить значения сеанса и перенаправить страницу одновременно - PullRequest
0 голосов
/ 13 апреля 2020

Мое намерение - сохранить значения сеанса и передать их моему page2_form.php. Прежде чем добавить сессию в мой код, я смог направить пользователя на страницу независимо от того, выбрал ли он из выбора ->. Мое действие form было loadpage.php, для каждого параметра есть регистр переключателя, потому что каждый параметр имеет свою форму (у меня есть только один сейчас, но я добавлю больше позже). После добавления переменных сеанса я добавил header('Location: loadpage.php');, но у меня это не работает. Это сохраняет значения сеанса, но не направляет мою страницу. Я попытался изменить действие формы обратно на header('Location: loadpage.php');, но затем я не смог сохранить значения сеанса. Я новичок в php / html и все еще учусь, но не смог найти решение этой проблемы. При необходимости я могу опубликовать больше моего кода.

page1_form. php

    <?php
      if(isset($_POST['ilerleButon'])){
        session_start();

        $_SESSION['sayi'] = htmlentities($_POST['sayi']);
        $_SESSION['madde'] = htmlentities($_POST['madde']);
        $_SESSION['tarih'] = htmlentities($_POST['tarih']);
        $_SESSION['selectedPage'] = htmlentities($_POST['selectedPage']);
        header('Location: loadpage.php');
      }
    ?>
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- Gerekli Meta Tagleri -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!--Bootstrap-->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" ></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" ></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js" ></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
        <link href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
        <!-- <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script> -->


         <title>Bitirme Projesi</title>
      </head>
      <body>
        <form role="form" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST" name="theForm" id="theForm">
          <div class="container">
            <div class="row">
              <div class="col-md-auto">
                <label for="sayi">Sayı</label>
                <input type="number" class="form-control" id="sayi" name="sayi" required>
                <br>
                <label for="madde" >Madde</label>
                <input type="text" class="form-control" id="madde" name="madde" required>
                <br>
                <label for="datepicker">Tarih</label>
                <input type="text" class="form-control" id="datepicker" name="tarih" required>
                <hr>
                <div>
                    <div class="form-group">
                      <select class="form-control-auto"  form="theForm" name="selectedPage" required>
                      <option value="page_0">--Konu Seçiniz--</option>
                      <option value="page_1">Fazla Kredi</option>
                      <option value="page_2">Çap İzin</option>
                      <option value="page_3">Çap Ders Saydırma</option>
                      </select>
                    </div>
                </div>
                <input class="btn btn-primary"  name="ilerleButon"  id="ilerle" type="submit" value="Kaydet" style="font-size:15px; "/>
              </div>
            </div>
          </div>
        </form>
          <script>
            $( function() {
              $( "#datepicker" ).datepicker({
                format: 'dd/mm/yyyy',
                weekStart: 1,
                autoclose: true,
                todayHighlight: true
              });
            } );
            </script>
      </body>
    </html>

loadpage. php

<?php
$requested_page = $_POST['selectedPage'];

switch($requested_page) {
  case "page_0":
    echo "Konu Seçmediniz.";
    break;
  case "page_1":
    header("Location: page2_form.php");
  break;
  case "page_2":
    header("Location: page_2.php");
  break;
  default :
  header("Location: page1_form.php");
  break;
}
?>

1 Ответ

1 голос
/ 14 апреля 2020

У вас есть пара вещей, которые вы должны исправить, но я думаю, что главная проблема в том, что когда вы перенаправляете, ваше сообщение больше не устанавливается, поэтому вам нужно будет просто опубликовать сообщение прямо на целевой странице:

<form role="form" action="loadpage.php" method="POST" name="theForm" id="theForm">

Затем на этой странице сделайте сеанс. Также я бы сделал функцию для получения вашего запроса, чтобы вы могли выполнить некоторую фильтрацию:

<?php
# You could include this from a separate page, makes your script cleaner
function getRequest($key = false, $type = 'post')
{
    switch($type) {
        case('get'):
            $arr = $_GET;
            break;
        case('post'):
            $arr = $_POST;
            break;
        default:
            $arr = $_REQUEST;
    }
    if(!empty($key))
        return (isset($arr[$key]))? trim($arr[$key]) : null;

    return $arr;
}
# Don't put this after any "if" statements, just make it first thing on top of
# every top-level page
session_start();
# Just stop if invalid
if(empty(getRequest('selectedPage')))
    die("Invalid request.");
# Assign the session variables
$_SESSION['sayi'] = htmlentities(getRequest('sayi'));
$_SESSION['madde'] = htmlentities(getRequest('madde'));
$_SESSION['tarih'] = htmlentities(getRequest('tarih'));
$_SESSION['selectedPage'] = htmlentities(getRequest('selectedPage'));
# Modify the switch a bit. What you have is not wrong though.
# Make sure to use exit after he redirect so the script doesn't continue to run
switch(getRequest('selectedPage')) {
    case "page_0":
        # Since everything else redirects, just die here
        die("Konu Seçmediniz.");
    case "page_1":
        $page = "page2_form";
        break;
    case "page_2":
        $page = "page_2";
        break;
    default:
        $page = "page1_form";
        break;
}
# Just do one redirect here
header("Location: {$page}.php");
# This may be the end of the script anyway, but best to get in the habit of
# exiting after redirect
exit;

Если вы действительно хотите сначала опубликовать на той же странице, а затем перенаправить, на вашем loadpage.php вам нужно перенаправить с помощью значение сеанса вместо значения $_POST:

<?php
switch($_SESSION['selectedPage']) {
    case "page_0":
        # Since everything else redirects, just die here
        die("Konu Seçmediniz.");
    case "page_1":
        $pg = "page2_form";
        break;
    case "page_2":
        $pg = "page_2";
        break;
    default:
        $pg = "page1_form";
        break;
}
# Just do one redirect here
header("Location: {$pg}.php");
exit;
# If this is the end of the script, don't close it with a "?>" it is proper syntax to leave it off
# and then you don't have to worry about any hidden spaces that  may mess you
# up down the road.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...