Shrinking links without fat (F3)



It's not a shame to shorten links at 13, right? A beginner, and not only a beginner, should try to write your own Link Tamer while learning a new framework. Which is what I did. What can I say - the fifth bootstrap, a fat-free framework and a piece of the soul.



Here is the code . For readers like me;)



A framework, right?



Laravel β€” 65- FatFreeFramework. Python Flask, , - :



#  
@app.route('/')
def hello_world():
    return 'Hello, World!'





//  
$f3->route('GET /',
    function() {
        echo 'Hello, world!';
    }
);


, . .zip ., , . index.php /ui.



β€” ui , β€” , URL.



"":



<?php
//: index.php

// Kickstart the framework
$f3=require('lib/base.php');
$f3->set('DEBUG', 1);
if ((float)PCRE_VERSION<8.0)
    trigger_error('PCRE version is out of date');
$f3->config('config.ini');

//     

$f3->run();


, . !



[ XAMPP Windows VS Code



Homepage



. , ?



//: index.php

$f3->route('GET /',
    function($f3) { //   F3    
                $view = new View; //  
        echo $view->render('home.htm'); // 
    }
);


. v5 alpfa.



ui,



<!-- : ui/home.htm -->

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="<?php echo $ENCODING; ?>" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> (),  ()!</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
    </head>
    <body class="text-center bg-dark text-light"> <!--   ;) -->

        <!--  -->
        <nav class="m-2">
            <ul class="nav nav-pills justify-content-center">
                <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="#"></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">  </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="https://nikonovs.ru"></a>
                </li>
            </ul>
        </nav>

        <div class="container">
        <h1>   .</h1>

        <!--    POST-  /newLink -->
        <form class="mt-5 mb-3" action="/newLink/" method="POST">
            <div class="row justify-content-center">
                <div class="col-auto">
                <label for="inputLink" class="col-form-label"> :</label>
                </div>
                <div class="col-auto">
                <input required placeholder="https://" type="url" name="link" id="inputLink" class="form-control mb-1" aria-describedby="inputLink">
                </div>
                <div class="col-auto">
                <button type="submit" class="btn btn-outline-primary">!</button>
                </div>
            </div>
        </form>

        <!--  -->
        <p class="text-left m-auto mb-5" style="max-width: 30rem;">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Omnis illum molestiae hic fugiat molestias nemo, architecto beatae repellat ullam exercitationem non ab, necessitatibus maxime quod iure ipsa quam quos! Reprehenderit. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Necessitatibus eos sapiente voluptates veniam sequi delectus totam tenetur praesentium obcaecati. Repudiandae quisquam, ipsa ullam corrupti molestiae minima optio nihil est modi?</p>

        <footer class="m-2">  <img width="20" height="20" src="https://image.flaticon.com/icons/svg/833/833472.svg" alt="">, <a href="https://v5.getbootstrap.com/"> Bootstrap'</a>     <a href="https://fatfreeframework.com/"> </a></footer>
        </div>
    </body>
</html>


, . POST- , .

().





β€” MySQL. PhpMyAdmin, "linker", SQL:



SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE IF NOT EXISTS `links` (
  `code` varchar(4) NOT NULL,
  `link` varchar(1000) NOT NULL,
  `hits` int(255) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `links`
  ADD UNIQUE KEY `code` (`code`);


3 :



  1. Code β€” 4 , , example.com/ABC1
  2. Link β€” .
  3. Hits β€” .


, .



<?php
//    
$db = new DB\SQL(
    'mysql:host=localhost;port=3306;dbname=linker',
    'root',
    ''
);

//      :

//     c   SQL-:
$f3->set('result', $db->exec('SELECT * FROM wherever')); 
//    ,  <?= $resul ? >

//    SQL Mapper:
$row = new DB\SQL\Mapper($db, 'links');

$row->load(array('link="https://habrahabr.ru"')); //       ,    :
$row_value = $row->somerow; // 

//    :
$row->link = 'https://habr.com';
$row->save(); //  ,    

//        : https://a.nikonovs.ru/MPHR   ,    ,   .
?>


.





index'e, .



, (home.htm) β€” "newLink.htm".

( "" β€” ).

" ":



<?php
//:  ()

//   index'   
$f3->set('link', $shorted_link);
$view = new View;
echo $view->render('newLink.htm');
//    :
<?= $link ?>


newLink.html:



<!-- : newLink.htm -->

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="<?php echo $ENCODING; ?>" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> (),  ()!</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
    </head>
    <body class="text-center bg-dark text-light">
        <nav class="m-2">
            <ul class="nav nav-pills justify-content-center">
                <li class="nav-item">
                    <a class="nav-link" aria-current="page" href="/"></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">  </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="https://nikonovs.ru"></a>
                </li>
            </ul>
        </nav>

        <div class="container">
        <h1>   .</h1>

        <!--         -->
        <form class="mt-5 mb-3">
            <div class="row justify-content-center">
                <div class="col-auto">
                    <label for="inputLink" class="col-form-label">:</label>
                </div>
                <div class="col-auto">
                    <input disabled required type="url" name="link" id="inputLink" class="form-control disabled" aria-describedby="inputLink" value="<?= $link ?>">
                </div>
            </div>
            <p class="m-2 text-secondary">   : `<?= $hits ?>`</p>
        </form>

        <a href="/" class="mt-3 mb-5 btn btn-primary btn-lg">  </a>

        <footer class="m-2">  <img width="20" height="20" src="https://image.flaticon.com/icons/svg/833/833472.svg" alt="">, <a href="https://v5.getbootstrap.com/"> Bootstrap'</a>     <a href="https://fatfreeframework.com/"> </a></footer>
        </div>
    </body>
</html>


.



$f3->route('GET|POST /newLink', //    POST  GET
    function($f3) {

            $db = new DB\SQL( //      
                'mysql:host=localhost;port=3306;dbname=linker',
                'root',
                ''
            );

            //    :
            $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            function generate_string($input, $strength = 4) {
                $input_length = strlen($input);
                $random_string = '';
                for($i = 0; $i < $strength; $i++) {
                    $random_character = $input[mt_rand(0, $input_length - 1)];
                    $random_string .= $random_character;
                }

                return $random_string;
            }

            //   link -          . link - .
            $check = new DB\SQL\Mapper($db,'links');
            $check->load(array('link="'. $link .'"'));
            if ($check->dry()) {
                $g_code = generate_string($permitted_chars);
                $row = new DB\SQL\Mapper($db,'links');
                $row->reset();
                $row->code = $g_code;
                $row->link = $link;
                $row->save();
            } else {
                $g_code = $check->code; // link ,    
            }

            $short_link = 'https://'. $_SERVER['HTTP_HOST'] . '/' . $g_code; //  

            //  $_POST     $f3->get('POST'),    (,   ):  "link"   : 
            $link = $f3->get('POST.link');

            if ( !empty($f3->get('POST')) ) { // HTML,   POST  .

            $f3->set('link', $short_link);
            $f3->set('hits', $check->hits);
            $view = new View;
            echo $view->render('newLink.htm');

            } else { // -   
                $f3->$f3->reroute('/');
            }

        }
);


! , .





:



  1. URL
  2. Profit!


.



$f3->route('GET /@code', //   "@",    PARAMS
    function($f3) {

        //  $db
        $db = new DB\SQL(
            'mysql:host=localhost;port=3306;dbname=linker',
            'root',
            ''
        );

        $code = $f3->get('PARAMS.code'); // 

        $link = new DB\SQL\Mapper($db,'links'); 

        //      - ,     
        if ($link->load(array('code="'.$code.'"', 'link=?'))) {
            $link->hits++;
            $link->save();

            $f3->reroute($link->link);
        } else {
            $f3->reroute('/'); //     -    
        }
    }
);


, newLink, β€” code "newLink" ( , ), , .



$f3β†’run()!



!

, , .



(), , . !



  • , $g_code , , .
  • You can also make normal statistics and display it by going to / @ code / stats
  • Prohibit creating links to the shortening service itself, create a list of resources "protected" from shortening
  • I strongly recommend that even in such a small matter, do input validation on the server side, with the output of the corresponding errors, you should not rely on adding the required attribute and type = "url" to the input field

    RedComrade


  • Suggest in comments ...



    In touch)






All Articles