redirect to different URL with .htacess or PHP [cl

2020-05-10 03:40发布

I have a form at index.php that takes in user input, it the includes and sends the user input to another php file for processing.

Here is the code of index.php:

<?php
if(isset($_GET['q'])){
    include_once "form.php";
    exit(0);
}
?>
<!Doctype HTML>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Search</title>
    </head>
    <body>
        <form method="get">
         <input type="text" name="q" />
    </form>
    </body>
 </html>

When one submits the form, by hitting enter when the text-input is focused, it goes to

http://mysite.com/?q=textUserEntered (if just the domain was visited before) or http://mysite.com/index.php?q=textUserEntered (if index.php is visited before)

How can I get it to go to http://mysite.com/form?q=textUserEntered or http://mysite.com/index.php/form?q=textUserEntered while still passing the form data to form.php

I would prefer a solution with PHP, but if the only way to do this would be with .htacess, then please share.

I tried this in the beginning index.php and form.php, it navigates to the URL but doesn't pass the data to form.php and navigates to the 404 error page.

if(!empty($_GET['q']))
{
    header("Location: form?q=".rawurlencode($_GET['q']));
    exit;
}

I can't use the action attribute because adding form.php to the value of the action attribute would make the URL http://mysite.com/form.php?q=userEnteredText not http://mysite.com/form?q=userEnteredText

标签: php .htaccess
1条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-05-10 04:01

Just tell the form where to send the data, you don't need to redirect:

<form method="get" action="form.php">
查看更多
登录 后发表回答