【问题标题】:PHP: print a variable contained in a methodPHP:打印方法中包含的变量
【发布时间】:2021-09-28 02:58:58
【问题描述】:

我希望有人可以帮助我: 我有 2 个 php 文件来详细说明 paypal IPN、paypalIPN.php 和 ipnlistener.php。 ipnlistener.php 包含 IpnListener 类,里面有很多函数如下:

class IpnListener
{       

    /**
     *  If true, the recommended cURL PHP library is used to send the post back
     *  to PayPal. If flase then fsockopen() is used. Default true.
     *
     *  @var boolean
     */
    public $use_curl = true;
    /**
     *  If true, cURL will use the CURLOPT_FOLLOWLOCATION to follow any
     *  "Location: ..." headers in the response.
     *
     *  @var boolean
     */
    public $follow_location = false;
    /**
     *  If true, the paypal sandbox URI www.sandbox.paypal.com is used for the
     *  post back. If false, the live URI www.paypal.com is used. Default false.
     *
     *  @var boolean
     */
    public $use_sandbox = true;
    /**
     *  The amount of time, in seconds, to wait for the PayPal server to respond
     *  before timing out. Default 30 seconds.
     *
     *  @var int
     */
    public $timeout = 30;
    /**
     * If true, enable SSL certification validation when using cURL
     *
     * @var boolean
     */
    public $verify_ssl = true;
    private $_errors = array();
    private $post_data;
    private $rawPostData;               // raw data from php://input
    private $post_uri = '';
    private $response_status = '';
    private $response = '';
    const PAYPAL_HOST = 'www.paypal.com';
    const SANDBOX_HOST = 'www.sandbox.paypal.com';
    /**
     *  Post Back Using cURL
     *
     *  Sends the post back to PayPal using the cURL library. Called by
     *  the processIpn() method if the use_curl property is true. Throws an
     *  exception if the post fails. Populates the response, response_status,
     *  and post_uri properties on success.
     *
     *  @todo add URL param so function is more dynamic
     *
     *  @param  string  The post data as a URL encoded string
     */
    
    protected function curlPost($encoded_data)
    {
        $uri = 'https://'.$this->getPaypalHost().'/cgi-bin/webscr';
        $this->post_uri = $uri;
        $ch = curl_init();
        if ($this->verify_ssl) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CAINFO, dirname(dirname(__FILE__)) . '/pp/cert/api_cert_chain.crt');
        }
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_data);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $this->follow_location);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        $this->response = curl_exec($ch);
        $this->response_status = strval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        if ($this->response === false || $this->response_status == '0') {
            $errno = curl_errno($ch);
            $errstr = curl_error($ch);
            throw new Exception("cURL error: [$errno] $errstr");
        }
        return $this->response;
    }
    /**
     *  Post Back Using fsockopen()
     *
     *  Sends the post back to PayPal using the fsockopen() function. Called by
     *  the processIpn() method if the use_curl property is false. Throws an
     *  exception if the post fails. Populates the response, response_status,
     *  and post_uri properties on success.
     *
     *  @todo add URL param so function is more dynamic
     *
     *  @param  string  The post data as a URL encoded string
     */
    protected function fsockPost($encoded_data)
    {
        $uri = 'ssl://'.$this->getPaypalHost();
        $port = '443';
        $this->post_uri = $uri.'/cgi-bin/webscr';
        $fp = fsockopen($uri, $port, $errno, $errstr, $this->timeout);
        if (!$fp) {
            // fsockopen error
            throw new Exception("fsockopen error: [$errno] $errstr");
        }
        $header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
        $header .= "Host: ".$this->getPaypalHost()."\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: ".strlen($encoded_data)."\r\n";
        $header .= "Connection: Close\r\n\r\n";
        fputs($fp, $header.$encoded_data."\r\n\r\n");
        while(!feof($fp)) {
            if (empty($this->response)) {
                // extract HTTP status from first line
                $this->response .= $status = fgets($fp, 1024);
                $this->response_status = trim(substr($status, 9, 4));
            } else {
                $this->response .= fgets($fp, 1024);
            }
        }
        fclose($fp);
        return $this->response;
    }
    private function getPaypalHost()
    {
        return ($this->use_sandbox) ? self::SANDBOX_HOST : self::PAYPAL_HOST;
    }
    public function getErrors()
    {
        return $this->_errors;
    }
    private function addError($error)
    {
        $this->_errors[] .= $error;
    }
    public function getPostData()
    {
        return $this->post_data;
    }
    public function getRawPostData()
    {
        return $this->rawPostData;
    }
    /**
     *  Get POST URI
     *
     *  Returns the URI that was used to send the post back to PayPal. This can
     *  be useful for troubleshooting connection problems. The default URI
     *  would be "ssl://www.sandbox.paypal.com:443/cgi-bin/webscr"
     *
     *  @return string
     */
    public function getPostUri()
    {
        return $this->post_uri;
    }
    /**
     *  Get Response
     *
     *  Returns the entire response from PayPal as a string including all the
     *  HTTP headers.
     *
     *  @return string
     */
    public function getResponse()
    {
        return $this->response;
    }
    /**
     *  Get Response Status
     *
     *  Returns the HTTP response status code from PayPal. This should be "200"
     *  if the post back was successful.
     *
     *  @return string
     */
    public function getResponseStatus()
    {
        return $this->response_status;
    }
    /**
     *  Get Text Report
     *
     *  Returns a report of the IPN transaction in plain text format. This is
     *  useful in emails to order processors and system administrators. Override
     *  this method in your own class to customize the report.
     *
     *  @return string
     */
    public function getTextReport()
    {
        $r = '';
        // date and POST url
        for ($i=0; $i<80; $i++) { $r .= '-'; }
        $r .= "\n[".date('m/d/Y g:i A').'] - '.$this->getPostUri();
        if ($this->use_curl) {
            $r .= " (curl)\n";
        } else {
            $r .= " (fsockopen)\n";
        }
        // HTTP Response
        for ($i=0; $i<80; $i++) { $r .= '-'; }
        $r .= "\n{$this->getResponse()}\n";
        // POST vars
        for ($i=0; $i<80; $i++) { $r .= '-'; }
        $r .= "\n";
        foreach ($this->post_data as $key => $value) {
            $r .= str_pad($key, 25)."$value\n";
        }
        $r .= "\n\n";
        return $r;
    }
    /**
     *  Process IPN
     *
     *  Handles the IPN post back to PayPal and parsing the response. Call this
     *  method from your IPN listener script. Returns true if the response came
     *  back as "VERIFIED", false if the response came back "INVALID", and
     *  throws an exception if there is an error.
     *
     *  @param array
     *
     *  @return boolean
     */
    public function processIpn($post_data=null)
    {   
                
      
        try
        
        {
            $this->requirePostMethod();     // processIpn() should check itself if data is POST
            // Read POST data
            // reading posted data directly from $_POST causes serialization
            // issues with array data in POST. Reading raw POST data from input stream instead.
            if ($post_data === null) {
                $raw_post_data = file_get_contents('php://input');
            } else {
                $raw_post_data = $post_data;
            }
            $this->rawPostData = $raw_post_data;                            // set raw post data for Class use
            // if post_data is php input stream, make it an array.
            if ( ! is_array($raw_post_data) ) {
                $raw_post_array = explode('&', $raw_post_data);
                $this->post_data = $raw_post_array;                             // use post array because it's same as $_POST
                
            } else {
                $this->post_data = $raw_post_data;                              // use post array because it's same as $_POST
            }
            
            
            $myPost = array();
            
            if (isset($raw_post_array)) {
                foreach ($raw_post_array as $keyval) {
                    $keyval = explode('=', $keyval);
                    if (count($keyval) == 2) {
                        $myPost[$keyval[0]] = urldecode($keyval[1]);
                    }
                }
            }
            
            // read the post from PayPal system and add 'cmd'
            $req = 'cmd=_notify-validate';
            foreach ($myPost as $key => $value) {
                if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() == 1) {
                    $value = urlencode(stripslashes($value));
                } else {
                    $value = urlencode($value);
                }
                $req .= "&$key=$value";
            }

            //XXX Debug log
            $file = fopen('lastresponse.log', 'w');
            fwrite($file, $req);
            fclose($file);     

            file_put_contents('dati.log', print_r($myPost, true));
            file_put_contents('dato.log', print_r("numero transazione: ".$myPost['txn_id'], true));
         
            //mail("mail@gmail.com","test",print_r($myPost,true));    
            
         


            if ($this->use_curl) {
                $res = $this->curlPost($req);
            } else {
                $res = $this->fsockPost($req);
            }
            if (strpos($res, '200') === false) {
                throw new Exception("Invalid response status: " . $res);
            }
            // Split response headers and payload, a better way for strcmp
            $tokens = explode("\r\n\r\n", trim($res));
            $res = trim(end($tokens));
            if (strpos ($res, "VERIFIED") !== false) {
                return true;
            } else if (strpos ($res, "INVALID") !== false) {
                return false;
            } else {
                throw new Exception("Unexpected response from PayPal: " . $res);
            }
        } catch (Exception $e) {
            $this->addError($e->getMessage());
            return false;
            
        }
        
        
        return false;
          
    }
    /**
     *  Require Post Method
     *
     *  Throws an exception and sets a HTTP 405 response header if the request
     *  method was not POST.
     */
    public function requirePostMethod()
    {
        // require POST requests
        if ($_SERVER['REQUEST_METHOD'] && $_SERVER['REQUEST_METHOD'] != 'POST') {
            header('Allow: POST', true, 405);
            throw new Exception("Invalid HTTP request method.");
        }
    }
    
}

感谢这部分:

file_put_contents('dati.log', print_r($myPost, true));
file_put_contents('dato.log', print_r("numero transazione: ".$myPost['txn_id'], true));

我能够保存一个包含所有元素数组的日志文件,或者只保存 PayPal 交易的一个元素。 我需要做的是在 IpnListener 类之外打印 $myPost 。 我该怎么做?

【问题讨论】:

  • 小注 类中的函数称为方法
  • 谢谢@RiggsFolly 请原谅我的无知

标签: php function class paypal try-catch


【解决方案1】:

你可以去上课,将 $tempMyPost 声明为 public。

每次迭代并向 $myPost 添加内容时,也要执行 $this->tempMyPost

例如,如果你有

            $myPost[$keyval[0]] = urldecode($keyval[1]);

也可以

            $this->tempMyPost[$keyval[0]] = urldecode($keyval[1]);

然后,走出对象,在你实例化它的地方下方,然后做

print_r($object->tempMyPost);

其中 $object 是保存您的对象的变量的名称。

【讨论】:

    【解决方案2】:

    您可以使用方法从方法中返回值

    return $myPost;
    

    或者(更好的方法)传递一个缓冲记录器对象作为方法参数,然后在方法完成后,获取并打印所有记录器内容。请参见此处的示例: https://github.com/symfony/console/blob/5.3/Output/BufferedOutput.php

    【讨论】:

    • 感谢您的回复,我尝试使用“return $myPost”,但现在出现此错误“致命错误:未捕获的错误:在 /htdocs/pp 中调用 null 上的成员函数 processIpn() /ipnlistener.php:373 堆栈跟踪:#0 /htdocs/pp/PaypalIPN.php(15): require_once() #1 {main} 在 /htdocs/pp/ipnlistener.php 第 373 行抛出“
    • 可能是因为 $myPost 在 try 块中?
    • 这个错误表示方法不是从对象调用的,它与方法返回的值无关。能否请您显示更新的方法和调用它的位置?
    • 你能解释一下为什么你实际上需要访问这个方法之外的方法的内部变量吗?
    • 如果这个var是方法的结果,就在方法体的最后返回。否则在里面做所有需要的操作。
    猜你喜欢
    • 2015-02-01
    • 2014-10-17
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 2012-10-21
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多