重新运行相同的脚本后保留PHP变量

时间:2017-05-16 16:43:34

标签: php html ember.js

我是PHP的新手,我正在尝试为现有应用添加功能。

每次来自客户端的数据库请求时,都会使用以下PHP代码。

  <?php
    header("Access-Control-Allow-Origin: *");

    require_once("config/keychain.php");

    function decrypt($data, $key, $iv){
      $key = pack('H*', $key);
      $iv = pack('H*', $iv);
      return mcrypt_decrypt( MCRYPT_RIJNDAEL_128 , $key , $data ,  
      MCRYPT_MODE_CBC ,  $iv );
    }
    $request = (object)$_REQUEST;
    $dbConfig = (object)parse_ini_string(decrypt(file_get_contents("config/database.ini"), ENCRYPTION_KEY, ENCRYPTION_IV));
    require_once("include/UniversalDB.php");
    require_once("include/UniversalModel.php");
    require_once("include/UniversalController.php");
  /*
    Set DB Connection
  */
    $dbConnection = new UniversalDB();
   $dbConnection->init($dbConfig->host, $dbConfig->user, $dbConfig-
   >password, 2);
   /*$universalDB->connect();*/
   require_once("boot.php");
  ?>

我正在尝试从其中一个请求值(登录$ _REQUEST值)维护一个属性。

我尝试将其添加到上一个脚本中。

if(property_exists($request,'selectedDatabase')){
  $selectedDatabase = $request->selectedDatabase;
}

我会正确初始化$selectedDatabase。但是,每次运行此脚本时,所有内容都会被初始化。

我还尝试在$selectedDatabase中制作$GLOBALS并将其设为静态,但在另一个请求到来时我会失去该值。

任何想法如何维护$selectedDatabase

注意:编写此脚本的文件名为Index.php,我不确定它是否是第一个要加载的脚本。但它似乎就好了!

谢谢,

1 个答案:

答案 0 :(得分:1)

有多种方法可以保持价值。这是一对夫妇:

会话

一种方法是使用PHP的内置session handling。存储会话数据的方法有多种 - 默认使用文件,但支持数据库中的其他方式。

首先致电session_start()。然后使用superglobal数组$_SESSION来获取和设置值。

$selectedDatabase = null;//initialize to empty value
$sessionStarted = session_start();
if ($sessionStarted) {
    $selectedDatabase = $_SESSION['selectedDatabase'];
}
if ($selectedDatabase) {
    //value is set, use it
}
else {
    //set the value from $request
    if(property_exists($request,'selectedDatabase')){
        $selectedDatabase = $request->selectedDatabase;
    }
    //store the value in the session for subsequent requests
    $_SESSION['selectedDatabase'] = $selectedDatabase;
}

参见this phpfiddle中的演示。

文件

另一种解决方案可能是将值存储在文件中,例如使用file_get_contents()file_put_contents()以及file_exists。内容也可以使用json_encode()或其他序列化函数(例如serialize())存储为对象。

$selectedDatabase = null;//initialize to empty value
$fileName = 'databaseConfig.txt'; //set path accordingly
if (file_exists($fileName)) {
    $selectedDatabase = file_get_contents($fileName);
}
if ($selectedDatabase) {
    //value is set, use it
}
else {
    //set the value from $request
    if(property_exists($request,'selectedDatabase')){
        $selectedDatabase = $request->selectedDatabase;
    }
    //store the value in the session for subsequent requests
    file_put_contents($fileName, $selectedDatabase);
}