Reducción de enlaces sin grasa (F3)



No es una pena acortar enlaces a 13, ¿verdad? Un principiante, y no solo un principiante, debe intentar escribir su propio Link Tamer mientras aprende un nuevo marco. Que es lo que hice. ¿Qué puedo decir? El quinto arranque, un marco sin grasa y un pedazo del alma.



Aquí está el código . Para lectores como yo;)



Un marco, ¿verdad?



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 , , .
  • También puede hacer estadísticas normales y mostrarlas yendo a / @ code / stats
  • No permitir la creación de enlaces al servicio de acortamiento en sí, crear una lista de recursos "protegidos" del acortamiento
  • Recomiendo encarecidamente que incluso en un asunto tan pequeño para realizar la validación de entrada en el lado del servidor, con la salida de los errores correspondientes, no debe confiar en agregar el atributo requerido y el tipo = "url" en el campo de entrada

    Camarada Roja


  • Sugerir en comentarios ...



    En contacto)






All Articles