Переменная буферизации вывода PHP - PullRequest
2 голосов
/ 14 марта 2012

Можно ли использовать переменную POST в буферизованном скрипте?Код следующий:

<?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;
?>

Примечание. Я уже пытался получить доступ к $ someVar напрямую из someScript, но безуспешно.Вот почему я спрашиваю.Спасибо

РЕДАКТИРОВАТЬ: возможно 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) не удалось

Ответы [ 3 ]

3 голосов
/ 14 марта 2012

Переменная $someVar уже доступна для вас в someScript.php. Вы не должны использовать строку запроса для ее передачи.

Если вы по какой-то причине не хотите изменять someScript.php, вы можете сделать это:

$_GET['var'] = $someVar; 

Или просто так:

$_GET['var'] = $_POST['var'];
1 голос
/ 14 марта 2012

Да, вы можете.

Поскольку require() работает аналогично include(), включенный файл наследует переменную scope.

Из руководства:

"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 ....

1 голос
/ 14 марта 2012

Когда вы включаете сценарий с include или require, этот сценарий имеет доступ ко всем переменным в области видимости на сайте включения.В вашем примере вы можете получить доступ к $someVar напрямую из someScript.php (вы также можете получить прямой доступ к $_POST или чему-либо еще).

...