Post data with curl to another server - php

I try to post some data to another server using curl. The problem is that I get nothing on the other server.
Server1:
$a = $USER->id;
$b = $USER->username;
error_reporting(-1);
$url = 'http://remote_server/a.php';
$data = array(
'cus' => $a,
'cust' => $b
);
$postString = http_build_query($data, '', '&');
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 2);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$post = curl_exec ($ch);
curl_close ($ch);
and on Server2:
<?php
session_start();
var_dump($_POST);
?>
Of course it doesn't work, it gives array(0) {}.
So, how I will see the data on the other server?

To see the actual output of var_dump($_POST) in Server2, you must either :
Server1 side : echo $post variable
Server2 side : write the content of var_dump's result in a file :
ob_start();
var_dump($_POST);
$output = ob_get_clean();
$fp = fopen('log.txt', 'a');
fwrite($fp, $output);
fclose($fp);

Related

JSON Encode To PHP Variable via Curl fails with empty response

i have searched a lot on google and here but im not getting any further with my problem. I am not a coder though I am trying to parse JSON to PHP Variables, but i get an empty response, where i want a table to be shown or at least any jsondata
Here is what my code looks like:
<!DOCTYPE html>
<html>
<body>
<h1>Available Agents </h1>
<?php
$url = 'https://url/livewebservice/imoscontactagentstate?Username=username&Pwd=password&Cmd=GetState&ResultType=JSON';
// Initiate curl
$ch = curl_init ($url);
$data = json_encode ($data,true);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
' Content-Type: application/x-www-form-urlencoded ',
'charset=utf-8')
);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
var_dump(json_decode($result, true));
print_r($result);
foreach ($result as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
?>
</body>
</html>
I am grateful for any hints
Try to remove true from $data = json_encode ($data,true); as far as can i remember true is used only in json_decode to create an associative array
The problem was solved my Username did not have the permission to access the data and we made minor changes to the code so it looks like this:
php
$data = array(
"UserName" => "Username",
"Pwd" => "Password",
"Cmd" => "GetAgentStateList",
"ResultType" => "JSON",
);
$url='https://host/livewebservice/service/?'.http_build_query($data);
echo $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded", "charset=UTF-8",));
$result = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
curl_close($ch);
$f_result=json_decode($result);
print_r($f_result);
?>
i hope this helps someone coming from google someday.

How to properly send a JSON CURL to Slack?

I have a CURL code that I use to integrate with GetResponse and I thought ill go ahead and copy/paste it for slack too. For some reason there are no errors at all yet slack is empty of requests (a POST to this URL with Postman works just fine). What am I missing? I couldn't find a solution the whole night.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
$slackReporting_error = "";
if(empty($slackReporting_res->error)){
echo "OK";
} else {
$slackReporting_error = $slackReporting_res->error->message;
}
echo $slackReporting_error;
?>
I always get an OK.
Since you din't return anything from function so you are getting nothing inside $slackReporting_res .Do like below:-
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);exit;
}
curl_close($ch);
return $content;
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
var_dump ($slackReporting_res); //check output and work accordingly
?>
And now Op's got error and solved through this link(mentioned by OP in comment):-
PHP - SSL certificate error: unable to get local issuer certificate
Here is a simple example of how to use slack with curl
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
$msg = array('text' => $txt);
$c = curl_init(SLACK_WEBHOOK);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
curl_exec($c);
curl_close($c);
}
?>
Snippet taken from here

PHP upload and send file with cURL

I'm attempting to upload a file to a WordPress installation and then send it, along with other data from other form fields, to Lever's API.
I can send data to the endpoint just fine, but not so much with the file uploading. The following does in fact upload to wp-content/uploads, but I think the problem lies either on the next line move_uploaded_file or where I'm passing it in the $data array.
<form enctype="multipart/form-data" method="post" action="<?php echo get_template_directory_uri(); ?>/jobForm.php">
<input type="file" name="resume">
<button type="submit">Submit</button>
</form>
<?php
// URL
$url = "https://api.lever.co/v0/postings/XXXX/XXXXXX";
$name = $_POST["name"];
$email = $_POST["email"];
$urls = $_POST["urls"];
$target = "/www/wp-content/uploads/" . basename($_FILES["resume"]["name"]);
move_uploaded_file($_FILES["resume"]["tmp_name"], $target);
// data
$data = array(
"name" => $name,
"email" => $email,
"urls" => $urls,
"resume" => #$_FILES["resume"]
);
// initiate curl instance, set options, and post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // url
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // full data to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return results as a string instead of outputting directly
echo $data["resume"];
// $output
$output = curl_exec($ch);
var_dump($output);
// close curl resource to free up system resources
curl_close($ch);
?>
I tried using the $target variable for the "resume" $data value, but that didn't seem to work either. As you can probably tell, I'm not exactly sure where this is going wrong (I'm a front-end developer out of my element :D).
Echoing $data["resume"] gives an Array, while echoing $target gives the location + name of the file, as expected. I guess I'm unsure what I need to be passing through in the $data array...Any ideas what I'm doing wrong here? If it helps, I get no error from Lever when submitting. In fact, it returns a 200 OK message and posts just fine, just without a resume field!
You can do that like this
$localFile = $_FILES[$fileKey]['tmp_name'];
$fp = fopen($localFile, 'r');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'someurl' . $strFileName); //$strFileName is obvious
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
else {
$msg = 'File uploaded successfully.';
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);

parse json data from curl

server.php
// some code here .....
// this is the end of the file:
$json_data = array(
'test1'=>hello world,
'test2'=>hello stack
);
echo json_encode($json_data);
api.php
$text = api("http://example.com/?TEXT=$text&APIKEY=$apikey");
// return the json from server.php file
echo $text;
function api($url) {
$ch = curl_init();
$timeout = 20;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
the file api.php return the json successfully
{"test1":"hello world","test2":"hello stack"}
The problem is when I try to parse the returned JSON in order to get the value of test1 it doesn't show anything.
I tried something like this it but can't parse the JSON.
$obj=json_decode($text);
// dosent show anything
echo $obj->test1;
Put quotes around the values in your array.
$json_data = array(
'test1'=>"hello world",
'test2'=>"hello stack");

How to read CURL POST on remote server?

This is my cURL POST function:
public function curlPost($url, $data)
{
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
$this->curlPost('remoteServer', array(data));
How do I read the POST on the remote server?
The remote server is using PHP... but what var in $_POST[] should I read
for e.g:- $_POST['fields'] or $_POST['result']
You code works but i'll advice you to add 2 other things
A. CURLOPT_FOLLOWLOCATION because of HTTP 302
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
B. return in case you need to output the result
return $result ;
Example
function curlPost($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $result;
}
print(curlPost("http://yahoo.com", array()));
Another Example
print(curlPost("http://your_SITE", array("greeting"=>"Hello World")));
To read your post you can use
print($_REQUEST['greeting']);
or
print($_POST['greeting']);
as a normal POST request ... all data posted can be found in $_POST ... except files of course :) add an &action=request1 for example to URL
if ($_GET['action'] == 'request1') {
print_r ($_POST);
}
EDIT: To see the POST vars use the folowing in your POST handler file
if ($_GET['action'] == 'request1') {
ob_start();
print_r($_POST);
$contents = ob_get_contents();
ob_end_clean();
error_log($contents, 3, 'log.txt' );
}

Categories