Attaching get fields to URL using Curl in PHP - php

I am able to perform server and client side redirects using Curl but I am unable to attach GET fields to the URL via a get request, here is my code:
$post = curl_init();
curl_setopt($post,CURLOPT_URL,$url);
curl_setopt($post,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($post, CURLOPT_USERAGENT,'Codular');
curl_setopt($post, CURLOPT_CUSTOMREQUEST,'GET');
curl_exec($post);
curl_close($post);
Nothing gets attached when I perform the execution, what am I doing wrong?
New code I am using:
function curl_req($url, $req, $data='')
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
if (is_array($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$temp = array("akash"=>"test");
$result = curl_req("http://localhost/test.php", 'POST', $temp);
echo $result;
print_r($result);
test.php:
print_r($_POST);
print_r($_REQUEST);

Try this:
// Fill in your DATA below.
$data = array('param' => "datata", 'param2' => "HelloWorld");
/*
* cURL request
*
* #param $url string The url to post to 'theurlyouneedtosendto.com/m/admin'/something'
* #param $req string Request type. Ex. 'POST', 'GET' or 'PUT'
* #param $data array Array of data to be POSTed
* #return $result HTTP resonse
*/
function curl_req($url, $req, $data='')
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
if (is_array($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Fill in your URL below.
$result = curl_req("http://yourURL.com/?", "POST", $data)
echo $result;
This works fine for me.

Related

how to send post data using curl in php array json

how to send post data using curl in php array json
post curl param orderlist like an array
this is my code
<?php
class PostOrderPolicy extends CI_Controller{
public function index(){
$data = $this->getData();
foreach ($data as $key) {
$orderListt = array(
'orderDate' => $key['order_date'],
'IDNumber' => $key['IDnumber'],
'itemDescription' => $key['description']
);
$send = $this->sendData($orderListt, $key['resi_number']);
if ($send) {
$res["message"] = "Sukses";
}else{
$res["message"] = "Gagal";
}
}
//echo json_encode($res);
}
private function getData(){
$sql = "SELECT * FROM t_transaction WHERE status='00'";
return $this->db->query($sql)->result_array();
}
private function sendData($data){
$result = array();
$url = "https://contoh.co.id/createPolicy";
$res = array();
$sign = $this->getSign();
$upperSign = strtoupper($sign);
//$random = $this->getRandomStr();
$random = '049KN1PSOL16QHIF';
$batch = 'BATCH000002';
$dataArr = array(
'sign' => $upperSign,
'randomStr' => $random,
'batchNo' => $batch,
'orderList' => [$data]
);
$string = json_encode($dataArr);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$response = json_decode(curl_exec($ch), TRUE);
print_r($response);
print_r($string);
}
}
?>
but my result post field
[enter image description here][1]
[1]: https://i.stack.imgur.com/b7LEP.png
i want like this
[enter image description here][2]
[2]: https://i.stack.imgur.com/xExJ2.png
{"sign":"35EAF78F95A52DDA79FC9911559026F6","randomStr":"049KN1PSOL16QHIF","batchNo":"BATCH000002","orderList":[{"orderDate":"2020-07-01 11:00:00.000","resiNumber":"99875646957","itemDescription":"testing"},{"orderDate":"2020-07-01 ]11:00:00.000","IDNumber":"28929740170","itemDescription":"testing"}]}
Return response instead of outputting:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Execute the POST request:
$result = curl_exec($ch);
Close cURL resource:
curl_close($ch);

how to view final url before submission curl php

I want to know final url just before executing curl to check all parameters passing as desired. how to view that.
<?PHP
function openurl($url) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
openurl($sms_url);
?>
desired output to check all params and its values passing correct..
http://remoteserver/plain?user=user123&password=user#user!123&Text=TESThere
You forgot to add the $postvars as parameter to your function.
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
// create a test var which we can display on screen / log
$test_url = sms_url . http_build_query($postvars);
// either send it to the browser
echo $test_url;
// or send it to your log (make sure loggin is enabled!)
error_log("CURL URL: $test_url", 0);
openurl($sms_url, $postvars);

get data from URL using file_get_contents and cURL

I am using codeigniter framework.
I want to retrieve the data from the URL provided. I already tried this answers: tried.
Problem is that when i access the url that time it is printing the data. but when i try it with file_get_contents function, it is not going to print any data.
<?php
$url ='https://test.com/getSessionData';
$test = file_get_contents($url);
$t = json_decode($test);
var_dump($t);
?>
That url returns json data like:
{
"email": "test#t.com",
"LOGIN": true,
"name": "testing",
"logintype": "ca"
}
Also tried using cURL:
<?php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
?>
But it is not working and it returns empty. i have checked that allow_url_fopen is on.
This might helpful
http://php.net/manual/en/migration56.openssl.php
So code looks like this:
<?php
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/path/to/bundle/ca-bundle.crt",
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://test.com/getSessionData", false, stream_context_create($arrContextOptions));
echo $response; ?>
This is the class I said:
/**
* Created by PhpStorm.
* User: rain
* Date: 15/11/2
* Time: 下午4:08
*/
class MyCurlLibrary{
public static function getRequest($url,Array $data=array(),$isNeedHeader=0){
$ch = curl_init();
if($data){
$bindQuery = http_build_query($data);
$url.="?".$bindQuery;
}
curl_setopt($ch, CURLOPT_URL, $url);
//if need return
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//this is for https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, $isNeedHeader);//if contains header
//this is for web redirect problem
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public static function postRequest($url,Array $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post Data
curl_setopt($ch, CURLOPT_POST, 1);
// post variable
if($data){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($ch);
curl_close($ch);
//return data
return $output;
}
}
/**
* sample
*
* //test Data
$url = "http://localhost:8080/test/test.php";//改文件有代码 print_r($_GET); print_r($_POST)
$data = array('a'=>'b','c'=>'d',8=>666,888);
//test get function
$result = MyCurl::getRequest($url,$data);
//test post function
$result = MyCurl::postRequest($url,$data);
//print result
var_dump($result);
*
*
*/

Hubstaff - retrieve data with php cURL

I'm trying to connect with hubstaff api, has anyone ever tried it? I'm a newbie in php-cURL, how do you convert this to PHP Curl?
curl -H "App-Token: BMyQnju-4tknuBQMsN0ujr6NWF5ohQaP9de8AWMJXik" -H "Auth-Token: X-vfv2c7jf_0NKoHLbX1t4yftK-TI-jZ4d7roNegw24" "http://api.hubstaff.com/v1/users"
It also would not show any result of I do this:
// Standard data
$data['app_token'] = $this->app_token;
// Debugging output
$this->debug = array();
$this->debug['HTTP Method'] = $http_method;
// Create a cURL handle
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'App-Token: ' . $this->app_token,
'Content-Type: application/xml'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Send data
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Debugging output
$this->debug['Posted Data'] = $data;
}
// Execute cURL request
$curl_response = curl_exec($ch);
// Save CURL debugging info
$this->debug['Last Response'] = $curl_response;
$this->debug['Curl Info'] = curl_getinfo($ch);
// Close cURL handle
curl_close($ch);
// Parse response
$response =$curl_response;// $this->parseAsciiResponse($curl_response);
// Return parsed response
return $response;
Im just trying to get my Auth-Token
Any help would be greatly appreciated.
#Michal I have solved my own problem and created this simple class to help anyone else in connecting with hubstaff fast. feel free for any suggestions and optimizations
class HubstaffApi {
private $app_token = '';
private $auth_token = '';
private $debug = [];
public function __construct($app_token, $auth_token) {
$this->app_token = $app_token;
$this->auth_token = $auth_token;
}
private function sendRequest($api_method, $http_method = 'GET', $data = null) {
// Standard data
$data['app_token'] = $this->app_token;
$request_url = "https://api.hubstaff.com/v1/";
// Debugging output
$this->debug = array();
$this->debug['Request URL'] = $request_url . $api_method;
// Create a cURL handle
$ch = curl_init();
// Set the request
curl_setopt($ch, CURLOPT_URL, $request_url . $api_method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'App-Token: ' . $this->app_token,
'Auth-Token: ' . $this->auth_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// Send data
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Debugging output
$this->debug['Posted Data'] = $data;
}
// Execute cURL request
$curl_response = curl_exec($ch);
// Save CURL debugging info
$this->debug['Last Response'] = $curl_response;
$this->debug['Curl Info'] = curl_getinfo($ch);
// Close cURL handle
curl_close($ch);
// Parse response
$response = $curl_response;
// Return parsed response
return $response;
}
public function users(array $parameters = array()) {
return $this->sendRequest('users', 'GET', $parameters);
}
public function activities(array $parameters = array()) {
return $this->sendRequest('activities', 'GET', $parameters);
}
public function screenshots(array $parameters = array()) {
return $this->sendRequest('screenshots', 'GET', $parameters);
}
}
You can simply use this by:
$Hubstaff = new HubstaffApi(
YOUR_APP_TOKEN,
YOUR_AUTH_TOKEN); //simply get auth token in developer.hubstaff 's generator, it doesn't expire anyway.
$response = $Hubstaff->activities([
"start_time" => "2015-09-10T00:00:00+08:00:00",
"stop_time" => "2015-09-10T24:00:00+08:00:00",
"users" => YOUR_HUBSTAFF_ID
]);
echo $response;

URL encode error?

My PHP code (free.php) on http://techmentry.com/free.php is
<?php
{
//Variables to POST
$access_token = "b34480a685e7d638d9ee3e53cXXXXX";
$message = "hi";
$send_to = "existing_contacts";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freesmsgateway.com/api_send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('access_token' => $access_token,
'message' => urlencode('hi'),
'send_to' => $send_to,)
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>
I am getting this error: THE MESSAGE WAS BLANK
This error means: "The message field was blank or was not properly URL encoded" (as told by my SMS gateway). But as you can see that my message field isn't blank.
I believe you can't send an array to CURLOPT_POSTFIELDS, you would need to replace the line with the following
curl_setopt($ch, CURLOPT_POSTFIELDS, "access_token=".$accesstoken."&message=".urlencode('hi')."&send_to=".$send_to);
I hope this solves it
Use http_build_query():
<?php
{
$postdata = array();
//Variables to POST
$postdata['access_token'] = "b34480a685e7d638d9ee3e53cXXXXX";
$postdata['message'] = "hi";
$postdata['send_to'] = "existing_contacts";
//Initialize CURL data to send via POST to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://freesmsgateway.com/api_send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata) );
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result";
}
?>

Categories