search

Home  >  Q&A  >  body text

Encountered error: Trying to get Json data using PHP on cPanel server setup

<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>
P粉896751037P粉896751037519 days ago443

reply all(1)I'll reply

  • P粉124070451

    P粉1240704512023-08-14 14:32:25

    There will be no HTTP_ORIGIN# in $_SERVER unless you send an Origin header in the request (see Manual) ##element. But you can use REMOTE_HOST instead:

    $origin = $_SERVER['REMOTE_HOST'] ?? '';
    

    As you pointed out, your code causes a 403 error because this test fails (because

    $origin is always ''):

    if (in_array($origin, $allowedOrigins)) {
    

    Please note that you can use

    REMOTE_HOST as a fallback in cases where it is possible to send the Origin header:

    $origin = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['REMOTE_HOST'] ?? '';
    

    reply
    0
  • Cancelreply