curl is not working in Yii - php

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.

Related

how to pass dynamic URL to curl in php - getting error 1

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']}";

Yii2 request PUT not working properly

I am using a rest api in yii2 with Authorization : Bearer and my update action requires sending data using PUT. I have configured the actionUpdate completely but somehow i am not getting any data in Request PUT.
I found few articles online about problems with Yii2 PUT but could not find out weather there is any solution to that yet or not?
One of the article or issue is github issue and it points to this github issue
Ad if no solution yet than what alternative should i use for Update action.
Here is my actionUpdate code
public function actionUpdate($id)
{
$params = Yii::$app->request->bodyParams;
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id' => Yii::$app->user->id])->one();
if($model !== null){
$model->load($params, '');
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
}
}
}
This is a screenshot of debug screen. See the event_name attribute.
That was screenshot after the execution of $model->load($params,'') line.
I am calling the service like following and not able to Update the data properly. My service works fine through postman.So i guess i am missing something in CURL request.
$service_url = 'http://localhost/site-api/api/web/v1/events/'.$eventDetailDBI->gv ('id');
$curl = curl_init($service_url);
$curl_post_data = array(
"event_name" => $eventDetailDBI->gv ('name'),
);
$header = array();
$header[] = 'Authorization: Bearer 4p9mj82PTl1BWSya7bfpU_Nm';
$header[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
$json = json_decode($curl_response, true);
curl_close($curl);
I am getting correct data in my POST fields and passing correct data but the service doesnt update any data.
Thank you
try this:
public function actionUpdate($id)
{
// this will get what you did send as application/x-www-form-urlencoded params
// note that if you are sending data as query params you can use Yii::$app->request->queryParams instead.
$params = Yii::$app->request->bodyParams;
$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id' => Yii::$app->user->id])->one();
if($model !== null){
// This will load data to your safe attribute as defined in your model rules using your default scenario.
$model->load($params, '');
$model->partner_id = Yii::$app->user->id;
$model->updated_date = time();
if ($model->save()) {
/*
you can use Yii::$app->getResponse()->setStatusCode(200) here but no need to do that.
response will be 200 by default as you are returning data.
*/
// yii\rest\Serializer will take care here of encoding model's related attributes.
return [
'status' => 1,
'data' => $model
];
}
else {
// when validation fails. you model instance will hold error messages and response will be auto set to 422.
return $model;
}
}
}

POST url with Curl PHP

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.

Decoding JSON after sending using PHP cUrl

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 &quot 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.

writing cURL like function in a rails app

I'm trying to convert this PHP cURL function to work with my rails app. The piece of code is from an SMS payment gateway that needs to verify the POST paramters. Since I'm a big PHP noob I have no idea how to handle this problem.
$verify_url = 'http://smsgatewayadress';
$fields = '';
$d = array(
'merchant_ID' => $_POST['merchant_ID'],
'local_ID' => $_POST['local_ID'],
'total' => $_POST['total'],
'ipn_verify' => $_POST['ipn_verify'],
'timeout' => 10,
);
foreach ($d as $k => $v)
{
$fields .= $k . "=" . urlencode($v) . "&";
}
$fields = substr($fields, 0, strlen($fields)-1);
$ch = curl_init($verify_url); //this initiates a HTTP connection to $verify_url, the connection headers will be stored in $ch
curl_setopt($ch, CURLOPT_POST, 1); //sets the delivery method as POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //The data that is being sent via POST. From what I can see the cURL lib sends them as a string that is built in the foreach loop above
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This verifies if the target url sends a redirect header and if it does cURL follows that link
curl_setopt($ch, CURLOPT_HEADER, 0); //This ignores the headers from the answer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //This specifies that the curl_exec function below must return the result to the accesed URL
$result = curl_exec($ch); //It ransfers the data via POST to the URL, it gets read and returns the result
if ($result == true)
{
//confirmed
$can_download = true;
}
else
{
//failed
$can_download = false;
}
}
if (strpos($_SERVER['REQUEST_URI'], 'ipn.php'))
echo $can_download ? '1' : '0'; //we tell the sms sever that we processed the request
I've googled a cURL lib counterpart in Rails and found a ton of options but none that I could understand and use in the same way this script does.
If anyone could give me a hand with converting this script from php to ruby it would be greatly appreciated.
The most direct approach might be to use the Ruby curb library, which is the most straightforward wrapper for cURL. A lot of the options in Curl::Easy map directly to what you have here. A basis might be:
url = "http://smsgatewayadress/"
Curl::Easy.http_post(url,
Curl::PostField.content('merchant_ID', params[:merchant_ID]),
# ...
)

Categories