How to avoid the 403 Forbidden error in a WP Plugin with Ajax and PHP


I’ve stumbled on the “403 Forbidden error” for which many explanations/solutions can be found in many places, most of them on Stack.
However, I struggle for quite a while for solving this error in my situation.
I asked that same question on the WordPress forum but got no answer..

I have a WordPress plugin, let’s call it “foobar”, that processes a shortcode.

My plugin’s php file, foobar.php, builds and returns at some point the Javascript code:

$myvariable = '
 url: "'.plugin_dir_url( __FILE__ ) .'myPHPFunction.php",
 '.type: "post",
 success: function(response) { console.log("return from myPHPFunction.php:"+response); },
 error: function(xhr,status,error) { console.log("status="+status+",xhr="+xhr+",errth="+error);}

return $myvariable;

The reason why I want to call php from the browser with an ajax call is that I need that its content is run asynchronously when the page is displayed.

The myPHPFunction.php file is in the same directory as the plugin’s.

myPHPFunction.php is very powerful, it makes : 😉

    echo "abcd";

When I open a WordPress page (mytestpage) containing the shortcode, WordPress builds and runs the Javascript in an HTML page, and I get in the browser console :

status=error,xhr=<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<title>403 Forbidden</title>
<p>You don't have permission to access /wp-content/plugins/foobar/myPHPFunction.php
on this server.</p>

Curiously, this is what happens locally on my development server (I use MAMP 5.7). On the production site at my provider’s, it works.
But I need having it running in development…

If I move myPHPFunction.php to the root of my website, and update my code accordingly:

 url: "",

it works.. : abcd is returned in the console…

So very probably it comes from the fact that the HTML page generated by WordPress and the PHP file are not in the same domain.
As myPHPFunction.php must be delivered with my plugin, there is no way to put it outside the plugin’s directory.

Hence I must solve the cross-domain call.

I think that solving this on the server by configuration (.htaccess) is not safe.
In the case of a plugin, no guarantee that my plugin users won’t experience that error in their deployment context.
And many users can’t/don’t know how to operate on their apache server, especially if it’s managed by a provider (and possibly mutualized).
Besides it’s probably not straightforward : I tried myself without success.

The other solution seems to try having headers returned by the server :

That didn’t work either..
I tried adding those lines in either of my php files, without success…

I now run out of ideas…

Any help appreciated…

Thanks a lot

, , humhum 4 years 2020-03-04T19:50:59-05:00 0 Answers 154 views 0

Leave an answer