I'm trying to use my webservice by curl:
public function getImages($time) {
$url = $this->rest_url['employees'] . "?action=getAllNewPhotos&accessKey=" . $this->rest_key['employees'] . "&lastcheck=" . $time;
$data = $this->CI->curl->simple_get($url);
if ($data) {
return json_decode($data);
} else {
return null;
}
}
But it keeps giving me the following error:
Fatal error: Call to a member function simple_get() on a non-object
Why is that?
Also if I add curl in my autoload it says:
Unable to load the requested class: curl
However if I run my code by following code, there is no problem:
$url = $this->rest_url['employees'] . "?action=getAllNewPhotos&accessKey=" . $this->rest_key['employees'] . "&lastcheck=" . $time;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
if ($data) {
return json_decode($data);
} else {
return null;
}
I'm just curious why my first approach is not working!
If you need more clarification, please let me knwo!
Thanks
You seem to be mixing a few things.
If you want to load this as a Codeigniter library, you need to first create it as one. Steps are found in the User Guide. This will go in your libraries directory.
simple_get() should then be a function on your class library called "curl". However, I would probably use a different name to avoid naming clashes
Related
I'm using Slim framework to access the functions from existing PHPFox website. I'm just a newbie to Slim framework so truing to learn it.
I've included the necessary file for this. But the issue I'm facing is I'm always getting "404 Page Not Found" error upon making request. Even I tried to print the message "Object Created" after creation of object, it got printed that means till this point there is no error. When I try to get inside the function by echoing some message I got 404 error.
Can someone please help me in correcting the mistake I'm making in my code?
Following is my code (login_ws.php):
<?php
require 'Slim/Slim.php';
require('config.php');
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
//Object created
$application->map (
'/login/:login/:password/:divice_type',
function()
{ echo "Ina funcionality"; die;
global $application;
if($application->request->isGet()) {
$login = $application->request->get('login');
$password = $application->request->get('password');
$divice_type = $application->request->get('divice_type');
/*$divice_token = $application->request->get('divice_token');*/
}
if($application->request->isPost()) {
$login = $application->request->post('login');
$password = $application->request->post('password');
$divice_type = $application->request->post('divice_type');
/*$divice_token = $application->request->post('divice_token');*/
}
list($bLogged, $aUser) = Phpfox::getService('user.auth')->login($login, $password);
if($aUser['user_image']) {
$aUser['user_image'] = Phpfox::getParam('core.url_user').$aUser['user_image'];
} else {
$aUser['user_image'] = '';
}
if((!empty($aUser)) && ($bLogged>0)) {
$msg='Login succesfully';
Phpfox::getService('user.auth')->setUserId($aUser['user_id']);
$appKey = Phpfox::getService('apps')->getKey('3');
$test = doPost("http://localhost/token.php?key=".$appKey);
$arrayToken = json_decode($test);
$aUser['token'] = $arrayToken->token;
$aUser['key'] = $appKey;
} else {
$msg='Login Failed';
$aUser[]=$login;
$aUser[]=$password;
}
$result=array('status'=>$bLogged ? 'true' : 'false','data'=>$aUser,'msg'=>$msg);
header("Content-Type: application/json");
echo json_encode($result);
}
)->via('GET','POST');
//Purpose of via() : The function will be invoked when there is a match for the URI whether the request is using HTTP GET or HTTP POST method.
$application->run();
function doPost($aParams) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $aParams);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
The request I'm making through browser's URL is as follows:
http://localhost/webservice/login_ws.php/login?login=admin#gmail.com&password=admin123&divice_type=iphone
Please help me in correcting the mistake I'm making. Also if you find I'm doing anything in wrong way which is not standard for Slim framework please correct me. I'd be more than happy for it.
Thanks.
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 creating an application for Google App engine, where CURL isn't allowed.
As far as I know, urlFetch is the best alternative.
I don't know if I can achieve the same result with urlFetch, but I would really, really appreciate it if anyone with more experience could help me out.
The plan was to convert the following CURL requests to urlFetch. If anyone can point me in the right direction, or propose a better alternative, I'd greatly appreciate it.
public function postCall($endpoint, $post_data, $param1, $param2, $json=1, $headers=false) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $this->options['url'].$endpoint);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
if ($headers && is_array($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$post_data['req_token'] = $this->hash($param1, $param2);
curl_setopt($ch, CURLOPT_POST, count($post_data));
if (!$headers)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
else
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data);
$this->debug('POST params: ' . json_encode($post_data));
$result = curl_exec($ch);
if ($result === false) {
$this->debug('CURL error: '.curl_error($ch));
return false;
}
$this->debug('HTTP response code' . curl_getinfo($ch, CURLINFO_HTTP_CODE));
$this->debug('POST return ' . $result);
// close connection
curl_close($ch);
if ($json)
return json_decode(utf8_encode($result), true);
else
return $result;}
Did you look at the Urlfetch documentation and the linked PHP article about wrappers?. You can experiment with this live shell.
The code could be translated to something like:
public function postCall($endpoint, $post_data, $param1, $param2, $json=1, $headers=false) {
$post_data['req_token'] = $this->hash($param1, $param2);
$this->debug('POST params: ' . json_encode($post_data));
$data = http_build_query($post_data);
$options =
array("http"=>
array(
"method" => "POST",
"content" => $post_data,
)
);
if ($headers && is_array($headers)) {
$options["http"]["header"] = $headers;
}
$context = stream_context_create($options);
$result = file_get_contents("http://app.com/path?query=update", false, $context);
if ($result === FALSE) {
$this->debug('Error: '. print_r($http_response_header));
return FALSE;
}
$this->debug('Response headers:' . print_r($http_response_header)); // To get the status code you would need to parse that response
$this->debug('POST return ' . $result);
if ($json)
return json_decode(utf8_encode($result), true);
else
return $result;
}
Here is simple library which replaces curl native functions with urlfetch. https://github.com/azayarni/purl
Someone here suggested using the PURL from azayarni. Let me warn you: avoid using it on Google App Engine. I spent SEVERAL days trying to get it work without success: the Google PHP Client SDK is rewriting itself some CURL functions and simply PURL mess it up a lot. Some things were working, some were not. The URLFETCH tool is much more easier and safe.
Its a very old post, but just an update: Google App Engine now supports cURL with its PHP 5.5 runtime.
Hey all I have seen several questions on the topic here, but none of them have solved my problem. I have a script on my site which I want to use to generate several different types of emails to my users. I wanted a way to be able to create template files for the different emails which accept $_POST variables to fill in relevant information, and to simply make a post request to these templates and get back the response to place as the body of the email. I am attempting to write a function which would accept the location of the template file (either relative or absolute would work, but I would prefer relative honestly), and an array of parameters that I would like to send to the template via post. So far I have had no luck. Here is my code so far:
private function post_request($url, $data) {
$output = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = curl_error($ch);
}
curl_close($ch);
return $output;
}
I have been getting the error "couldn't connect to host" from curl, but after outputting my url to an error log I have been able to verify that copying and pasting the URL into firefox results in seeing the page correctly.
Any ideas? I am not married to the idea of using curl, so if there is a better option I would be more than happy to use it instead. Thanks for the help all!
You should be able to use file_get_contents() for this, so long as your host has not prevented it from accessing remote locations (and the $url script is not looking exclusively for POST data).
private function post_request($url, $data) {
$output = array();
$url_with_data = '';
foreach ( $data as $k=>$v ){ // Loop through data and create request string
$url_with_data .= '&' . $k . '=' . $v;
}
// Remove first ampersand and encode the data
$url_with_data = urlencode( substr( $url_with_data, 1 ) );
// Request file
// Format will be http://url.com?var1=data&var2=data&var3=data
$result = file_get_contents( $url . '?' . $url_with_data );
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = 'Could not open remote file';
}
return $output;
}
Another option: You say that both files reside on the same server. If that is the case, you could simply require() the template builder.
private function post_request($url, $data) {
$output = array();
#require_once('./path/to/template_builder.php');
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = 'Could not open remote file';
}
return $output;
}
Then in template_builder.php:
<?php
unset( $result );
if ( is_array( $data ) ){
// Parse $data ...
$result = $email_template;
}
As it turns out, the issue ended up being a server configuration error. The server was timing out while attempting to contact the file because it was hitting the wrong DNS server. Fixing that solved my problem!
I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz