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 = '
$.ajax({
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 : 😉
<?php
echo "abcd";
?>
When I open a WordPress page (mytestpage) containing the shortcode, WordPress builds and runs the Javascript in an HTML page http://www.mywebsite.com/mytestpage/, and I get in the browser console :
status=error,xhr=<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /wp-content/plugins/foobar/myPHPFunction.php
on this server.</p>
</body></html>
,errth=Forbidden
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: "http://www.mywebsite.com/myPHPFunction.php",
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 https://enable-cors.org/server_apache.html 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
Leave an answer