Quite sure I'm doing something wrong here, just don't know what or where.
I have a Laravel controller that handles an ajax post request and returns the results of a curl request to that ajax call:
public function store()
{
/** Receive long and lat through ajax **/
$long = Input::get('longitude');
$lat = Input::get('latitude');
$location = $lat . "," . $long;
$url = blablable;
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$result = curl_exec($curl);
return $result;
curl_close($curl);
}
This works: the curl returns a JSON array, which gets passed back to the ajax call.
But now I want to save the incoming data to the database:
$location = new Location();
$location->latitude = Input::get('latitude');
$location->longitude = Input::get('longitude');
$location->save();
I add those 4 lines at the top of the function, the data gets saved to the database but the JSON array get's grabbled, somehow <!-- app/models/Location.php --> gets added to the top of the return, making the JSON array invalid.
No clue as to what is causing this so any hints or suggestions are highly appreciated!
-- Edit 1 --
The result of Input::all(); is
array(2) {
["latitude"]=>
string(10) "50.8809794"
["longitude"]=>
string(9) "4.6920714"
}
This is not intended as a solution, but as a way to clean up your code a bit:
You don't need to use curl and can use Request::create() and Route::dispatch() instead.
You should use the protected $fillable attribute in your model, to clean up the new entry.
Your code can become:
public function store()
{
// This is for saving the entry
$location = new Location();
$location->fill(Input::all());
$location->save();
// This is for the cURL
// (assuming this is a GET requst, but other methods are available)
$request = Request::create('/path/to/url/', 'GET');
$response = Route::dispatch($request);
// Do stuff with the $response or just return it
return $response;
}
Related
I am making rest API with Yii Plus when I am trying to print_r request (using Postman) it's empty, can anyone let me know what I am doing wrong.
<?php
namespace frontend\controllers;
use Yii;
use yii\rest\Controller;
class ApiController extends Controller
{
Const APPLICATION_ID = 'ASCCPE';
private $format = 'json';
public function actionUserRegister()
{
$request = \Yii::$app->request->post(); $post = (file_get_contents("php://input"));
print_r($request);
die('sdw');
}
}
Output
You are not trying to print request. You are trying to print post data, but you are not sending any post data by your request.
The \Yii::$app->request->post(); returns data from $_POST array. This array is filled from request body only for data that have been sent in form-data or x-www-form-urlencoded format.
In postman click open the body part of request, select one of the two mentioned formats and fill the data you want to send.
If you want to use other format for request, like json or xml, you have to read it from php://input. You already have it in your code:
$post = (file_get_contents("php://input"));
So try to print the $post instead of $request variable. But you still need to fill the body part of request in postman.
The params you've set in postman are the GET params. Those are part of request's url. You can get them for example like this:
$request = \Yii::$app->request->get();
You are returning with the message in the die function.
Instead of this you can try this way:
die(print_r($request, true));
Example:
public function actionCreate()
{
$request = Yii::$app->request->post();
die(print_r($request, true));
}
better:
return print_r($request, true);
Example:
public function actionCreate()
{
$request = Yii::$app->request->post();
return print_r($request, true);
}
better:
// include the VarDumper class
\Yii::info(VarDumper::dumpAsString($request));
// output will be located in your app.log file
More info on the print_r function
Example:
public function actionCreate()
{
return Yii::$app->request->getBodyParams();
}
I am using the SageOne API PHP Library. It works fine, but I get an error if I try to use get or post.
The error is,
Only variables should be passed by reference sage.api.php on line 130
My get request code is
$client = new SageOne(SAGE_CLIENT_ID, SAGE_CLIENT_SECRET);
$client->setAccessToken("c7c7547xxxxxxxxxxxx8efa4f5df08f750df");
$data = array( );
$result = "";
$client = $client->get('/products', $data);
I don’t know what’s wrong.
Full Code
require 'sage.api.php';
define('SAGE_CLIENT_ID', "fa1e8c1b114347a356d2");
define('SAGE_CLIENT_SECRET', "faaa7b353521f823ba13e3a20e72dd057c3a5fd1");
$client = new SageOne(SAGE_CLIENT_ID, SAGE_CLIENT_SECRET);
$callbackURL = 'xxxxx/addonmodules.php?module=sageone';
// We need to build the authorise url and redirect user to authorise our app
if(!$_GET['code']){
$authoriseURL = $client->getAuthoriseURL($callbackURL);
// redirect user
header("Location: ".$authoriseURL);
exit;
// We now have the authorisation code to retrieve the access token
} else {
$accessToken = $client->getAccessToken($_GET['code'], $callbackURL);
$token= $accessToken['access_token'];
$end = 'public';
$data ='';
$result = $client->get($end, $data);
echo '<pre>';
print_r($result);
Code Snippets from sage.api.php
class SageOne { ...
...
public function get($endpoint, $data=false){
return $this->call($endpoint, 'get', $data);
}
...
// error line 130 from this code
private function buildSignature($method, $url, $params, $nonce){
// uc method and append &
$signature = strtoupper($method).'&';
// percent encode bit of url before ? and append &
$signature .= rawurlencode(array_shift(explode('?', $url))).'&';
// percent encode any params and append &
if (is_array($params)){
// sort params alphabetically
$this->ksortRecursive($params);
// build query string from params, encode it and append &
$signature .= str_replace(
array('%2B'),
array('%2520'),
rawurlencode(http_build_query($params, '', '&'))
).'&';
// params can be string
} else {
// build query string from params, encode it and append &
$signature .= rawurlencode($params).'&';
}
// add 'nonce' - just use an md5
$signature .= $nonce;
// now generate signing key
$signingKey = rawurlencode($this->signingSecret).'&'.rawurlencode($this->accessToken);
// encode using sha 1, then base64 encode
$finalSignature = base64_encode(hash_hmac('sha1', $signature, $signingKey, true));
return $finalSignature;
}
This is the shortest i can make to see all important code
This is due to trying to return the result of a function or method directly to another function or method... the result doesn't have a reference.
So, for example:
$obj->method(doSomething(), 'asdf', 'qwerty');
The error means you should assign the value of doSomething() before passing it.
$result = doSomething();
$obj->method($result, 'asdf', 'qwerty');
Also see: Only variables should be passed by reference
A function (in this case, $client->get()) can be defined to receive its parameters by reference. This means that it can modify those parameters directly. So if you call $client->get($a, $b), the function may alter the values of $a and $b.
Clearly, it can only alter the values of variables, so when a function receives a parameter by reference, you must pass it a variable, not a string, an integer, or a direct call to another function.
So if the function $client->get() receives its first parameter by reference, none of the following can work:
$client->get('string', $data);
$client->get(15, $data); // int
$client->get(other_function_call(), $data);
$client->get(12.5, $data); // float
$client->get(array(), $data);
You have to do this:
$a = 'string';
$client->get($a, $data);
Or $a = whatever, be it a string, an int, a function call. The point is (and this is stated quite clearly in the error message) that you must pass a variable. So save whatever you want to pass as a variable, then pass that.
The title may not make sense, not sure how to word it. Anyways, i'm practicing curl and OOP at the same time here with the riot games API. the API is kind of set up dumb where some info you want to request requires input that you wouldn't know off hand, so it requires another separate call to get the required info first.
class league
{
const URL = 'http://prod.api.pvp.net/api/lol/na/v1.1/';
const URL_2 = 'http://prod.api.pvp.net/api/lol/na/v2.1/';
const KEY = 'key';
public function summonerByName($summoner_name)
{
$request = 'summoner/by-name/' . $summoner_name . '?api_key =' . self::KEY;
return $this->fetch($request);
}
public function recentGamesByName($summoner_name)
{
//need to make two calls for this since you cant get recent games by name in the api
$id = summonerByName($summoner_name);
//now get recent games
$request = 'game/by-summoner/' . $id->id . '/recent';
return $this->fetch($request);
}
private function fetch($request)
{
$url = self::URL . $request . '?api_key=' . self::KEY;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
return json_decode($data);
}
}
this is returning Fatal error: Call to undefined function summonerbyname()
if i use all this extra code below in the public function recentGamesByName() instead of $id = summonerByName() it works fine, but it seems unnecessary, and i want to replace that with just the function.
$grg = self::URL . 'summoner/by-name/' . $summoner_name . '?api_key=' . self::KEY;
$placeholder = curl_init($grg);
curl_setopt($placeholder, CURLOPT_RETURNTRANSFER, 1);
$ph_result = curl_exec($placeholder);
curl_close($placeholder);
$ph_result = json_decode($ph_result);
$id = $this->summonerByName($summoner_name);
You may want to read up on OOP.
A couple of things to remember about OOP. When you're INSIDE the class and need to call another function, you use the the special $this variable.
So you would use:
$someVariable = $this->summonerByName($summoner_name);
to get the results from that function.
If you're OUTSIDE the class and need to access that function, then you need to assign the entire class to a variable like so:
$league = new league();
and then you can access any function within the class using that variable.
So you could do...
$someVariable = $league->summonerByName($summoner_name);
if you had already assigned the class to a variable name $league. By the way, that $league variable? It's called an object. Thus Object Oriented Programming. Objects are kinda like arrays, but use a different syntax. You can print_r an object just like you can print_r an array. When accessing an object's variable you use the $objectName->variableName syntax instead of $arrayName['variablename'] syntax that you use in arrays.
In Symfony2, I want to test a controller action with 2 subsequent requests if it behaves properly.
The first request will analyze the database and take appropriate action, the second request will also analyze the database and take a different action.
My code goes as follows:
protected function setUp() {
$this->_client = static::createClient();
$kernel = static::$kernel;
$kernel->boot();
$this->_em = $kernel->getContainer()->get('doctrine.orm.default_entity_manager');
$this->_em->beginTransaction();
}
public function testAddToCartWith2Posts() {
$this->addObjects(); // Initialize the database
$object = static::$kernel->getContainer()->get('doctrine')->getRepository('BaseBundle:Object')->findAll()[0];
$id = $object->getId();
$crawler = $this->_client->request('POST', '/cart/add/' . $id);
$crawler = $this->_client->request('POST', '/cart/add/' . $id);
$session = static::$kernel->getContainer()->get('session');
$cart = $session->get('cart');
$this->assertEquals($session->getId(), $cart->getSession());
$this->assertEquals(2, count($cart->getCartItems()));
}
The first request is able to read the list of objects. The second request is not.
The database becomes empty between requests. How could I fix this problem?
Im trying to use the GiantBomb api to query video games, and currently when I enter the URL into a browser, it works just fine. The Json data shows up.
Heres an example url..
http://www.giantbomb.com/api/search/?api_key=83611ac10d0dfghfgh157177ecb92b0a5a2350c59a5de4&query=Mortal+Kombat&format=json
But when I try to use my php wrapper that Im just starting to build, it returns html??
Heres the start of my wrapper code....(very amateur for now)
You'll notice in the 'request' method, Ive commented out the return for json_decode($url), because when I uncomment it, the page throws a 500 error??? So I wanted to see what happends when I just echo it. And it echos an html page. Surely it should just echo what is shown, when you just enter that url into the browser, no?
However...if I replace the url with say a GoogleMap url, it echoes out Json data just fine, without using json_decode. Any ideas as to wahts going on here????
class GiantBombApi {
public $api_key;
public $base_url;
public $format;
function __construct() {
$this->format="&format=json";
$this->api_key = "83611ac10d0d157177ecb92b0a5a2350c59a5de4";
$this->search_url = "http://www.giantbomb.com/api/search/?api_key=".$this- >api_key."&query=";
}
public function search($query){
$query = urlencode($query);
$url = $this->search_url.$query.$this->format;
return $this->request($url);
}
public function request($url) {
$response = file_get_contents($url);
echo $response;
//return json_decode($response, true);
}
}
//TESTING SECTION
$games = new GiantBombApi;
$query = $_GET['search'];
echo $games->search($query);
I ran a few requests through Postman and it seems that the api looks at the mime-type as well as the query string. So try setting a header of "format" to "json".