根据用户输入的关键字重定向

时间:2013-09-02 06:02:36

标签: php javascript mysql

我有一个页面,用户可以在其中输入他正在销售的内容并重定向到该页面。我知道mysql LIKE '%%' function,但我没有使用数据库。如果案例匹配,我只想重定向到该页面。怎么可能?是javascript还是php?

例如:如果用户输入“laptop”,那么他/她将被重定向到laptop.php(我有页面)。我怎样才能做到这一点?

表单结构:

 <form class="sellcont" action="" method="post">
     <input type="text" name="selling" >
<input type="submit" name="submit" value="Next" class="myButton">
 </form>


 <?php if(isset($_POST['submit'])){
 $sell = $_POST['selling'];
 if(!empty($_POST['selling'])){

//This is where I am lost. 

}


 }

3 个答案:

答案 0 :(得分:2)

评论后

如果输入良好,您可以使用php header重定向并检查输入($ _POST ['sell'])和in_array

$goodinput = array("laptop", "pc", "mac", "cellphone");

if(!empty($_POST['selling'])){

    if (in_array($_POST['selling'],$goodinput)){ //checks if user input is a  good input

       header('Location: http://www.yoururl.com/'.$_POST['selling'].'php');
       exit();

    } else {

       header('Location: http://www.yoururl.com/wedonthavethatpage.php');
       exit();

    }
}

<强>建议:

  • 您可以在数据库中存储类似的值并创建动态页面,而不是创建单个页面,例如:laptop.php

答案 1 :(得分:1)

PHP代码应该是这样的:

<?php if(isset($_POST['submit'])){
 $sell = $_POST['selling'];
 if(!empty($_POST['selling'])){
     header('location: ./'.$_POST['selling'].'.php');   
 }
 else {
     header('location: ./index.php');  //index.php is PHP files on which user enter selling item
  }  
}
?>

答案 2 :(得分:1)

您也可以使用此答案中的代码:

How can I check if a URL exists via PHP?

查看用户输入的内容是否可用。如果是,请执行重定向,否则,将其发送到备用页面。

E.g。

if(!empty($_POST['selling'])){
    $file = 'http://www.yourdomain.com/'.$_POST['selling'].'.php';
    $file_headers = @get_headers($file);
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
        $exists = false;
    }
    else {
        $exists = true;
    }

    if ($exists) {
        header(sprintf('Location: %s', $file);
    }
    else {
        header('Location: http://www.yourdomain.com/other_page.php');
    }
    exit();
}