0

我有用于缩短 URL 的 PHP 代码。我想将它与 CodeIgniter 集成。我怎样才能做到这一点?
我有 3 页:index.phppage.php以及一个.htaccess文件和一个数据库备份文件。

index.php

<?php
mysql_connect("localhost","root","");
mysql_select_db("test");

$url=$_GET['url'];
$url_details=mysql_fetch_array(mysql_query("select * from tinyurls where shorturl like ('".$url."')"));
if(!empty($url_details)){
    header("location: ".$url_details['actualurl']);
}else{
    echo '<h2 style="color:red">Error 404: Page not found</h2>';
}
?>


page.php

<?php
if(isset($_POST['url'])){
mysql_connect("localhost","root","");
mysql_select_db("test");

    $exist=mysql_fetch_array(mysql_query("select * from tinyurls where actualurl='".$_POST['url']."'"));
    if(empty($exist))
    {
        function get_random_word($length=6){
            $chars='abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $word="";
            for($i=0;$i<$length;$i++){
                $word.=substr($chars,rand(1,strlen($chars)),1);
            }

            $isexist=mysql_fetch_array(mysql_query("select id from tinyurls where shorturl like ('".$word."')"));
            if(empty($isexist)){
                return $word;
            }else{
                return "";
            }
        }

        $tiny_word="";
        while($tiny_word==""){  
            $tiny_word=get_random_word();
        }
        mysql_query("insert into tinyurls set shorturl='".$tiny_word."', actualurl='".$_POST['url']."'");
    }else{
        $tiny_word=$exist['shorturl'];
    }
    echo "TinyURL: http://".$_SERVER['SERVER_NAME']."/tinyurl/".$tiny_word."<br/><br/>";
}
?>
<html>
    <head><title>Shorten URL</title></head>
    <body>
        <form method="post" action="">
            Enter the URL:<br/>
            <input type="text" name="url" style="padding:5px;width:500px"/><br/><br/>
            <input type="submit" style="padding:5px" value="Shorten URL">
        </form>
    </body>
</html>

.htaccess文件

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^p\/(.*)$ page.php?q=$1 [L]
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

如何将它与 CodeIgniter 集成?

4

1 回答 1

0

当我将它与 codeigniter 集成时,控制器会转到我网站的主页而不是原始 url

在您的代码中,您只是echo在输入 URL 而不是重定向它:

header('Location: http://' . $_SERVER['SERVER_NAME'] . '/tinyurl/' . $tiny_word);
于 2012-01-05T10:35:12.713 回答