【问题标题】:retaining PHP variable after re-running the same script重新运行相同的脚本后保留 PHP 变量
【发布时间】:2017-05-16 16:43:33
【问题描述】:

我是 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。但是,每次运行此脚本时,一切都会未初始化。

我也尝试在$GLOBALS 中设置$selectedDatabase 并将其设为静态,但是当另一个请求到来时我失去了价值。

任何想法如何维护$selectedDatabase

注意:编写此脚本的文件名为Index.php,我不确定它是否是第一个加载的脚本。不过好像是这样!

谢谢,

【问题讨论】:

  • 你可以尝试一下会话。
  • 谢谢,我认为会话解决了我的问题!
  • 谢谢* ....

标签: php html ember.js


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2011-06-05
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2020-12-09
    相关资源
    最近更新 更多