How to call action using CURL in magento? - php

I have to call action using CURL, because of backround process. Below is my code.
$url = "http://www.domain.com/index.php/checkout/cart/deleteall";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$data = curl_exec($ch);
$errorMsg = curl_error($ch);
curl_close($ch);
echo $data;
echo '<br/>';
echo $errorMsg;
die();
Cart Controller action
public function deleteallAction()
{
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item){
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
}
$this->_redirectReferer(Mage::getUrl('*/*'));
}
I have create deleteallAction in cart controller. But CURL its not working. Its also not give me any error. I have call this in ajax.
Please guide me, if I am wrong.
Thank you!

Jimmeh.you need to change action url http://www.domain.com/index.php/checkout/cart/updatePost and change action method post
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.domain.com/index.php/checkout/cart/updatePost");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"update_cart_action=empty_cart&cart=$quoteId");
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
As you add new action in cartcontroller the for empty cart use code $this->_emptyShoppingCart(); to empty cart.
See more at cartcaontollers
public function updatePostAction()
{
$updateAction = (string)$this->getRequest()->getParam('update_cart_action');
switch ($updateAction) {
case 'empty_cart':
$this->_emptyShoppingCart();
break;
case 'update_qty':
$this->_updateShoppingCart();
break;
default:
$this->_updateShoppingCart();
}
$this->_goBack();
}
How curl works http://davidwalsh.name/curl-post

Related

Unable to get json data from rest api in php

code:
<?php
$url = base_url()."eventapi";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result, true));
?>
eventapi controller
<?php
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Eventapi extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function index_get()
{
$data['client_id'] = $this->session->userdata('client_id');
$client_id = $data['client_id'][0]['client_id'];
$this->db->select('*');
$this->db->from('event');
$this->db->where('client_id',$client_id);
$sql = $this->db->get();
$result = $sql->result_array();
$this->response($result, 200);
}
}
output:
array(0) { }
eventapi data
[{"id":"1","client_id":"20190702082406","event_type":"Private Event","event_name":"Birthday Celebration","event_date":"2019-08-15","event_time":"08:00 PM","event_des":"Birthday celebration ","s_date":"2019"}]
I am creating a simple rest API using Codeigniter where API works fine. Now, the problem is that when I am getting data from eventapi using curl it shows me output i.e array(0) { } I don't know why? So, How can I solve this issue? Please help me.
Thank You
If the above one is your code, you didn't add any parameters. The array passing with empty input. So you get empty output. Please correct the input.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
$inputParameters");
Please add these lines along with the curl .
And don't forget to add the header also .
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Retrieving data of curl post in PHP

I am trying to senddata to a url by using curl with codeigniter. I have successfully implemented the code for sending the data as below.
function postToURL($reg_no, $data)
{
$url = 'http://localhost/abcSystem/Web_data/viewPage';
$send_array = array(
'reg_no' =>$reg_no,
'data' =>$data,
);
$fields_string = http_build_query($send_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$post_data = 'json='.urlencode(json_encode($send_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if (curl_errno($ch)) {
die('Couldn\'t send request: ' . curl_error($ch));
} else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
print_r('success'); // this is outputting
return $output;
} else {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
}
The out put is success. I want to see if this post data can be retrieved. So I tried to change the above url controller file as below.
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
But nothing is printing. I want to get the data of posting. Please help me on this.
Your Written code
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
is not to Print or capture Posted Data . Because you are dealing with Current Page PHP INPUT Streaming , whereas you are posting data on Other URL . So what you need to do is just Put a log of posted data in File. Use below code after $output = curl_exec($ch)
file_put_contents("posted_data.txt", $post_data );
This way you will be able to write your each post in file Posted_data.txt File - Make sure you give proper File Permission. If you want to keep trace of each POST than just make the file name dynamic so per API Call it can write a log.
Another option is to save the $post_data in DATABASE - Which is not suggestable from Security point of view.
Where ever you are calling your postToURL() function, you need to output the result of it.
For example:
$output = postToURL('Example', array());
echo $output;
This is because you are returning the curl output rather outputting it.

how to post the value in url using PHP

I am creating a web service. I have tried to write an URL but its throwing error. I am not getting where I am going wrong. I want to pass these variable values in url and depending on this i want to call the web service
<?php
if($_POST["occupation"] == '1'){
$occupation = 'Salaried';
}
else{
$occupation = 'Self+Employed';
}
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?interestRateType='.$_POST["interestRateType"]'.&occupation='.$_POST["occupation"].'&offeringTypeId='.$_POST["offeringID"].'&city='.$_POST["city"].'&loanAmt='.$_POST["loanAmt"].'&age='.$_POST["age"];
echo $url;
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json = json_decode($result, true);
//print_r($json);
//echo $json['resultList']['interestRateMin'];
$json_array = $json['resultList'];
print_r($json_array);
?>
Try below code. You have syntax error before &occupation
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?interestRateType='.$_POST["interestRateType"].'&occupation='.$_POST["occupation"].'&offeringTypeId='.$_POST["offeringID"].'&city='.$_POST["city"].'&loanAmt='.$_POST["loanAmt"].'&age='.$_POST["age"];
Copy this because there is some ' and . error
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?
interestRateType='.$_POST["interestRateType"].'&
occupation='.$_POST["occupation"].'&
offeringTypeId='.$_POST["offeringID"].'&
city='.$_POST["city"].'&
loanAmt='.$_POST["loanAmt"].'&
age='.$_POST["age"];

Github api request with php curl

I am trying to get the latest commit from github using the api, but I encounter some errors and not sure what the problem is with the curl requests. The CURLINFO_HTTP_CODE gives me 000.
What does it mean if I got 000 and why is it not getting the contents of the url?
function get_json($url){
$base = "https://api.github.com";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $base . $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CONNECTTIMEOUT, 1);
$content = curl_exec($curl);
echo $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $content;
}
echo get_json("users/$user/repos");
function get_latest_repo($user) {
// Get the json from github for the repos
$json = json_decode(get_json("users/$user/repos"),true);
print_r($json);
// Sort the array returend by pushed_at time
function compare_pushed_at($b, $a){
return strnatcmp($a['pushed_at'], $b['pushed_at']);
}
usort($json, 'compare_pushed_at');
//Now just get the latest repo
$json = $json[0];
return $json;
}
function get_commits($repo, $user){
// Get the name of the repo that we'll use in the request url
$repoName = $repo["name"];
return json_decode(get_json("repos/$user/$repoName/commits"),true);
}
I use your code and it will work if you add an user agent on curl
curl_setopt($ch, CURLOPT_USERAGENT,'YOUR_INVENTED_APP_NAME');

PubSubHubbub error to confirm subscription

I use this code:
<?php
if(isset($_GET["hub_challenge"])) {
echo $_GET["hub_challenge"];
}
else {
}
$ch = curl_init("http://pubsubhubbub.appspot.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,"hub.mode=subscribe&hub.verify=sync&hub.callback=http://rssreaderbg.net/pubsubbub/example/index.php&hub.topic=http://rssreaderbg.net/blog/?feed=comments-rss2");
curl_exec($ch);
file_put_contents("logmeme.txt",$HTTP_RAW_POST_DATA);
?><?php
if(isset($_GET["hub_challenge"])) {
echo $_GET["hub_challenge"];
}
else {
}
$ch = curl_init("http://pubsubhubbub.appspot.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,"hub.mode=subscribe&hub.verify=sync&hub.callback=http://rssreaderbg.net/pubsubbub/example/index.php&hub.topic=http://rssreaderbg.net/blog/?feed=comments-rss2");
curl_exec($ch);
file_put_contents("logmeme.txt",$HTTP_RAW_POST_DATA);
?>
But the hub at pubsubhubbub.appspot.com gives me "Error trying to confirm subscription" ,why?
The simplest solution is to try performing a subcription verification yourself.
Send a GET request to your callback with the params as explained in the spec. Make sure your callback returns a 2XX and only echoes the hub.challenge provided by the hub.

Categories