« Return

PHP and jQuery create your own URL shortner

demo


<?php        
    // ===========================================
    // File 1: shortner.php
    
    /* MySQL table structure
    ==============================================
    CREATE TABLE `shorturls` (
      `shorturl` char(5) NOT NULL,
      `url` varchar(255) NOT NULL,
      `date` datetime NOT NULL,
      KEY `shorturl` (`shorturl`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
    ==============================================    
    */
    
    if (filter_has_var(INPUT_POST, 'submit')) {
    $url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL); // validate url ( avoid trouble )
      if ( $url ) { // if validate 
          
          // connect to mysql database
          require_once($_SERVER['DOCUMENT_ROOT'] . '/connect.php');

          function rand_shorturl() {
            global $dbh;
            
            $charset = "abcdefghijkmnpqrstuvwxyz0123456789";
            for ($i = 0; $i < 4; $i++) {
              $shorturl .= $charset[mt_rand(0, strlen($charset) - 1)];
            }
            // make sure the random assigned value is not a dup ( chance are one in a billion, correct? but let’s make it right )
            $stmt = $dbh->prepare("SELECT shorturl from shorturls WHERE shorturl = :shorturl"); // prepare
            $stmt->execute(array(':shorturl' => $shorturl)); // bind and execute
            $result = $stmt->fetch(PDO::FETCH_ASSOC); // fetch
            if ($stmt->rowCount()) { // if true, let’s get another random value              
            rand_shorturl(); // recursive
            } else { return $shorturl; }
          }
          
          $shorturl = rand_shorturl(); // create a short url          
          
          $stmt = $dbh->prepare("INSERT INTO shorturls VALUES (:shorturl, :url, NOW())"); // prepare
          $stmt->execute(array(':shorturl' => $shorturl, ':url' => $url)); // bind and execute
          
          if ($stmt->rowCount()) { 
          $display = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $shorturl;
          }
          else { $display = 'an error has occurred, please give it another try'; }
          
          $dbh = null; // close
      }
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    
    <title>BCDC.US™ - Website Strategy and Programming</title>
    <link rel="shortcut icon" href="/images/favicon.ico" type="image/ico" />
    
    <style type="text/css" media="screen">
    body { margin:30px; }
    input[type=text] { border:1px solid black; text-decoration:none; padding:10px; width:600px; height:auto; margin-bottom:10px; background:url(/images/graphic_45lines_light.png); }
    input[type=text].complete { border:3px solid #C4DF31; padding:8px; }
    </style>
        
    <script type="text/javascript" src="http://www.google.com/jsapi"></script> 
    <script type="text/javascript">
    google.load('jquery', '1.4');
    </script>
    
    <script type="text/javascript" charset="utf-8">
      $(document).ready(function() {
             
        var display = $(':input').not(':submit');
        var default_text = 'paste here your long url';
        
        if ( display.val() != default_text ) { 
          display.attr({ readonly: 'readonly' });
          display.addClass('complete');
          $(':submit').val('reload to short another url');
          
          $(':submit').click(function(event) {
            event.preventDefault();
            window.location = '<?php echo basename(__FILE__); ?>';
          });          
        }

        display.focus(function() {          
          if ( $(this).val() == default_text ) { 
            $(this).val('');
          }
        });
      });
    </script>
    
</head>
<body>
    <form action="<?php echo basename(__FILE__); ?>" method="post" accept-charset="utf-8">
      <div>
        <input class="<?php if ( !$display ) { echo 'ready'; } ?>" type="text" name="url" tabindex="1" value="<?php if ( $display ) { echo $display; } else { echo 'paste here your long url'; } ?>"/><br />
        <input type="submit" name="submit" tabindex="2" value="make it short!" />
      </div>  
    </form>
</body>
</html>

    // ===========================================
    // File 2: shorturl.php
    
<?php
    $shorturl = $_SERVER['REQUEST_URI'];
    $shorturl = str_replace('/', '', $shorturl); # make sure to remove forward slahes if any
    
    # connect to mysql database
    require_once($_SERVER['DOCUMENT_ROOT'] . '/connect.php');

    $stmt = $dbh->prepare("SELECT url from shorturls WHERE shorturl = :shorturl"); // prepare
    $stmt->execute(array(':shorturl' => $shorturl)); // bind and execute
    $result = $stmt->fetch(PDO::FETCH_ASSOC); // fetch
    if ($stmt->rowCount()) { // if true, let’s get another random value   
    $dbh = null; // close
    header('Location:' . $result['url']); // good bye
    } else { // rowCount returned false ( not a short url, so chances are it’s a 404 )
    header('Location: /message.php?message=404'); // load 404 custom page
    }
?>