从不同的文件中获取会话数组

时间:2017-04-08 18:57:20

标签: php arrays session-cookies

我无法从其他文件访问数组,仍然无法弄明白,我的数据是否已经存储到数组中。我应该把$ _SESSION放到函数中吗?

Lat3_3a.php

<form id="form1" name="form1" method="post" action="Lat3_3b.php">
    Insert number: <input type="number" name="num" id="num" />
    <input type="submit" name="button" id="button" value="OK" />
</form>

Lat3_3b.php

<?php
   session_start();
    $_SESSION["num"] = $_POST["num"];
    if (empty($_SESSION["num"]))
        echo "Please, insert number";
    else {
        $val=$_POST['num'];
    echo " Factorial  " .$val. " ! =  " .factorial($val)."<br/>";
    echo "<a href='Lat3_3c.php'>Link</a>";
  }

    function factorial($val){

         if($val<=1){
            $result=1;
            return $result; 
         }elseif($val>1){
            for($i=1; $i<=$val; $i++){
               $result=$val * factorial($val-1);
         }
         return $result;
         }

         $data=array($val,$result,"12345", "Travis");
         $_SESSION["var"]=$_POST["data"];    
  }
  ?>

Lat3_3c.php

<?php
  session_start();
  if(empty($_SESSION["var"]))
      echo "Variable not found";
  else
  echo "Data : ". $_SESSION["var"];

?>

1 个答案:

答案 0 :(得分:0)

好好再查看一下代码,您需要了解有关会话,发布和功能的更多信息。为此,请查看PHP手册网站。 网站http://php.net

要使代码正常工作,您需要使用以下内容:

<?php
   session_start();
    $_SESSION["num"] = $_POST["num"];
    $_SESSION["var"]=array();
    if (empty($_SESSION["num"])){
        echo "Please, insert number";
    }
    else {
        $val=$_POST['num'];
        $function_result=factorial($val);
        $data=array($val,$function_result,"12345","Travis");
        $_SESSION["var"]=$data;
        echo " Factorial  " .$val. " ! =  " .$function_result."<br/>";
        echo "<a href='Lat3_3c.php'>Link</a>";
    }
    function factorial($val){

         if($val<=1){
            $result=1;
            return $result; 
         }elseif($val>1){
            for($i=1; $i<=$val; $i++){
               $result=$val * factorial($val-1);
            }
            return $result;
         }
     }
  ?>

我不是在考虑你的数学。