PHP while循环对URL Shortner脚本无法正常工作

时间:2014-05-02 21:17:29

标签: php url-shortener

我正在尝试创建URL Shortner网站,我的问题是PHP while循环不能正常工作。问题是我允许用户一次输入五个链接以缩短URL。我在我的localhost中测试它,我遇到了这个问题。如果我添加单个链接,那么它可以正常工作。但是,如果我添加多个全部五个链接,那么它无法正常工作。我的代码是

add_url.php

<form method="post" enctype="multipart/form-data" style="padding:10px;" autocomplete="off" >
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." required />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="hidden" name="cool" value="<?php echo $_SESSION['CSRF_TOKEN'];?>" />
     <button style="padding:5px; margin:5px; float:right;" type="submit" class="btn btn-small btn-success" name="shorten" value="sortn">Shorten</button>
     </form>
     <div id="msgDiv" style="padding:10px;">
     <?php


     if(isset($_POST['shorten']) AND ($_POST['shorten'] == 'sortn')){

         $post_links = $_POST;

         include 'usrShortenLink.php';
         Shorten::new_shorten_link($post_links);
         echo "<meta HTTP-EQUIV=\"REFRESH\" content=\"3; url=$site\">";

     }
     ?>
     </div>

我需要回显mets标签,因为如果用户将刷新页面,那么它将再次发布所有数据。和$ site = localhost我已将其设置为将其用于其他功能。

usrShortenLink.php代码

<?php

class Shorten{

    public static function check_archived_link($link, $user_email){

        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        $check_archived_query = "SELECT * FROM `url_table` WHERE BINARY (`url` = '$link' AND `u_email` = '$user_email' AND `archived` != '0')";

        if($result = $db->query($check_archived_query)){
            if($result AND $db->affected_rows > 0){

                $update_archived_link = "UPDATE `url_table` SET `archived` = '0' WHERE BINARY (`url` = '$link' AND `u_email` = '$user_email')";

                if(($db->query($update_archived_link)) AND ($db->affected_rows > 0)){
                    throw new Exception('Your entered link is already in use with your account and it was deactivated by you. We\'ve activated your link.<br>');
                    return true;
                } else {
                    throw new Exception('Your entered link is already in use with your account and it was deactivated by you. We tried to activate the links but we got some error. Please try again.<br>');
                }

            }           
            else {
                self::check_link($link, $user_email);
            }
        }

        else {
            throw new Exception('We faced some unwanted errors. Please try once again.<br>');
        }

    }

    public static function check_link($link, $user_email){

        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        $check_query = "SELECT * FROM `url_table` WHERE BINARY (`url` = '$link' AND `u_email` = '$user_email')";

        if($result = $db->query($check_query)){
            if($result AND $db->affected_rows > 0){
                throw new Exception('Your entered link is already in use with your account. We don\'t do duplicates.<br>');
            } 

        }

        else {
            throw new Exception('We faced some unwanted errors. Please try once again.<br>');
        }

    }

    public static function check_details_from_db($link, $user_email){
        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        if(!filter_var($link, FILTER_VALIDATE_URL)){
            throw new Exception('Entered link is not in valid format. Please check it.<br>');
        } else 

            if(strlen($link) > 1000){
                throw new Exception('Entered link is too long to process.<br>');
            } else 

                //check links are in database and archived or not
                self::check_archived_link($link, $user_email) ;

    }

    public static function gen_code(){
        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        //generate random code for shorten url

        $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
        $len = 6;
        $numrows = 1;
        $code = empty($code);

        while($numrows != 0){
            for($i = 0; $i <= $len; $i++){
                $rand = rand()% strlen($charset);
                $temp = substr($charset, $rand, 1);
                $code .= $temp;
            }

            $find = $db->query("SELECT `id` FROM `url_table` WHERE BINARY `code` = '$code'");
            $numrows = $find->num_rows;
        }
        return $code;
    }

    public static function insert_link($link, $user_email, $blah){

        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        try {
            self::check_details_from_db($link, $user_email);
        } 
        catch(Exception $e) {
            echo '<b>Message:</b> ' .$e->getMessage();
        }

        if(empty($e)){

            $code = self::gen_code();
            if(strlen($code) > 7){
                $code = '';
                $code .= "";
                $code .= self::gen_code();


            }

            $ip = $_SESSION['ip'];
            $date = time();
            $site_name = $site;

            $hash_string = $user_email.'/'.$date.'/'.$ip.'/'.$code;
            $hash  = $blah->encode($hash_string);

            $insert_link_query = "INSERT INTO `url_table` (`url`, `site`, `code`, `u_email`, `create_time`, `ip`, `hash`, `archived`) 
                                                                  VALUES ('$link', '$site_name', '$code', '$user_email', '$date', '$ip', '$hash', '0')";


            if($result = $db->query($insert_link_query)){
                if($result AND $db->affected_rows > 0){
                    echo '<b>Message:</b> Successful! Check your all links at right side. You can manage all links from the same table.<br>';
                    $refresh_url = $site.'user/v1/home';                        
                } else {
                    echo '<b>Message:</b> We got an error. Please try again.<br>';
                }
            } else {
                echo '<b>Message:</b> Ooopps! We got an error. Please try again.<br>';
            }  
        }


    }

    public static function new_shorten_link($post_links){
        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        $cool = $db->real_escape_string(htmlentities($post_links['cool']));
        $user_email = $_SESSION['email'];
        include $_SERVER['DOCUMENT_ROOT'].'/encryption.php';
        $blah = new Encryption; 
        foreach($post_links['link'] as $links){
            $link = $db->real_escape_string(htmlentities($links));

            if(!empty($link)){
                $code = '';
                self::insert_link($link, $user_email, $blah);
            }
        }   
    }

}

?>

现在,问题是如果我添加单个链接,那么它将生成缩短的代码,其字符串长度将为7个字符。但是,如果我添加多个链接,那么我会增加缩短代码的字符串长度。我只允许在code列的数据库中插入20个字符。所以它插入最多20个字符,但对我来说仍然是一个问题。我想只生成7个字符。所以有人可以帮我这个吗?

以下是我在测试脚本中添加的最后几个测试链接。

1.2 / 257986542 ---- locho / 1tqjoV8f
1.2 / 2558351 ---- locho / 15-FS1k7
1.2 / 258645312 ---- locho / 11k7yXwxeTIZWPUpCL6R&lt; ----第二个链接的副本然后                                                                 然后是循环生成的代码。

1.2 / 2576531 ---- locho / 1WPUpCL6RiHgh0D
1.2 / 254886 ---- locho / 1h0DsJGz
1.2 / 25654 ---- locho / 1fAlObMN
1.2 / 256845 ---- locho / 13KnctqjoV8fAlObMNu9
1.2 / 257865 ---- locho / 1AlObMNu9Yda5-F
1.2 / 25879 ---- locho / 1yXwxeTI
1.2 / 2578 ---- locho / 11k7yXwxeTIZWPU&lt; ----第二个链接问题 1.2 / 252 ---- locho / 1JGzE_mvQB4r23K&lt; ----第1链接的副本 1.2 / 253 ---- locho / 1_mvQB4r 1.2 / 254 ---- locho / 1ctqjoV8
1.2 / 255 ---- locho / 1a5-FS1k
1.2 / 256 ---- locho / 1S1k7yXw
1.2 / 25 ---- locho / 1JGzE_mv&lt; ---- 1st links

您可以在生成的结果中找到一些类似的代码。

1 个答案:

答案 0 :(得分:1)

public static function gen_code(){
            include $_SERVER['DOCUMENT_ROOT'].'/core/db_config_inc.php';

                    //generate random code for shorten url

                    $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
                    $len = 6;
                    $numrows = 1;
                    $code = '';

                    while($numrows != 0 AND strlen($code) < 8 ){
                        for($i = 0; $i <= $len; $i++){
                            $rand = rand()% strlen($charset);
                            $temp = substr($charset, $rand, 1);
                            $code .= $temp;
                        }

                        $find = $db->query("SELECT `id` FROM `url_table` WHERE BINARY `code` = '$code'");
                        $numrows = $find->num_rows;
                    }
        return $code;
    }

试试这个......这会对你有所帮助......;)