angularjs, ionic, and json decode using php - php

I'm working with Ionic framework and AngularJS. I want to retrieve data from Mysql and decode to JSON using PHP so that I can use it in my Ionic App.
Here is my PHP code
<?php
/*
Here was my php codes to get all data from mysql and assign it to $episode array
*/
header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
echo json_encode($episode);
//close the db connection
mysqli_close($connection);
When I run my App in the browser The console gave me this error
XMLHttpRequest cannot load http://***Here Was My Url***/episodes.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
The code for controller
$scope.posts = [];
var Url = "http://here was my url/episodes.php";
$http.get(Url)
.success(function(response){
console.log("Reveived getPosts via HTTP: ", response, status);
angular.forEach(response, function(child){
$scope.posts.push(child);
});
})
.error(function(response, status){
console.log("Error while received response. " + status + response);
});
But when I run the App in a real device the array gave me this
http://i.imgur.com/lI2ihb9.png
Hope you can help me to solve it.

Add this to your index.php file
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
Alternatively you could also add this to your .htaccess file:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Related

php cors issue with axios post

I have a simple post request with axios to php script which renders some pdfs and should return a String.
Now I got this error:
Access to XMLHttpRequest at 'IP:7580/pdfgen/pdfGen.php' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I set this in my php file:
<?php
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
With no changes. also tried this:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
also no changes.
my axios call looks like this:
axios.post("http://IP:7580/pdfgen/pdfGen.php", this.state)
.then(response => {
report = {...this.state.report};
report.createdAt = reportCreatedAt;
window.open(response.data);
this.setState({report: report, pdf: response.data});
console.log(response);
})
What could solve this?
Thanks in advance
A working solution for me is:
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 1000');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
}
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization");
}
exit(0);
}

CORS Allow-Access-Control-Origin on Mobile Chrome

I am getting an error on mobile, when I use Chrome to try out my new responsive web app. I have done everything from add php headers in several different ways, to passing headers in my ajax request. On the web, I used CORS toggle, a Chrome extension that allows you to toggle on and off CORS, which fixes the problem on web. Yet I cannot seem to find a solution like this for mobile. Anyway I can bypass CORS on mobile Chrome??
I have tried ALL of these ways, and nothing seems to work..
php option 1:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With');
header('Access-Control-Allow-Methods: GET, PUT, POST');
?>
php option 2:
<?php
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
echo "You have CORS!";
?>
jQuery AJAX:
$.ajax({
url: '<MY API ENDPOINT>',
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With",
'Access-Control-Allow-Methods': "GET, PUT, POST",
'Authorization':
'Bearer <MY TOKEN>',
'Cache-Control': 'no-cache'
},
data: formData,
processData: false,
contentType: false
}).done(function(res) {
Remove the access control headers from your ajax request. Access control headers are automatically set by the browser as defined in the W3C CORS spec.
Whatever headers you include in your ajax request, you need to allow in the server response. In your case it's Authorization and Cache-Control. Add them to Access-Control-Allow-Headers.
Use option 2 of your php code. It includes a response for the cors preflight OPTIONS request. Option 1 will not work for that reason.

jQuery .get() :Rrequest to external API - Access error : Doesn't match

I have already taken a look at this link and cannot seem to find where my issue is even after constant debugging.
I know my .htaccess file works because it works for internal requests and the ReWrite is working as expected.
My current .htaccess code (on the API server) however is:
Header set Access-Control-Allow-Origin "*"
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^API/Public /API/Public/api.php [QSA,L]
My PHP file headers (on the API server) are:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
However, I still get this error when I try now send a request to that API server:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.com/API/Public/?start=example. (Reason: CORS header 'Access-Control-Allow-Origin' does not match 'http://sendingfrom.com, *').
using this code:
$.get('http://www.example.com/API/Public/', { start: 'example' })
.done(function(test){
alert(test);
});
Could someone please offer me any help to where I have gone wrong or what I am missing? Thanks so much in advance!
Omg, I found the fix here.
I had to remove the whole PHP headers:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}

php session value is not working in chrome browser but working in postman?

i am working with RESTFUL APIs . my front-end(http://localhost:3000/) and back-end(http://workless/services) are in different origin. Because of that i have implemented the CORS mechanism to access the sevice from different origin.
it like bellows..
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
// optional configuration
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
Everything is working on postman tools, trouble is while i'm going to call some apis which is needed saved session value it's return 401 status because of losing the session value..
The session value is not stored while accessing via chrome/mozilla but it's working on postman..
can anyone please say why it occurs??

CORS POST request in ZF2 becomes OPTIONS request instead

Is there anyway in Zend Framework 2 to allow CORS on my API?
I have already allowed all origins header("Access-Control-Allow-Origin: *");
Every time I send a POST request with headers the server responds with 405.
On my access log I see the the request is actually OPTIONS
Yes - extend the \Zend\Mvc\Controller\AbstractRestfulController::options method in your controller, if your controller class is extending from it. By default, it returns a 405, which is probably why you see that response.
Headers can be set via \Zend\Http\Headers::addHeaders
Note: "Zend" is currently "Laminas", since Zend Framework has become Laminas.
So to start with your php script should do these checks:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
Once you do that CORS will be enabled.

Categories