0

I would like to make a call to the external API before the page is loaded on my WordPress website. It looks somewhat like this:

$si = session_id();
$res = @file_get_contents("https://my-api.com/si_check?si={$si}", false);
if ($res != 'ok')
    exit('not ok');

It doesn't have to be php but what matters is it should send the session id to the api and if the api responds with anything but "ok" it should stop the page from loading (or maybe redirect somewhere).

I have tried adding this code to functions.php, index.php and wp-config.php based on what other people were recommending, but only functions.php runs consistently every time the page is loaded, but it fails when I open a page not in the browser, but in code, for example:

import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'}

res = requests.get('https://my-website.com', headers=headers)
print(res.text)

It is especially important since obviously this code is meant to keep some users out of the website, and bots are a primary target, but the code above completely bypasses the api call and gets the whole html page. Which file can I add this check to so that It will run 100% of the time?

1 Answer 1

0

The correct way to do this would be to wrap your custom functionality in a function and hook it to init.

2
  • I assumed that this code (with the hook) should be added to wp-settings.php. It seems like it runs every time, but the bots still get through no problem. Is there a way to run the code even before WordPress loads? But I still need a way to get the session id. Commented Jul 28 at 15:59
  • Absolutely not. Never edit core files, the only places you should be adding code are your (custom) theme's functions.php or a site-specific plugin. Anything added to core files or a theme or plugin from the WP repo will be overwritten by updates. The init hook fires once WordPress is fully loaded but before any headers are sent, so the hook will fire every time. Bots rarely maintain a session, so you'll have to resort to something more sophisticated to detect them. Then you run into the issue of bots that you do want to be able to access your site, like search engine spiders.
    – Chris Cox
    Commented Jul 28 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.