Manupulate Error file_get_contents - codeigniter

I have a script
$data = file_get_contents('http://my_example_link/data.xml');
and if http://my_example_link/data.xml is showing error
Failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
I would like to create condition if the link is showing error above I will showing alert notification using bootstrap panel.
can I doing like that ?

You can do it with curl, Please refer curl_getinfo
<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check HTTP status code
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
}
}
// Close handle
curl_close($ch);
?>

Related

`406 Not Acceptable` response: Error 406 - Not Acceptable

I uploaded laravel5.6 project on server and got this error. Running well on local machine.
when we request api using guzzle with laravel throwing error. Below is my code requesting api.
try{
$response = $this->client->request('GET',$this->url.'index');
$response = $response->getBody()->getContents();
}catch (\GuzzleHttp\Exception\ClientException $e) {
echo 'Caught response: '.$e;
}
returns
Caught response: GuzzleHttp\Exception\ClientException: Client error: GET http://example.com/api/index resulted in a 406 Not Acceptable response:Error 406 - Not Acceptable
How to get solve this error

Google places API returning failed to open stream: HTTP request failed error

I am hoping for some direction on this error. I have a loop that connects with the google places API. Every few times I test it I get an HTTP request failed error. But when I take the API call from the error it works in a browser or in postman. Any suggestions for what might be causing this? Thanks for all of your help. Here is my API call and the error.
$googleApiPlaceUri = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
foreach ($attractions as $attraction) {
$api_call = "{$googleApiPlaceUri}?query={$attraction}+in+{$city}&key={$api_key}";
$api_return_array[] = json_decode(file_get_contents($api_call));
foreach ($api_return_array as $result) {
$results = $result->results;
array_push($results_array, $results);
}
}
Here is the error I get...
Warning: file_get_contents(https://maps.googleapis.com/maps/api/place/textsearch/json?query=hiking +in+Denver&key=API_KEY): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Which status code should I return?

I am doing an dropbox.js upload. I am checking for errors on the server and returning them to my frontend via json. So far so good.
header('HTTP/1.1 500 Internal Server Error');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 100)));
on my frontend I can catch the error and do some nice stuff to alert the user
error: function(file, errorMessage, xhr) {
console.log(xhr);
// catch the error and alert the user
}
The problem is the errors are not really 'server errors' so how should I return them in the header? A 500 does not seem appropriate. It does not I suppose really matter but would nice to return the right type of error.
The kind of errors include
filename is not unique
wrong file type
file is too large
What is the best status code to use?
Thanks.

How to get data from API google?

I have access_token and now to try get fata from Google API using this sample:
https://developers.google.com/android-publisher/api-ref/edits/details/get
I try to get data executing query to this URL:
https://www.googleapis.com/androidpublisher/v2/applications/packageName/edits/editId
$curl = new Curl();
$curl->get('https://www.googleapis.com/androidpublisher/v1/applications/com.shazam.android&access_token='.$_SESSION['access_token']["access_token"]);
Where $_SESSION['access_token']["access_token"] is access_token
As a result I get message: Error: 404: HTTP/1.1 404 Not Found
How to get information from API?
This is full URL request, it does not work:
https://www.googleapis.com/androidpublisher/v2/applications/com.shazam.android/edits/1?access_token=ya29.Ci-5Azg5JoBiESM5cEzM3TQrP3SXHAFirFg0f-Fj83PxtrtINWQDe2L-3f5wP7oAtQ
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Full code is:
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
$curl = new Curl();
$curl->get('https://www.googleapis.com/androidpublisher/v1/applications/com.shazam.android/edits/1/&access_token='.$_SESSION['access_token']["access_token"]);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
} else {
echo 'Response:' . "\n";
var_dump($curl->response);
}
// Create an authorized analytics service object.
//$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
//$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
//$results = getResults($analytics, $profile);
//printResults($results);
} else {
$redirect_uri = 'http://localhost/play/oauth2callback.php';
header('Location: ' . $redirect_uri);
}
After getting access_token I try to make Curl request:
$curl = new Curl();
$curl->get('https://www.googleapis.com/androidpublisher/v1/applications/com.shazam.android/edits/1/&access_token='.$_SESSION['access_token']["access_token"]);
Well, another possible caused of error 403 or Insufficient Permission is that the scope that you are using is incorrect or you have not requested the scopes you need when you retrieved your access token. So try to double check the scope that you are using and enable all the API in the Dev Console that you are using.
You can check which scopes you have requested by passing your access_token to this endpoint:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN
For more information, check the solution in these related SO question if it can help you.
Permission issue Google Play
Google API 'Insufficient Permission'?

WebWorks AJAX Cross domain request

I'm working on a playbook app with webworks sdk.
I'm trying to make an http request (method: post) by sending AND recieving data.
I can get the response from server, but the server can't get the $POST data, when I try to display $_POST['apiKey'], nothing apears, I checked my code 100 times, checked my config.xml for uri, can't find the error.
TL;DR: can't send but can receive data.
My PHP Server code:
echo "passed key is: ".$_POST["apiKey"]; // Nothing apears
echo "<br>";
if(md5($_SESSION['private_key'])===$_POST["apiKey"]){
}
else{
echo "Invalid API Key"; // Always getting this response on client app
exit();
}
?>
My JS Client code:
function httpRequest(){
var key="a984a4474cff54d8468a296edf3af65b";
document.getElementById("status").innerHTML="Reaching server...";
//////////////////////////////////////
var xdr = getXDomainRequest();
xdr.onload = function() {
document.getElementById("status").innerHTML=xdr.responseText;
}
xdr.open("POST", "http://mydomain/index.php");
xdr.send("apiKey="+key);
}
Solved:
When using POST method you should define the request header:
xdr.open("POST", "http://mydomain.com/index.php");
xdr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // with this line
xdr.send("apiKey="+key);
Solved: When using POST method you should define the request header:
xdr.open("POST", "http://mydomain.com/index.php");
xdr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // with this line
xdr.send("apiKey="+key);

Resources