PHP输出缓冲变量

问题描述:

是否可以在缓冲的脚本上使用POST变量?代码如下PHP输出缓冲变量

<?php 
header('Content-type: application/json'); 

$someVar= $_POST["var"]; 

ob_start(); 
require "someScript.php?var=" . $someVar; // instead of passing through GET, is there a way to use the $someVar directly? 
$output = ob_get_clean(); 
echo $output; 
?> 

注意:我已经尝试直接从someScript访问$ someVar,但没有成功。这就是为什么我问。由于

编辑:可能someScript.php

<?php 
    header('Content-type: application/json'); 
    require_once("BD.php"); 
    require_once("json/json_header.php"); 
    require_once("tools.php"); 
    require_once('class.phpmailer.php'); 

    $BD = new BDInfo(); 


    function encodeIDs($id1,$id2){ 

     // doesn't matter 
    } 

    $response = array("errorCode" => 0, "errorDesc" => "No Error"); 


    if(isset($someVar)){ 
     try{ 
      $link = mysqli_connect($BD->BDServer, $BD->BDUsername, $BD->BDPassword); 

      if(!$link) 
       throw new Exception("..."); 

      if(!mysqli_select_db($link, $BD->BDDatabase)) 
       throw new Exception("..."); 

      $SQL="SELECT (...) us.VAR='" . $someVar . "';"; 

      $RS = mysqli_query($link,$SQL); 
      if($RS && $row = mysqli_fetch_array($RS)){ 
       // process query result 
      } 
      else 
      { 
       $response["errorCode"]=4;  
       $response["errorDesc"]="Error descr"; 
      } 
      mysqli_close($link); 

     }catch (Exception $e) { 
      $response["errorCode"]=1; 
      $response["errorDesc"]="Database Error: " . $e->getMessage(); 
     } 
    }else{ 
     $response["errorCode"]=2; 
     $response["errorDesc"]="Invalid Parameters"; 
    } 

    echo json_encode($response); 
?> 

我得到无效的参数,显示出isset($ VAR)失败

+0

你试过了吗?你到目前为止有什么? – 2012-03-14 11:24:24

+0

你打算做什么? – sandeep 2012-03-14 11:26:10

+0

可能重复的[PHP的 - 包括()文件不工作时,变量放在URL?](http://*.com/questions/8301552/php-include-file-not-working-when-variables-are- put-in-url) – DaveRandom 2012-03-14 11:26:13

变量$someVar已在someScript.php中提供给您。您不应该使用查询字符串来传输它。

如果你想避免修改someScript.php出于某种原因,那么你可以这样做:

$_GET['var'] = $someVar; 

或者只是这样的:

$_GET['var'] = $_POST['var']; 
+0

我无法在someScript.php*问$ someVar。我刚刚尝试过。 – jose 2012-03-14 12:03:21

+0

它应该工作。尝试设置一个更简单的例子,看看它是否有效。请参阅[这里](http://uoco.net/d/dev/include/)。 – diolemo 2012-03-14 13:07:48

当包括与includerequire一个脚本,该脚本访问包含网站范围内的所有变量。在你的例子中,你可以直接从someScript.php访问$someVar(你也可以直接访问$_POST或其他任何东西)。

+0

但与他使用的输出缓冲区不同。 – m1crdy 2015-09-23 13:22:24

是的,可以。

由于require()的工作方式与include()类似,因此包含的文件会继承变量作用域。

从手册:

"When a file is included, the code it contains inherits the variable scope of the 
line on which the include occurs. Any variables available at that line in the 
calling file will be available within the called file, from that point forward. 
However, all functions and classes defined in the included file have the global 
scope." 

设想一个包括(或需要),其包含的代码替换线include ...