Create shorter version of url in php

120 views Asked by At

I have an url like this :

http://domain.com/key1=00998833&key2=8666886&par3=testing&page=2

There are many parameters in the url, but I need to show a shorter version of url when the page is being displayed on Browser. To be more clear, I need the url to be something like: http://domain.com/link123456 or in a slightly different way.

Is there any way to do it ?

I searched a lot for but couldn't find any solution yet.

Thanks

3

There are 3 answers

2
Cortez Nix On

Put on your htaccess file:

RewriteRule   ^link123456/?$   index.php?key1=00998833&key2=8666886&par3=testing&page=2 [L,QSA]
0
Dennis van Schaik On

If you need all the vars, you can’t shorten them. What you can do is store the keys locally in a DB and put the ID of the row from the DB in the url.

Then when the url is loaded, you just check the DB for the row with the vars.

0
ʰᵈˑ On

Actually the urls will be generated from shortcode. Parameter settings will vary for each url - Comment Source

This makes me believe that you're wanting a database to store short urls against long urls.

You can use index.php as your router, and store the short URLs in the database against the long URLs.

Create a .htaccess rewrite rule

RewriteEngine On
RewriteRule ^(.*)$ index.php?q=$1 [NC,QSA]

This will make http://example.com/short123456 "redirect" to http://example.com/index.php?q=short123456.

Create your database (assuming MySQL)

CREATE TABLE `urls` (
  `short_url` varchar(50) NOT NULL,
  `long_url` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

We'll be storing our short and long urls here.

Create your router

In the .htaccess rewrite rule, we're going to index.php. So, within your index.php, we can do the following;

<?php
if( isset($_GET['q']) ) { //See if there is any query string
  $short_code = ctype_alnum( (string) $_GET['q']) ? (string) $_GET['q'] : ''; //Filter out any potential nasty characters.
  /**
   * Query database
   * SELECT `long_url` FROM `urls` WHERE `short_url` = $short_code
   * Best to use PDO or MySQLi to do this (and I'm assuming you're using a MySQL database to store these)
   */
   if($query->num_rows) { //There is a result
      $result = $query->fetch(PDO::FETCH_ASSOC); //Assuming you've used PDO
      header('Location: '. $result['long_url']); //Redirect to the long url
      die;
   } else {
      //Short code doesn't exist
      http_response_code(404); //No result, return with 404 Not Found
      die;
   } 
} else {
   //Do other logic...
}