Encountered error: Trying to get Json data using PHP on cPanel server setup
P粉896751037
2023-08-13 19:44:52
<p>I have an index.html file containing javascript: </p>
<pre class="brush:php;toolbar:false;">async function fetchCelebritiesData() {
try {
const response = await fetch('/data.php');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
return [];
}
}</pre>
<p>The PHP file connects the data to the application and gets the data from the names.json file. </p>
<pre class="brush:php;toolbar:false;"><?php
// Check if the request comes from an allowed domain
$allowedOrigins = array("example.com", "www.example.com");
$origin = $_SERVER['HTTP_ORIGIN'] ?? ''; // Get HTTP_ORIGIN from the request
if (in_array($origin, $allowedOrigins)) {
header("Access-Control-Allow-Origin: $origin");
} else {
header("HTTP/1.1 403 Forbidden");
exit;
}
//Read and output JSON data
$data = file_get_contents("data.json");
header("Content-Type: application/json");
echo $data;
?></pre>
<p>This setting gives me an error in the console with the following error message: </p>
<pre class="brush:php;toolbar:false;">ET https://example.com.com/data.php 403
fetchCelebritiesData @ (index):291
(anonymous) @ (index):375
load (async)
(anonymous) @ (index):373
(index):295 Error fetching data: SyntaxError: Unexpected end of JSON input
at fetchCelebritiesData ((index):292:33)
at async (index):375:30
fetchCelebritiesData @ (index):295
await in fetchCelebritiesData (async)
(anonymous) @ (index):375
load (async)
(anonymous) @ (index):373</pre>
<p>Need help understanding possible issues. I've checked the permissions on the PHP and JSON files and folders and everything looks fine. --6 4 4--</p>
<p>A log was generated showing a recurrence of this error. </p>
<p><code>[11-Aug-2023 09:08:58 UTC] PHP Notice: Undefined index: HTTP_ORIGIN in /home/pixellic/public_html/web-applications/celebrities-age-finder/get_secure_data.php on line 4</code></p>
<p>I am new to coding. </p>
<p>Thank you. </p>
<p>I try to get json data safely using php file. </p>
<p>But I got a 403 error. </p>
There will be no
As you pointed out, your code causes a 403 error because this test fails (becauseHTTP_ORIGIN# in
$_SERVER unless you send an Originheader in the request (see
Manual) ##element. But you can use
REMOTE_HOSTinstead:
$origin
Please note that you can useis always
''):
REMOTE_HOST
as a fallback in cases where it is possible to send the
Originheader: