Question

I am trying to make URL Shortner website and my problem is that PHP while loop is not working properly. Problem is that I am allowing users to enter five links at a time to make shorten URL. I was testing it in my localhost and I got this issue. If I add single link then it works properly. But if I add multiple all five links then its not working properly. My codes are

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>

I need to echo mets tag because if user will refresh the page then it will post all data once again. and $site = localhost which I've set to use it for other functions.

usrShortenLink.php codes are

<?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);
            }
        }   
    }

}

?>

Now, the problem is that if I add single link then it will generate shorten code and its string length will be 7 characters. But if I add multiple links then I get increased string length of shorten code. I've allowed only 20 characters to be inserted in database in code column. SO it is inserting max 20 characters but still its an issue for me. I want only 7 characters to generate. So can anyone help me with this?

Here are my last few test links which I've added to test script.

1.2/257986542 ---- locho/1tqjoV8f
1.2/2558351 ---- locho/15-FS1k7
1.2/258645312 ---- locho/11k7yXwxeTIZWPUpCL6R <---- second link's copy and then followed by code generated by loop.

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 <---- second links with issue 1.2/252 ---- locho/1JGzE_mvQB4r23K <---- copy of 1st links 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 <---- 1st links

You can find some similar codes in generated results.

Was it helpful?

Solution

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;
    }

Try this... this will help you... ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top