I have a thank you page with URL that contains variables :
http://vieillemethodecorpsneuf.com/confirmation-achat-1a/?item=1&cbreceipt=VM6JQ6VE&time=1429212702&cbpop=C123FA24&cbaffi=twitpalace&cname=Roberto+Laplante&cemail=roberto%40gmail.com&ccountry=FR&czip=000
I have this GET function to catch the variables :
<?php
$clickbank_name = (isset($_GET['cname'])) ? $_GET['cname'] : '';
$clickbank_email = (isset($_GET['cemail'])) ? $_GET['cemail'] : '';
$clickbank_country = (isset($_GET['ccountry'])) ? $_GET['ccountry'] : '';
$clickbank_zip = (isset($_GET['czip'])) ? $_GET['czip'] : '';
$clickbank_aff = (isset($_GET['cbaffi'])) ? $_GET['cbaffi'] : '';
?>
Now I need to use curl PHP to send the data to that Zapier URL (but with the variables attached to it so it will give me) :
https://zapier.com/hooks/catch/bheq6y/?tag=client&cbaffi=twitpalace&cname=Roberto+Laplante&cemail=roberto%40gmail.com&ccountry=FR&czip=000
ps. I have added a manual tag to the URL
What would be the PHP Curl code to make this work? Need to be behind the scene operation.
I'll give it a shot.
$get_fields = ['tag' => 'client'];
if (isset($_GET['cname'])) $get_fields['cname'] = $_GET['cname'];
if (isset($_GET['cemail'])) $get_fields['cemail'] = $_GET['cemail'];
if (isset($_GET['ccountry'])) $get_fields['ccountry'] = $_GET['ccountry'];
if (isset($_GET['czip'])) $get_fields['czip'] = $_GET['czip'];
if (isset($_GET['cbaffi'])) $get_fields['cbaffi'] = $_GET['cbaffi'];
$encoded = '';
foreach($get_fields as $name => $value){
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
$url = 'https://zapier.com/hooks/catch/bheq6y/?'.rtrim($encoded,'&');
// simple get curl
$output = file_get_contents($url);
// or if you want more control over the request
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
$output = curl_exec($curl);
curl_close($curl);
In this example, we are posting data in parameters to another curl.php page and in curl.php,
i wrote some code to get executed whenever curl.php get called and the result will be sent back to page from where curl.php got a request.
Mechanism : This example is made in PHP using Curl.
First Step : Create curl.php file. That file will be called by another php file by using curl mechanism.
So in curl.php we will get some parameters. We get parameters and do some functionalities. After that when we desire output,
we just encode with json using json_encode() and simple echo.
$post = $_POST;
echo json_encode($post);
Note : index.php will get the data in json format because we are sending back data in json format to index.php
Second Step : we have to create an index.php file. Where we write a logic for executiing a curl with some parameters and then call curl.php and get result from curl.php
$url = 'http://localhost/curl_demo/curl.php'; // This is my targeted file(curl.php) that i want to execute when curl executed
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'id=1&name=sanjay'); // pass parameters to curl.php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$resArr = json_decode($response, true);
curl_close($ch);
print_r($resArr);
Note: The data that we get after curl executed successfully, we will get it in json format. That means we have to decode it using json_decode() in php.
Related
I'm trying to pass a $url to curl using a function.
the URL is built with a variable in it in the following method:
a.php // main page, include (a.php, b.php)
b.php // dynamic string function
c.php // curl function
I build a dynamic string successfully using sessions data // $_SESSION["input"]
myDynamicstringfunction set a string by multiple sessions input values.
$dval = myDynamicstringfunction();
echo $dval;
// render correctly to: "-e5 -g6 -g7"
the $dval value is a string that resolve as expected. the $url is:
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 $dval";
The $url is render correctly with the
echo $url;
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
I pass the $url to the curl function using:
$r = mycUrlfunction($url);
The curl function I use:
function singleRequest($url){
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$curly = curl_exec($ch);
if ($curly == FALSE){
die("cURL Error: " . curl_error($ch));
}
$result = json_decode($curly, true);
// close cURL resource, and free up system resources
curl_close($ch);
echo '<pre>';
return ($result);
}
The above get me an error (curl 1) - CURLE_UNSUPPORTED_PROTOCOL (1)
I have tried many things to get the $url to work with no success.
if I set the $url value manually without the $dval variable like this:
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
The code works just fine and I get the correct results from the API call.
I tried using different quotes, {}, [], encoding to ASCII, vprintf(), and other solutions with no success.
the problem was with constructing the dynamic variable $dynamicstring of the URL
initially used
$dynamicstring= "-a" . $_SESSION["a"]." -b".$_SESSION['b']." -c".$_SESSION['c']." -d".$_SESSION['d']."<br>";
this have a few problems
when using echo it render the expected output correctly
it have a "<br>" at the end
it have the wrong structure
the correct way to construct the $dynamicstring is to use {}
$dynamicstring= "-a{$_SESSION["a"]} -b{$_SESSION['b']} -c{$_SESSION['c']} -d{$_SESSION['d']}";
I want to pass a string from one PHP file to another using $_GET method. This string has different value each time it is being passed. As I understand, you pass GET parameters over a URL and you have to explicitly tell what the parameter is. What if you want to return whatever the string value is from providing server to server requesting it? I want to pass in json data format. Additionally how do I send it as Ajax?
Server (get.php):
<?php
$tagID = '123456'; //this is different every time
$tag = array('tagID' => $_GET['tagID']);
echo json_encode($tag);
?>
Server (rec.php):
<?php
$url = "http://192.168.12.169/RFID2/get.php?tagID=".$tagID;
$json = file_get_contents($url);
#var_dump($json);
$data = json_decode($json);
#var_dump($data);
echo $data;
?>
If I understand correctly, you want to get the tagID from the server? You can simply pass a 'request' parameter to the server that tells the server what to return.
EDIT: This really isn't the proper way to implement an API (like, at all), but for the sake of answering your question, this is how:
Server
switch($_GET['request']) {
case 'tagID';
echo json_encode($tag);
break;
}
You can now get the tagID with a URL like 192.168.12.169/get.php?request=tagId
Client (PHP with CURL)
When it comes to the client it gets a bit more complicated. You mention AJAX, but that will only work for JavaScript. Your php file can't use AJAX, you'll have to use cURL.
$request = "?request=tagID";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '192.168.12.169/get.php' . $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
EDIT: added the working cURL example just for completeness.
Included cURL example from: How to switch from POST to GET in PHP CURL
Client (Javascript with AJAX)
$.get("192.168.12.169/get.php?request=tagId", function(data) {
alert(data);
});
when i am using curl in my core php file it's working fine for me and getting expected result also... my core php code is...
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://stage.auth.stunnerweb.com/index.php?r=site/getUser");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
echo $data; //here i am getting respond proper
here in above i am making call to getUser function and i am getting respond from that function...
but now my problem is when i am using this same code in my any Yii controller (tried to use it in SiteController & Controller) but it's not working...
public function beforeAction()
{
if(!Yii::app()->user->isGuest)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL ,"http://stage.auth.stunnerweb.com/index.php?r=site/kalpit");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
echo $data;
}
else
return true;
}
in yii can't we use curl like this?
Can you please suggest me how to use curl in yii?
Thanks in advance
Better use yii-curl
Setup instructions
Place Curl.php into protected/extensions folder of your project
in main.php, add the following to 'components':
php
'curl' => array(
'class' => 'ext.Curl',
'options' => array(/.. additional curl options ../)
);
Usage
to GET a page with default params
php
$output = Yii::app()->curl->get($url, $params);
// output will contain the result of the query
// $params - query that'll be appended to the url
to POST data to a page
php
$output = Yii::app()->curl->post($url, $data);
// $data - data that will be POSTed
to PUT data
php
$output = Yii::app()->curl->put($url, $data, $params);
// $data - data that will be sent in the body of the PUT
to set options before GET or POST or PUT
php
$output = Yii::app()->curl->setOption($name, $value)->get($url, $params);
// $name & $value - CURL options
$output = Yii::app()->curl->setOptions(array($name => $value))->get($get, $params);
// pass key value pairs containing the CURL options
You are running your code inside a beforeAction() method which is not supposed to render any data at all. On top of that, you do not let the method return anything if the current user is a guest. Please read the API docs concerning this.
I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
Now the question:
How can I process the json response format of moodle system? Any idea would be great.
[UPDATE]:
I have used another approach via curl and changed in php.ini following lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice: Trying to get property of non-object. Here is the updated code:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};
I've researched everywhere and cannot figure this out.
I am writing a test cUrl request to test my REST service:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
This works fine and the request is accepted by my service and $_Post is populated as required, with two variables, order and data. Data has the encoded JSON object. And when I print out $_Post['data'] it shows:
{"products":{"product1":"abc","product2":"pass"}}
Which is exactly what is expected and identical to what was sent in.
When I try to decode this, json_decode() returns nothing!
If I create a new string and manually type that string, json_decode() works fine!
I've tried:
strip_tags() to remove any tags that might have been added in the http post
utf8_encode() to encode the string to the required utf 8
addslashes() to add slashes before the quotes
Nothing works.
Any ideas why json_decode() is not working after a string is received from an http post message?
Below is the relevant part of my processing of the request for reference:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
Turns out that when JSON is sent by cURL inside the post parameters & quot; replaces the "as part of the message encoding. I'm not sure why the preg_replace() function I tried didn't work, but using html_entity_decode() removed the " and made the JSON decode-able.
old:
$return_obj->setData(json_decode($data['data']));
new:
$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);
try it im curious if it works.