How do sites such as Stack Overflow submit forms using action="/questions/ask/submit"
?
I would've thought mod_rewrite
would lose the $_POST
vars?
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L]
index.php
$q = explode("/", $_SERVER['REQUEST_URI']);
if($q[1]!=""){
switch($q[1]){
case "test":
include("test.php");
break;
...
test.php
<?php
if(isset($_POST["submitButton"])){
echo "Submitted";
}
else{
echo "Not submitted";
}
?>
<form method="post" action="/test/submit">
<input type="submit" name="submitButton">
</form>
If I remove action="/test/submit"
If my URL is /test
then it returns Not submitted
when I click the button.
If my URL is /test.php
then it returns Submitted
when I click the button.
Update
For the time being, I'm using the following.
index.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$q = explode("/", $_POST["url"]);
}
else{
$q = explode("/", $_SERVER['REQUEST_URI']);
}
...
test.php
<form method="post" action="/">
<input type="hidden" name="url" value="/test">
...
This allows my test.php to receive the post vars.
If there are no errors by the user, I use header("Location: test/success");
If there are errors, the URL will have to be /
which isn't ideal.
Update/resolution
The problem may be with Apache 2.4. The fix was to add this line to index.php:
parse_str(file_get_contents("php://input"),$_POST);
With this method, there's no need for any action="..."
(this will successfully POST to itself, even if the URL is a slug).