When I send POST request with json data in React app to PHP server, $_POST is empty.
And also php://input doesn't work.
I tried with following code.
PHP server side:
if($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization');
header('Access-Control-Max-Age: 1000');
header("Content-Length: 0");
header("Content-Type: text/plain");
} else if($_SERVER['REQUEST_METHOD'] == "POST") {
echo "Checking case1:\n";
echo "<br/>";
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
echo "<br/>";
echo "Checking case2:\n";
echo "<br/>";
var_dump($_POST);
}
React side code:
axios.post(
'https://xx.xx.com/index2.php',
{
member: id
},
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
withCredentials: true
}
)
PHP server is running on CloudFlare.
I wonder if this is related with Cloudflare's cache process or not.
I hope any helps, Thank you in advance.
Use headers as below
It works for me on PHP
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
}
while sending from axios you need to change headers
headers: {
'Content-Type': 'multipart/form-data,multipart/form-data',
'Access-Control-Allow-Origin': '*'
}
Related
I'm trying to get a data from php in my local server. from godot side it just works fine I can download an image. but when I'm trying to make a connection to a php I always get a HTTP error 405.
I've setup my godot and everything, and this is my code.
get_data.php
<?php
$item_db = file_get_contents("item_db.json");
if (isset($_SERVER['HTTP_ORIGIN'])){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Max-Age: 60");
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS"){
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Authorization,
Content-Type, Accept, Origin, cache-control");
http_response_code(200);
die;
}
}
if ($_SERVER['REQUEST_METHOD'] !== "POST"){
http_response_code(405);
die;
}
switch ($_REQUEST['command']){
case "add":
echo "add item";
break;
case "edit":
echo "edit item";
break;
}
?>
gdscript
$HTTPRequest.request("http://localhost/get_data.php",
["Content-Type: application/x-www-form-urlencoded",
"Cache-Control: max-age=0"],
false,
HTTPClient.METHOD_POST,
"command=edit"
)
Recently i did a site for a client. After receiving it the client sent the site for acunetix security check, which brought back this alert.
----acunetix alert---
`Access-Control-Allow-Origin: https://www.example.com
Access-Control-Allow-Credentials: true
Any origin is accepted (arbitrary Origin header values are reflected in Access-Control-
Allow-Origin response headers). For the WordPress /wp-json/ endpoint, this may be
the intended behavior and requires manual review. For further information, please
refer to the WordPress REST API Handbook linked in the "References" section below.`
--- the end of acunetix alert ---
i finally found where this is located - in rest-api.php
function rest_send_cors_headers( $value ) {
$origin = get_http_origin();
if ( $origin ) {
// Requests from file:// and data: URLs send "Origin: null".
if ( 'null' !== $origin ) {
$origin = esc_url_raw( $origin );
}
header( 'Access-Control-Allow-Origin: ' . $origin );
header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Vary: Origin', false );
} elseif ( ! headers_sent() && 'GET' === $_SERVER['REQUEST_METHOD'] && ! is_user_logged_in() ) {
header( 'Vary: Origin', false );
}
return $value;
}
Can anyone let me know what should i do in this case? How do i fix is or i just should let it be how it is done by wordpress.
thank you so much in advance.
see
function cors(){
if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$origin = $_SERVER['HTTP_ORIGIN'];
} else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
$origin = $_SERVER['HTTP_REFERER'];
} else {
$origin = $_SERVER['REMOTE_ADDR'];
}
$allowed_domains = array(
'http://localhost:4200',
'https://x.ir',
'https://www.x.ir',
);
if (in_array($origin, $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 3600");
header('content-type: application/json; charset=utf-8');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header("HTTP/1.1 200 OK CORS");
die();
}
}
I added the following to header:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With");
But I can still send any type of request, how I can make sure only POST is accepted?
You can check the method in your api by:
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod !== 'POST') {
http_response_code(400);
echo "Only POST method is allowed";
}
I have a javascript code to get username from a php file. The javascript code is not in the same domain, so it is cross-domain. In this case, domain1.com want to retrieve user information from domain2.com by using XMLHttpRequest. Here is the code
var http = new XMLHttpRequest();
http.open("POST", linkbased+'/username/', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("username").innerHTML = http.responseText;
}
}
http.send(data);
Here is my php file code
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
echo $_COOKIE['username'];
?>
If I access the php code directly, it will show the username. However, if I access it via XMLHttpRequest. It won't read the username. Is there something part am I missing?
From MDN
Credentialed requests
Credentialed Access Control Requests – that is, requests that are
accompanied by Cookies or HTTP Authentication information (and which
expect Cookies to be sent with responses) – can be either Simple or
Preflighted, depending on the request methods used.
In a Simple Request scenario, the request will be sent with Cookies
(e.g. if the withCredentials flag is set on XMLHttpRequest). If the
server responds with Access-Control-Allow-Credentials: true attached
to the credentialed response, then the response is accepted by the
client and exposed to web content. In a Preflighted Request, the
server can respond with Access-Control-Allow-Credentials: true to the
OPTIONS request.
So you might need to alter your code - the below is not tested however
var http = new XMLHttpRequest();
http.withCredentials = true;
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("username").innerHTML = http.responseText;
}
}
http.open("POST", linkbased+'/username/', true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send( data );
if( $_SERVER['REQUEST_METHOD'] == "POST" ) {
if( $_SERVER['HTTP_ORIGIN'] == 'http://domain1.com' ){
header('Access-Control-Allow-Origin: http://domain1.com');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: text/plain');
echo array_key_exists( 'username', $_COOKIE ) ? $_COOKIE['username'] : 'username not set';
} else {
header('HTTP/1.1 403 Access Forbidden',true,403);
header('Content-Type: text/plain');
echo "Sorry, you are not allowed to make such a request";
}
}
I am trying to implement CORS using php using the following code
//will add domains in this array
$allowedOrigins = array();
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != '') {
foreach ($allowedOrigins as $allowedOrigin) {
if (preg_match('#' . $allowedOrigin . '#', $_SERVER['HTTP_ORIGIN'])) {
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
}
}
$_SERVER['HTTP_ORIGIN'] returns nothing (empty string)
Is there any alternative for HTTP_ORIGIN ?
OR am I doing anything wrong ?