0

I have a JavaScript Code with a variable "dictionary" with JSON content. I need a function (saveData()) which sends the Data to the PHP back-end to save it in the database. That's my current code:

async function saveData() {
    try {
        let id = getCookie('hhb-id') | 0;
        const response = await fetch(`api.php?id=${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(dictionary)
        });

        if (!response.ok) {
            let responseData = await response.json();
            console.error('An error occurred while saving the data (Request): ', responseData);
        }
        else {
            console.log('Data saved successfully: ', await response.json());
        }
    } catch (error) {
        console.error('An error occurred while saving the data (Catch): ', error);
    }
}

My problem is that here everyone can send data to the back-end and not only the JavaScript function. How have I to change my code to do that?

That's my PHP code (api.php):

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_GET['id']) and $_GET['id'] > 0) {
        try {
            $data = json_decode(file_get_contents('php://input'));

            // save data to database
            ...
        } catch (Exception $e) {
            ...
        }
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kugelfisch
  • 19
  • 2
  • 1
    You can't prevent that. – Barmar Jun 26 '23 at 20:11
  • 2
    You should require the application to login, and use a session variable to tell whether the request is from a logged in user. – Barmar Jun 26 '23 at 20:12
  • 1
    Preventing users from *making* requests is the wrong approach. Assume anybody can make any request they want. What you control is how your server-side code *handles* that request, to include authenticating the user and authorizing the request they are making. – David Jun 26 '23 at 20:14

1 Answers1

0

Use authorization token in headers by simply authenticating users before accepting response

Worldest
  • 11
  • 4
  • 2
    "which is only know to you" — which then have to be published in the *public facing* JavaScript! – Quentin Jun 26 '23 at 20:23
  • 1
    This answer makes no sense. If you send a header from the client, it will be visible to the client. The only correct answer here is server side authentication and validation. – GrumpyCrouton Jun 26 '23 at 21:11
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 28 '23 at 05:08