2012-06-14 3 views
0

Следующий код отправляет данные на тестовую страницу, которая просто var_dumps переменная _REQUEST. Страница не получает параметр post, но получает параметры get.Why это происходит?php curl post данные не принимаются

<?php 
    $jsonData = '{"Page":"index.html","KeyNumber":12132321}'; 
    $timeout = 20; 
    $options = array(
     CURLOPT_URL => "http://myadmin/postdump.php?AID=100&age=5&ishide=0", 
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_CONNECTTIMEOUT => $timeout, 
     CURLOPT_POST => true, 
     CURLOPT_POSTFIELDS =>'jsonData='.$jsonData, 
     CURLOPT_ENCODING=>"", 
     CURLOPT_FOLLOWLOCATION=>true 
     ); 

    $ch = curl_init(); 
    curl_setopt_array($ch, $options); 
    $file_contents = curl_exec($ch); 
    curl_close($ch); 

    echo $file_contents; 
?> 
+0

Вы пробовали его без ничего в ГЭТ? Кроме того, вы пробовали 'var_dump'ing' $ _POST'? – gcochard

+0

Я думаю, что если вы передадите поля в виде строки, вам придется вручную «urlencode» значения ... – prodigitalson

+1

В руководстве говорится, что 'CURLOPT_POSTFIELDS' либо должна быть строкой с urlencoded или массивом. Вы пробовали использовать urlencoding для jsonData? –

ответ

0

Варианты объяснены на странице руководства пользователя curl_setopt. Информация для CURLOPT_POSTFIELDS такова:

Полные данные для публикации в HTTP-режиме «POST». Чтобы опубликовать файл, добавьте имя файла с @ и используйте полный путь. Тип файла может быть явно указан, следуя имени файла с типом в формате '; type = mimetype'. Этот параметр может быть передан как строка urlencoded, такая как 'para1 = val1 & para2 = val2 & ...' или как массив с имя поля в качестве ключа и данных поля как значение. Если значением является массив, то заголовок Content-Type будет установлен в multipart/form-data. Начиная с PHP 5.2.0, значение должно быть массивом, если файлы передаются этому параметру с префиксом @.

Так что я думаю, что вместо этого:

CURLOPT_POSTFIELDS =>'jsonData='.$jsonData, 

... вы хотите что-то вроде этого:

CURLOPT_POSTFIELDS => array('jsonData' => $jsonData), 
0

Try для кодирования значения поля с помощью функции UrlEncode и я также рекомендуется добавить заголовки к запросу для имитации запроса формы, передающего массив с заголовками в параметр CURLOPT_HTTPHEADER, например

$headers = array(
     'Host: domain.com', 
     'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
     'Accept-Encoding: gzip, deflate', 
     'Content-Type: application/x-www-form-urlencoded' 
    ); 

Недавно также я работал в завиток классе полезности прикрепленного ниже, чтобы помочь в тестировании некоторых форм, надеюсь, что это помогает:

<?php 

define('CURLMANAGER_USERAGENT_MOZ4', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)'); 
/** 
* 
* Makes remote calls via http protocol 
* @author Alejandro Soto Gonzalez 
* 
*/ 
class CURLManager { 
    private $fields = array(); 
    private $headers = false; 
    private $method = ''; 
    private $url = ''; 
    private $response = ''; 
    private $header = false; 

    /** 
    * 
    * Constructor 
    * @return void 
    */ 
    public function __construct() { 

    } 

    /** 
    * 
    * Executes the http request 
    * 
    * @param string $useragent Request user agent 
    * @param string $fields Post values to be sent in the request body 
    * @param array $headers Request headers 
    * @param string $method Http method POST, GET, etc.. 
    * @param string $url Remote url 
    * @param boolean $header true if the response should contain the http headers and false if not 
    * @return void 
    */ 
    public function executeRequest($useragent, $fields, $headers, $method = 'POST', $url, $header = false) { 
     $this->fields = $fields; 
     $this->method = $method; 
     $this->url = $url; 
     $this->headers = $headers; 
     $this->header = $header; 
     $this->initializeCURL($useragent); 
    } 

    /** 
    * 
    * Gets the response retrieved from the http request 
    * @return void 
    */ 
    public function getResponse() { 
     return $this->response; 
    } 

    /** 
    * 
    * Initializes curl and executes the request 
    * @param string $useragent Request user agent 
    * @return void 
    */ 
    private function initializeCURL($useragent) { 
     $ch = curl_init($this->url); 
     $this->addFieldsToRequestBody($ch, $this->method); 
     $this->addGenericOptions($ch, $useragent); 
     $this->showResponseHeaders($ch, $this->header); 
     $this->addRequestHeaders($ch, $this->headers); 
     $this->response = curl_exec($ch); 
     curl_close($ch); 
    } 

    /** 
    * 
    * Adds generics options to the current curl object 
    * @param curlObject $ch 
    * @param string $useragent Request user agent 
    * @return void 
    */ 
    private function addGenericOptions($ch, $useragent) { 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); 
     curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/sourceforge/bouncer-logger-tester/cookies.txt'); 
    } 

    /** 
    * 
    * Adds the data fields to request body 
    * @param curlObject $ch 
    * @param string $method Http method POST, GET, etc.. 
    * @return void 
    */ 
    private function addFieldsToRequestBody($ch, $method) { 
     if ($this->method=='POST') { 
      curl_setopt($ch, $this->getCurlMethod(), true); 
      curl_setopt($ch, $this->getCurlFieldsMethod(), $this->fields); 
     } 
    } 

    /** 
    * 
    * Adds headers to the current request 
    * @param curlObject $ch 
    * @param array $headers Array containing the http header 
    */ 
    private function addRequestHeaders($ch, $headers) { 
     var_dump($headers); 
     if ($headers !== false) { 
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
     } 
    } 

    /** 
    * 
    * Gets the curl method id 
    * @return integer 
    */ 
    private function getCurlMethod() { 
     switch ($this->method) { 
      case 'POST': return CURLOPT_POST; 
      default: return CURLOPT_POST; 
     } 
    } 

    /** 
    * 
    * Show response headers in the full text response 
    * @param curlObject $ch 
    * @param boolean $show True to show headers and false to not 
    * @return void 
    */ 
    private function showResponseHeaders($ch, $show) { 
     if ($this->header) { 
      curl_setopt($ch, CURLOPT_HEADER, 1); 
     } 
    } 

    /** 
    * 
    * Gets curl fields option 
    * @return void 
    */ 
    private function getCurlFieldsMethod() { 
     switch ($this->method) { 
      case 'POST': return CURLOPT_POSTFIELDS; 
      default: return CURLOPT_POSTFIELDS; 
     } 
    } 
} 

?> 
Смежные вопросы