I want to POST some CURL to a REST API with the use of a PHP Frontend. A Short Description of my Project ... The user (we call him Anton) logs in, on a classic Login Form on the Startsite. After that the user should be logged in until he wants to logout (But thats not the issue here). The main task of the user is to fill a Form with a projectname and a description. After a submit, the data are transferred to a JSON Object which creates the Project in the Software. When I run the CURL commands manually via the terminal, everything works fine. But my PHP Script, unfortunately not.
Login works fine in Terminal
curl -v \
-c cookie.txt \
-X POST \
-F j_username=Anton \
-F j_password=pw \
http://test.com/login.json
Login works fine in 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);
?>
**create Projekt works fine in Terminal but not in php Create a Projekt ... i have absolutely no idea ! How do i use the Cookie.txt and how do i fill the array (-d part) with the data ?
... and how can I stay logged in to create a projekt?
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
edit... but it actually not work. i have problems to use the 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);
?>
I strongly believe in your help. Thanks!