php retrieve curl_setopt POSTFIELDS string - php

Is there any way to retrieve the curl_setopt POSTFIELDS string which I had posted to the site after the curl_multi_exec($mh, $running) command?
Thanks.

You have to keep that data together with the individual resources:
$handles = array();
foreach ($urls as $url) {
$ch = curl_init($url);
$data = 'whatever';
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$handles[$url] = array(
'ch' => $ch,
'data' => $data,
);
}
This keeps the cURL handles and data together in a single structure that you can later use to inspect.
foreach($handles as $url => $data) {
// $url is the page you requested for this particular handle
// $data['data'] contains the data that goes with it
$body = curl_multi_getcontent($data['ch']);
curl_multi_remove_handle($mh, $data['ch']);
curl_close($data['ch']);
}

Related

Curl request with array values as input for query (GET) params

I have output from an array I would like to use as input in a PHP Curl request. Do I store them as another array and loop through the array with the Curl request?
Here is the output from the array:
foreach ($threadsarray['threads'] as $thread) {
print $thread['id']."<br />";
}
These are values I would like to use as input for Curl (obviously these values are different every time depending on the output for each loop above):
178369845
291476958
224408290
270960091
270715888
270513013
229639500
229630641
215503057
214314923
I want to execute a curl request for each of those thread id's...
Here is how I am building the Curl request:
$url2 = 'https://api.website.com/endpoint';
$data2 = array (
'specialkey' => '123abcd789xyz',
'anotherparam' => 'Brown',
'locale' => 'en-US',
'thread_id' => array (
$thread['id']
)
);
//build the query string because this is a get request
$params2 = '';
foreach($data2 as $key2=>$value2)
$params2 .= $key2.'='.$value2.'&';
$params2 = trim($params2, '&');
// Excecute the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url2.'?'.$params2 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 'false');
$mycurlresult = curl_exec($ch);
echo '<pre>';
$resultarray = json_decode($mycurlrequest, TRUE);
print_r($resultarray);
echo '</pre>';
if (FALSE === $mycurlrequest)
throw new Exception(curl_error($ch), curl_errno($ch));
I can't seem to build the request string correctly...what am I missing?
I can't really test this, but I'd suggest something like this. First, set up your curl, and create an array with an empty placeholder for thread_id.
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 'false');
$url2 = 'https://api.website.com/endpoint';
$data2 = array(
'specialkey' => '123abcd789xyz',
'anotherparam' => 'Brown',
'locale' => 'en-US',
'thread_id' => ''
);
Then loop over your array. For each item, replace the thread_id key in the $data2 parameters array with that item's id, build the query using http_build_query and execute the request.
foreach ($threadsarray['threads'] as $thread) {
$data2['thread_id'] = $thread['id']; // add the current id
$params2 = http_build_query($data2); // build the new query
curl_setopt($ch, CURLOPT_URL, $url2.'?'.$params2 );
$mycurlresult = curl_exec($ch);
echo '<pre>';
$resultarray = json_decode($mycurlrequest, TRUE);
print_r($resultarray);
echo '</pre>';
if (FALSE === $mycurlrequest)
throw new Exception(curl_error($ch), curl_errno($ch));
}

cURL to call API in PHP not working

I have tried calling the API using standard URL. All work perfectly directly from the browser. For e.g.:
http://www.worldcat.org/webservices/catalog/search/sru?query=srw.su%3D%22Computer organization%22&startRecord=101&maximumRecords=100&wskey=7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw
http://www.worldcat.org/webservices/catalog/search/sru?query=srw.su%3D%22Computer engineering%22&startRecord=101&maximumRecords=100&wskey=7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw
But when I use cURL to do it, I keep on having the error from the API that the wskey is not attached:
function curl_get_contents($url)
{
$ch = curl_init();
d($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
d($OCLCqueries);
foreach ($OCLCqueries as $OCLCquery) {
// echo "managed1";
$XMLdata = curl_get_contents($OCLCquery);
// echo "managed2";
}
I defined $OCLCqueries earlier. It is an array that contains the URL calls as values.
d() is a function that I call from an installed library which is a more sophisticated form of var_dump(), basically having the same purpose (serve as breakpoints for debugging) but dumping the data in a more human-readable format.
This is the output I have:
<body><h1>HTTP Status 400 - org.oclc.wskey.api.WSKeyException: WsKeyParam(wskey) not found in request</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>org.oclc.wskey.api.WSKeyException: WsKeyParam(wskey) not found in request</u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect (org.oclc.wskey.api.WSKeyException: WsKeyParam(wskey) not found in request).</u></p><HR size="1" noshade="noshade"><h3></h3></body>
How do I solve this problem?
Initially I thought the most likely reason for the failure was a lack of User-Agent string in the request but found, when testing the code below, that it's existence or not made no difference so I believe the problem is the format of the url used in the cURL request as it is already encoded. By separating the baseurl and the parameters as below it works fine.
$url='http://www.worldcat.org/webservices/catalog/search/sru';
$params=array(
'query' => 'srw.su="Computer organization"',
'startRecord' => 101,
'maximumRecords' => 100,
'wskey' => '7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw'
);
function curl_get_contents( $url=false, $params=array() ){
if( $url && !empty( $params ) ){
$url = $url . '?' . http_build_query( $params );
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0' );
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return (object)array(
'response' => $data,
'info' => $info
);
}
}
$data = curl_get_contents( $url, $params );
print_r( $data->response );
To simplify the call to the main function you could create a simple wrapper function like this.
function getcatalog( $baseurl=false, $term=false, $start=1, $max=1, $key=false ){
if( $baseurl && $term && $key ){
$params=array(
'query' => 'srw.su="'.$term.'"',
'startRecord' => $start,
'maximumRecords' => $max,
'wskey' => $key
);
return curl_get_contents( $baseurl, $params );
}
}
$data = getcatalog( $url, 'Computer organization', 1, 100,'7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw');
if( $data->info['http_code']==200 ){
print_r( $data->response );
}

cURL doesn't give any response on PHP script

I'm pretty new to PHP so any help would be greatly appreciated.
This is running on WAMP server with cURL enabled and is supposed to upload tracking for orders i'm trying to process. But when i run this script i don't get a response so i assume its broken somewhere however i don't get any errors so i'm unsure as to whats actually happening.
The problem seems to be cause but either the way I’m creating the $datatopost array or with the actual cURL part of my code I think.
if($_REQUEST)
{
$supplier = $_REQUEST["supplier_ID"];
$token = $_REQUEST["token"];
$filePath = $_REQUEST["filePath"];
$fileName = $_REQUEST["fileName"];
}
$itemID = array();
$array = file($filePath.$fileName);
foreach($array as $value)
{
$temp = explode(",",$value);
$itemID[] = array( "carrier" => $temp[1], "ci_lineitem_id" => $temp[0], "tracking" => $temp[2]);
}
$datatopost = array (
"supplier_id" => $supplier,
"token" => $token,
"tracking_info" =>json_encode($itemID)
);
$ch = curl_init ("https://scm.commerceinterface.com/api/v2/tracking_notification");
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
if( $response )
{
$response_json = json_decode( $response );
if( $response_json['success'] == true )
{
file_put_contents($filePath."Success.txt", $response);
}
else
{
file_put_contents($filePath."Failed.txt", $response);
}
}
file_put_contents($filePath."Success.txt", $responce);
file_put_contents($filePath."Failed.txt", $responce);
I think the variable $responce in the file_put_contents() method is unknown. Try to use $response.
You are trying to get a SSL secured site, so take a look at the CURLOPT_SSL_* options:
http://php.net/manual/en/function.curl-setopt.php.
For detailed information, you should check the cURL result (like already mentioned).

CURL PHP POST interferes with JSON

I currently have an API script that returns JSON. It has worked up until I tried to add in a curl php POST script before it. The curl script is working on it's own, and it is also working in the API script. However the JSON code is not being returned.
Is there something fundamentally wrong with this approach below?
Thanks in advance.
EDIT: The curl script works 100% on its own.
Said script is also working inside the below, it's just that the JSON does not return.
$name = "foo";
$age = "bar";
//set POST variables
$url = 'https://www.example.com';
$fields = array(
'name' => urlencode($name),
'age' => urlencode($age)
);
//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);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return json_encode(
array(
"status" => 1,
"message" => "Success!",
"request" => 10
)
);
You need to do the following use echo and also use CURLOPT_RETURNTRANSFER if not the output would be transferred directly to the page instead of $result
$name = "foo";
$age = "bar";
$url = 'http://.../a.php';
$fields = array('name' => urlencode($name),'age' => urlencode($age));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
header('Content-type: application/json');
echo json_encode(array("status" => 1,"message" => "Success!","request" => 10));

How to send form variables to multiple URLs in php (cURL?)

I seem to have run into a problem with trying to submit form variables to multiple urls.
The code i have below takes variables from a form and stores them in php, then I am trying to send those variables to certain urls (the variables do pass through, I've tested that). I heard cUrl is the way to do it, but I don't know if its working cause im stumped on how to to retrieve the response code.
<?php
$name = $_POST['firstname'];
$email = $_POST['email'];
$src = $_POST['srcUrl'];
$ip= $_SERVER['SERVER_ADDR'];
$suDate = date('Y-m-d H:i:s');
$data = array(
"fn" => $name,
"src" => $src,
"em" => $email,
"ip" => $ip,
"signupDate" => $suDate
);
$data2 = array(
"firstname" => $name,
"email" => $email,
);
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_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
post_to_url("http://exampleURL.com/page.php", $data);
post_to_url("http://exampleURL2.com/cgi-bin/add.cgi", $data2);
print_r($result);
?>
any help is greatly appreciated. thanks
In the code example you've provided above, $result contains the response you're looking for. To view the full details of the variable, use this:
print_r($result);
print_r is useful when you're not sure what data type a variable is or what data it might contain. print_r gives you all available information on the variable.
Edit: Also change curl_setopt($post, CURLOPT_POST, count($data)); to curl_setopt($post, CURLOPT_POST, 1); CURLOPT_POST is a true/false option (http://php.net/manual/en/function.curl-setopt.php).
Inside your function where you have $result = curl_exec($post); the $result data is the response. So you need to add return $return; and call the function with $response = post_to_url(...); and echo the response.

Categories