2014-10-17 139 views
0

我想使用PHP Frontend将一些CURL POST到REST API。 我的项目的简短描述... 用户(我们称他为Anton)在Startsite上的经典登录表单上登录。之后,用户应该登录,直到他想注销(但这不是问题在这里)。用户的主要任务是使用项目名称和说明填写表单。提交后,数据被传输到一个JSON对象,该对象在软件中创建项目。当我通过终端手动运行CURL命令时,一切正常。但不幸的是我的PHP脚本。使用PHP POST POST CURL to JSON(使用Cookie.txt)

登录工作正常,在终端

curl -v \ 
    -c cookie.txt \ 
    -X POST \ 
    -F j_username=Anton \ 
    -F j_password=pw \ 
    http://test.com/login.json 

登录在PHP

工作正常
<?php 
     //Login 
     error_reporting(E_ALL|E_STRICT); 
     ini_set('display_errors', '1'); 

     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, "http://test.com/login.json"); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
     curl_setopt ($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt'); 
     curl_setopt ($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt'); 
     curl_setopt($ch, CURLOPT_POST, true); 

     $data = array(
      'j_username' => 'Anton', 
      'j_password' => 'pw', 
     ); 

     curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
     $output = curl_exec($ch); 
     $info = curl_getinfo($ch); 
     curl_close($ch); 
     ?> 

**创建的Projekt工作正常,在终端而不是在PHP 创建Projekt的......我绝对不知道 ! 如何使用Cookie.txt以及如何填充数据(-d部分)?

...以及如何保持登录状态以创建项目?

curl -v \ 
     -b cookie.txt \ 
     -X POST \ 
     -H "Content-Type: application/json" \ 
     -d '{"name":"name12345", "description":"Some Kind of Description"}' \ 
     http://test.com/productions.json 

编辑... 但它实际上不工作。我有问题,使用cookie.txt :(

<?php 
// //Create Production 

function post_to_url($url, $data) { 
    $fields = ''; 
    foreach($data as $key => $value) { 
     $fields .= $key . '=' . $value . '&'; 
    } 
    rtrim($fields, '&'); 

    $post = curl_init(); 

    curl_setopt($post, CURLOPT_URL, $url); 
    curl_setopt($post, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt'); 
    curl_setopt($post, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt'); 
    curl_setopt($post, CURLOPT_POST, count($data)); 
    curl_setopt($post, CURLOPT_POSTFIELDS, $fields); 
    curl_setopt($post, CURLOPT_RETURNTRANSFER, 1); 

    $result = curl_exec($post); 

    curl_close($post); 
} 

$data = array(
    "name" => "Max", 
    "description" => "Some kind of description" 
); 


post_to_url("http://test.com/productions.json", $data); 

print_r($data); 

?> 

我坚信在您的帮助。 谢谢!

+0

我认为你错过了 curl_setopt($ ch,CURLOPT_COOKIEFILE,dirname(__ FILE __)。'/ cookie.txt'); //这是您从 – 2014-10-17 13:47:34

+0

读取cookie的地方感谢Stefan,我将setopt添加到了我的php代码中,但功能没有明显变化。 阵列 ( [名称] =>最大 [描述] =>有些种类描述 的) 那数组$数据。 – Florian 2014-10-17 14:06:08

回答

0

那将是非常非常非常感谢你,如果有人能翻译这个卷曲POST。 ..

curl -v \ 
     -b cookie.txt \ 
     -X POST \ 
     -H "Content-Type: application/json" \ 
     -d '{"name":"name12345", "description":"Some Kind of Description"}' \ 
     http://test.com/productions.json 

...与使用CURL_SETOPT的PHP。

非常感谢你!!!!