1

I want a to create a short 6 character link with every submit button hit.

I mean to say when a person hits the submit button, i want to take the data entered and save it in a database and create a permalink for it. It should be 6 characters long and only containing [a-z] [A-Z] [0-9].

I will save the 6 character string in the database with the entered data.

So how should i go about making this code and how should i generate the 6 characters?

And BTW i was thinking of making this code in PHP...

Thanks...

Arjun Bajaj
  • 1,932
  • 7
  • 24
  • 41
  • possible duplicate of [generating unique id's in php (for url shortener)](http://stackoverflow.com/questions/4977342/generating-unique-ids-in-php-for-url-shortener) – hakre Oct 12 '11 at 12:32
  • thanks for mentioning the duplicate... I saw the post, but I want to ask how unique is unuqid(); ? And will it always be unique? – Arjun Bajaj Oct 12 '11 at 12:44
  • 1
    You mean: [How unique is uniqid?](http://stackoverflow.com/questions/4070110/how-unique-is-uniqid) - You find the search box in the top-right corner, if you have missed it so far ;) – hakre Oct 12 '11 at 12:51

2 Answers2

1

Use an int column in your DB as the primary key that auto-increments on insert, then convert this ID from decimal to base-62 in your logic for the permalink (62 allows use of 0-9, a-z and A-Z).

When creating a new permalink:

<?php

/**
 * Convert decimal int to a base-62 string
 *
 * @param int $dec
 * @returns string
 */
function toBase62 ($dec) {

  // 0 is always 0
  if ($dec == 0)
    return "0";

  // this array maps decimal keys to our base-62 radix digits
  $values = array(
    "0", "1", "2", "3", "4", 
    "5", "6", "7", "8", "9", 
    "A", "B", "C", "D", "E",
    "F", "G", "H", "I", "J",
    "K", "L", "M", "N", "O",
    "P", "Q", "R", "S", "T",
    "U", "V", "W", "X", "Y", 
    "Z", "a", "b", "c", "d", 
    "e", "f", "g", "h", "i", 
    "j", "k", "l", "m", "n", 
    "o", "p", "q", "r", "s", 
    "t", "u", "v", "w", "x", 
    "y", "z"
  );

  // convert negative numbers to positive.
  $neg = $dec < 0;
  if ($neg)
    $dec = 0 - $dec;

  // do the conversion:
  $chars = array(); // this will store our base-62 chars

  while ($dec > 0) {

    $val = $dec % 62;

    $chars[] = $values[$val];

    $dec -= $val;
    $dec /= 62;

  }

  // add zero-padding:
  while (count($chars) < 6)
    $chars[] = '0';

  // convert to string
  $rv = implode( '' , array_reverse($chars) );

  // if input was negative:
  return $neg ? "-$rv" : $rv;

}


// Usage example:

// ... do mysql insert here and retrieve new insert_id into var $id ...

$permalink = toBase62($id);

?>

When decoding a requested permalink:

<?php

/**
 * Convert base-62 string to a decimal int
 *
 * @param string $str
 * @returns int on success, FALSE on failure
 */
function base62ToInt ($str) {

  // validate str:
  if ( ! preg_match('/^\-?[0-9A-Za-z]+$/', $str) )
    return FALSE; // not a valid string

  // "0" is always 0 (as is "0000...")
  if ( preg_match('/^0+$', $str) )
    return 0;

  // this array maps decimal keys to our base-62 radix digits
  $values = array(
    "0", "1", "2", "3", "4", 
    "5", "6", "7", "8", "9", 
    "A", "B", "C", "D", "E",
    "F", "G", "H", "I", "J",
    "K", "L", "M", "N", "O",
    "P", "Q", "R", "S", "T",
    "U", "V", "W", "X", "Y", 
    "Z", "a", "b", "c", "d", 
    "e", "f", "g", "h", "i", 
    "j", "k", "l", "m", "n", 
    "o", "p", "q", "r", "s", 
    "t", "u", "v", "w", "x", 
    "y", "z"
  );

  // flip $values so it maps base-62 digits to decimal values:
  $values = array_flip($values);

  // get chars from $str:
  $chars = str_split($str);

  // convert negative numbers to positive.
  $neg = $chars[0] == '-';

  if ($neg)
    array_shift($chars);

  // do the conversion:
  $val = 0;
  $i = 0;

  while ( count($chars) > 0 ) {

    $char = array_pop($chars);
    $val += ($values[$char] * pow(62, $i) );
    ++$i;

  }

  return $neg ? 0 - $val : $val;
}


// Usage example:

// ... assuming permalink has been put in a var called $permalink

$id = base62ToInt($permalink);

// ... now look up $id in DB

?>
daiscog
  • 11,441
  • 6
  • 50
  • 62
0

You can use composite key for permalink. I am just assuming your database table structure.

|Id |Tile                                       |
-------------------------------------------------
|1  | Lorem ipsum dolor sit amet                |
|2  | consectetur adipiscing elit               |
|3  | Vestibulum posuere bibendum scelerisque   |

I am assuming that id is auto increment value.

Now, you can generate unique permalink for each entry by getting 5 characters from tile and one character from Id field. If your ID is 2 digit then four characters from title field and 2 characters from ID and so on.

Salman Aslam
  • 761
  • 1
  • 11
  • 20
  • 1
    What if the title has a space in the first few chars: "An Example Title"? What if it has a number: id = 1000, title = "12 things to do" and id=100012, title="anything" will be the same? – daiscog Oct 12 '11 at 13:29
  • @daiscog good points, well space can be replaced by "_" by str_replace . And for your second point, for 6 letters we have certain number of possible values. So, its obvious that it has limited scope. – Salman Aslam Oct 12 '11 at 19:25
  • @SalmanAslam The OP said that only the characters [a-z][A-Z][0-9] are allowed, so that rules out translating a space to an underscore or hyphen. The second point I made was really supposed to be showing that this solution allows for a duplicate identifier to exist in the database. Using purely an auto-incrementing ID and translating it to base-62 will remove this possibility, even though it still has the same 6-character limited scope. – daiscog Oct 12 '11 at 19:46
  • 1
    Furthermore, as this solution uses an incrementing ID and just pads that ID with characters from the title, the scope is actually _narrower_ than 6^62, as only one permalink is ever created with the given starting number. I.e., ID 1 is only used once, and padded with five extra characters. You will therefore run out of possibilities after ID 999999, which gives a massively reduced range of permalinks. (Unless, of course, you allow the ID to be reused with different titles. But even then, you are limited by the fact that you will never get titles that begin with gibberish like "xYK7G") – daiscog Oct 12 '11 at 19:51