I'm trying to request a REST API using PHP Unirest.
The printed error is the following:
Bad URL, colon is first character
And my code:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Unirest\Request as UniRequest;
use CurlFile;
if (isset($_POST['primeiro'])) {
$where = $_POST["where"];
$equal = $_POST["equal"];
$resultado = new pedidos;
$valores = $resultado->LogIgualA($where, $equal);
}
class pedidos {
function LogIgualA($where, $equal) {
$wsURL = "localhost:8080/public";
try {
$valores = UniRequest::get($wsURL."/visual/json_log/where=".$where."/equal=".$equal, $headers, null);
} catch (Exception $e) {
echo $e->getMessage();
}
$valoresAux = $valores->body;
$valores = [];
foreach($valoresAux as $z){
$ID = $z->ID;
$DateConnection = $z->DateConnection;
$TimeToServe = $z->TimeToServe;
$ClientIP = $z->ClientIP;
$CacheCode = $z->CacheCode;
$Bytes = $z->Bytes;
$Method = $z->Method;
$RequestProtocol = $z->RequestProtocol;
$RequestIP = $z->RequestIP;
$RequestPort = $z->RequestPort;
$RequestFolder = $z->RequestFolder;
$Auth = $z->Auth;
$RouteLeft = $z->RouteLeft;
$RouteRight = $z->RouteRight;
$ContentType = $z->ContentType;
}
return $valores;
}
}
The "isset($_POST['primeiro']" is when I click the button in HTML so it calls the function in PHP.
I really don't know how to use this...
You need to prepend a protocol like https://.
There are other people having the same issue where prepending the protocol fixed this... https://github.com/Azure/doAzureParallel/issues/44
URL is not http: localhost:8080/public
Also check that there is no malicious input in your $_POST vars and maybe you need to use urlencode() on the fields containing appropriate characters.
Related
I'm using two API keys to receive the data. That's because provider have some daily quota limit. If quota exceeds the daily limit, 403 error is returned from the server.
I used $http_response_header to check the response from the server. But the problem is that when response returned isn't 200, e.g the API key used exceeds the daily limit, the code should execute again so that another API key is picked randomly. Here's the code I'm using:
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else{
echo 'No';
}
You can create a function of this code, and just re-run the function when the response is not 200. Something like this maybe?
function getAPIData() {
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else {
getAPIData();
}
}
Like #Jaquarh says, you might want to change max_execution_time also. Have a look here and see what works for you.
I've created perfect solution, check this:
$api = array('1st key','2nd key');
$k = array_rand($api);
$api_key_yt = $api[$k];
$total_api=count($api);
for ($loop=0;$loop<=$total_api;$loop++) {
$api_key_yt=$api[$loop];
$request2 = "https://example.com/?data&key=$api_key_yt";
$response = file_get_contents($request2);
$jsonobj = json_decode($response);
if (isset($jsonobj->items)) {break;} else {unset($jsonobj);}
}
print_r($jsonobj);
Please try this
$data = null;
do {
$keys = array('1stkey','2ndkey')
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
} while ($data == null);
I have a class function that calls JSON from a URL. That function then sets a list of variables from the results of the JSON.
What I am attempting to do is call back one of those strings from inside of another file (index.html). I do not receive any errors back, however the results are blank.
I'm sure it's not due to the json command because it works properly when not placed inside of a class/function. To be sure I attempted to add $somestring4 = 'this is string 4' into the ClassFile.php and call it - it was also blank.
Here is my code...
ClassFile.php
<?php
class newClass {
Function newFunction(){
$jsonFetched = file_get_contents('http://url.com/file.json'); //<== MISSING SINGLE QUOTES ADDED FOR CODE-READABILITY...
$jsonQuery = json_decode($jsonFetched);
$someString1 = $jsonQuery->level1->level2->string1 ;
$someString2 = $jsonQuery->level1->level2->string2 ;
$someString3 = $jsonQuery->level1->level2->string3 ;
}
}
$foo = new newClass;
?>
Call from Index.html
<?php
include($sitePath . '/classes/ClassFile.php') ;
$refClass = new newClass();
$someString3 = $refClass->newFunction();
echo $someString3;
?>
Thanks for the help and sorry for the ignorance.
<?php
class newClass {
public $jsonFetched = '';
public $jsonQuery = '';
public $someString1 = '';
public $someString2 = '';
public $someString3 = '';
function newFunction(){
$jsonFetched = file_get_contents('http://url.com/file.json');
$jsonQuery = json_decode($jsonFetched);
$this->someString1 = $jsonQuery->level1->level2->string1 ;
$this->someString2 = $jsonQuery->level1->level2->string2 ;
$this->someString3 = $jsonQuery->level1->level2->string3 ;
}
}
?>
<?php
include($sitePath . '/classes/ClassFile.php') ;
$refClass = new newClass();
$refClass->newFunction();
echo $refClass->someString3;
?>
I am trying to display records using PDO LIKE query, but I am getting this error message can I know how to solve this.
This is my code:
$rs = new JSONRecordSet();
$searchbooksSQL = "SELECT Title FROM l_stock WHERE Title LIKE ?";
$params = array("%$term%");
echo $rs->getRecordSet($searchbooksSQL, $params);
This is the getRecordSet code:
class R_RecordSet {
function getRecordSet($sql, $params = null) {
if (is_array($params)) {
$this->stmt = $this->db->prepare($sql);
// execute the statement passing in the named placeholder and the value it'll have
$this->stmt->execute($params);
} else {
$this->stmt = $this->db->query($sql);
}
return $this->stmt;
}
}
class JSONRecordSet extends R_RecordSet {
function getRecordSet($sql, $elementName = "ResultSet", $params = null) {
$stmt = parent::getRecordSet($sql, $params);
$recordSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
$nRecords = count($recordSet);
if ($nRecords == 0) {
$status = 'error';
$message = json_encode(array("text" => "No records found"));
$result = '[]';
} else {
$status = 'ok';
$message = json_encode(array("text" => ""));
$result = json_encode($recordSet);
}
return "{\"status\": \"$status\", \"message\":$message, \"$elementName\" :{\"RowCount\": $nRecords ,\"Result\": $result}}";
}
}
The error message i am getting is "Notice: Array to string conversion"
getRecordSet() is defined as:
function getRecordSet($sql, $elementName = "ResultSet", $params = null) {
however, you are calling it as:
echo $rs->getRecordSet($searchbooksSQL, $params);
You will need to modify your code to pass in an appropriate $elementName parameter. (The default is probably reasonable.)
echo $rs->getRecordSet($searchbooksSQL, 'ResultSet', $params);
Additionally, you should probably use json_encode() to generate the final result from JSONRecordSet::getRecordSet(), rather than building it up with string concatenation. It will make the code easier to read and understand.
Also, your two implementations of getRecordSet() are incompatible with each other, according to the Liskov Substitution Principle due to the change in the semantics of the input parameters, and is likely what led you to the parameter mismatch at your call site in the first place. You probably want to re-order JSONRecordSet::getRecordSet() parameters to:
function getRecordSet($sql, $params = null, $elementName = 'ResultSet') {
Here is the failure message I get in Terminal running 'phpunit tests':
1) StylistTest::test_find
null does not match expected type "object".
/Users/evanbutler/Desktop/hairSalonApp/tests/StylistTest.php:163
Here's my test method:
function test_find()
{
//Arrange
$name = "Stylist Jane";
$id = 1;
$name2 = "Stylist Bob";
$id2 = 2;
$test_stylist = new Stylist($name, $id);
$test_stylist->save();
$test_stylist2 = new Stylist($name2, $id2);
$test_stylist2->save();
//Act
$result = Stylist::find($test_stylist->getId());
//Assert
$this->assertEquals($test_stylist, $result);
}
And here's my method:
static function find($search_id)
{
$found_stylist = null;
$stylists = Stylist::getAll();
foreach($stylists as $stylist) {
$stylist_id = $stylist->getId();
if ($stylist_id == $search_id) {
$found_styist = $stylist;
}
}
return $found_stylist;
}
Here's my getAll method:
static function getAll()
{
$returned_stylists = $GLOBALS['DB']->query("SELECT * FROM stylists;");
$stylists = array();
foreach($returned_stylists as $stylist) {
$name = $stylist['name'];
$id = $stylist['id'];
$new_stylist = new Stylist($name, $id);
array_push($stylists, $new_stylist);
}
return $stylists;
}
If you'd like to see all my files here's the link to the git repository:
https://github.com/evanb2/hairSalonApp.git
I've been staring at this for way too long and I'm totally stumped.
Change
$found_styist = $stylist;
to
$found_stylist = $stylist;
You need a better IDE man. Simple static analysis could tell you about the unused variable.
I've been working with the PHP api for google Calendar, and have been getting quite frustrated.
I downloaded the zend package with all the libraries from google's page, and have been working off the provided code to make sure it can meet my requirements.
The issue I'm running into involves getting an event back from the system. The provided code includes a demo with function getEvent($clientId, $eventId), which based on the documentation and reading the code, i would expect to return an event that is in my calendar that matches the provided Id.
So in my tests, I create a new event, and then I try to retrieve it. However, whenever I retrieve the event, Zend_data_Gdata_App_HttpException is:
function processPageLoad()
{
global $_SESSION, $_GET;
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
requestUserLogin('Please login to your Google Account.');
} else {
$client = getAuthSubHttpClient();
$id = createEvent ($client, 'Tennis with Beth',
'Meet for a quick lesson', 'On the courts',
'2010-10-20', '10:00',
'2010-10-20', '11:00', '-08');
$newEvent = getEvent($client, $id);
}
}
the code for createEvent( ) is :
function createEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$startDate = '2008-01-20', $startTime = '10:00',
$endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08')
{
$gc = new Zend_Gdata_Calendar($client);
$newEntry = $gc->newEventEntry();
$newEntry->title = $gc->newTitle(trim($title));
$newEntry->where = array($gc->newWhere($where));
$newEntry->content = $gc->newContent($desc);
$newEntry->content->type = 'text';
$when = $gc->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$newEntry->when = array($when);
$createdEntry = $gc->insertEvent($newEntry);
return $createdEntry->id->text;
}
And finally the code for getEvent() is:
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
}
we have the same problem, just share my solution. since you assign $id = createEvent()
$id will have a URL values. then you use $id getEvent($client, $id);
the solution is that getCalendarEventEntry() can have a $query or just a URL.
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($eventId);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
Hope it helps!!