Writing the following curl in PHP - php

How would I write the following Curl in PHP?
I need to automate this process in php.
$ curl -F file=#/Users/alunny/index.html -u andrew.lunny#nitobi.com -F 'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps
Here is the link to the Phonegap Build API.
http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps
Any help would be greatly appreciated.
This is what I have tried so far...
<?php
$url = 'https://build.phonegap.com/api/v1/apps';
$file = 'mobilecontainer.zip';
$fields = array(
'title' => 'Test App',
'create_method' => 'file',
'private' => 'false'
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_SAFE_UPLOAD, 'true');
$result = curl_exec($ch);
print_r($result);
curl_close($ch);

You use CURL options improperly.
CURLOPT_SAFE_UPLOAD option disables support for the # prefix for
uploading files in CURLOPT_POSTFIELDS which is exactly what you
need to use.
CURLOPT_POST option expects a boolean value (true or false),
although count($fields) in your case will be evaluated to true
anyway.
-F option in the source curl command forces Content-Type value
to multipart/form-data. This mean that in PHP you have to pass
data to CURLOPT_POSTFIELDS as array. This array should contain two
elements: 'data' - json-encoded data, and 'file' - link to file
to upload.
So the code should look like this:
$url = 'https://build.phonegap.com/api/v1/apps';
$data = array(
'title' => 'Test App',
'package' => 'com.alunny.apiv1',
'create_method' => 'file',
'version' => '0.1.0',
);
$post = array(
'data' => json_encode($data),
'file' => '#mobilecontainer.zip',
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);

Related

consume Restful service in php?

I am trying to consume a Restful service using the below code:
$dat=array(
'entidad' => "F001",'tipoIdentificacion' => 'CC','numeroIdentificacion' => '1020442757'
);
$postdata =http_build_query( $dat );
//print_r($postdata);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
//var_dump($context);
$result=file_get_contents('http://172.18.131.195:9090/lince/rest/pazysalvo1/avaldescfin',FILE_USE_INCLUDE_PATH, $context);
//echo $result;
//$result = json_decode(file_get_contents('http://172.18.131.195:9090/lince/rest/pazysalvo1/avaldescfin?', false, $context),true);
print_r($result);
But it does not recognize the parameters that I am sending, and therefore returns null values:
{"entidad":"F001","tipoIdentificacion":null,"numeroIdentificacion":null,"codPersona":0,"estadoConsulta":"1","avales":[]}
How should I send the parameters?
I couldn't do it in this Asian way that I gave a solution in this other way.
//set POST variables
$url = 'http://172.18.131.195:9090/lince/rest/pazysalvo1/avaldescfin';
$fields = array(
'entidad' => 'F001','tipoIdentificacion' =>$tipoid,'numeroIdentificacion' => $numid
);
//url-ify the data for the POST
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$result=json_decode($result,true);
/*echo "<pre>";
print_r($result);
echo "</pre>";*/

Trouble with POST API using cURL

I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

PHP send and receive data curl or json

I'm trying to make two file talk to each other.
'output_file.php' to send data from domain 'a' to input_file located on domain 'b'.
Data from output file will later be send to crm via api.
I'm stuck as I don't know what am I doing wrong, what should I change in these files?
Here is output_file.php:
<?php
//send cURL
$curl = 'https://domain_name/input.php';
$fields = array(
'name' => urlencode($_POST['name']),
'email' => urlencode($_POST['email']),
'tel' => urlencode($_POST['tel']),
);
//var_dump($fields);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//var_dump($fields_string);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $curl);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
//var_dump($result);
curl_close($ch);*/
?>
Here is input_file.php:
// main data about the person. person_id is added later dynamically - PERSON DATA
$person = array(
'name' => 'name from output_file.php',
'email' => 'email from output_file.php',
'phone' => 'tel from output_file.php'
);
You can use below snippet for this. It should be work.
Ps. Please delete POST functions from your output file, it's uncesseray and useless.
$person = array(
'name' => $_REQUEST['name'],
'email' => $_REQUEST['email'],
'phone' => $_REQUEST['phone'],
);
Best,
As you do use POST to send your data, you will need to capture the POST on the target site. As you do use $_POST variables, you may want to have a look into security, to make sure the data recieved can not harm you:
PHP $_GET security, $_POST security best practice
Your Outfile:
<?php
$curl = 'https://domain_name/input.php';
$fields = array(
'name' => urlencode($_POST['name']),
'email' => urlencode($_POST['email']),
'tel' => urlencode($_POST['tel']),
);
// here you do prepare your POST data
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $curl);
// here you define that your data will be sent via POST
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
// this curlopt ensures the output of your destination is captured
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
?>
Your Input/Destination file:
<?php
// user $_POST to populate your array
$person = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['tel']
);
// see the result
var_dump($person);
?>

http_build_query not correctly encoding my post fields

It's a strange issue I'm facing. Here is the CURL request I'm sending:
$fields = array(
'action' => 'json',
'region' => '',
'states' => array('TX'),
'start' => '4/2/2010',
'end' => '4/2/2017',
'internalcomments' => 'no'
);
$fields_string = http_build_query($fields);
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$jsonResult = curl_exec($ch);
curl_close($ch);
However, when I'm printing out the content of the $fields_string, I see a trademark icon in the query string:
action=json®ion=&states%5B0%5D=AL&states%5B1%5D=TX&start=04%2F01%2F2010&end=04%2F07%2F2017&internalcomments=no
Notice the ® icon after the word json? Any idea where that's coming from?

Opposite method of file_get_content

You know how in PHP there's a method called file_get_content that gets the content of the page for the provided url? Is there an opposite method for it? Like, for example, file_post_content, where you can post data to external websites? Just asking for educational purposes.
You can use without cURL but file_get_contents PHP this example:
$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
See the PHP website: http://php.net/manual/en/function.file-get-contents.php#102575
Could write one:
<?php
function file_post_content($url, $data = array()){
// Collect URL. Optional Array of DATA ['name' => 'value']
// Return response from server or FALSE
if(empty($url)){
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
if(count($data)){
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$svr_out = curl_exec ($ch);
curl_close ($ch);
return $svr_out;
}
?>

Categories