How to generate random php slug/url and insert in database?

1.1k views Asked by At

i want to generate 6 character random url for each post like ac7Lmn,uYoXo etc when user clicks submit button .

if the slug already exists in database then generate another.

i need short random url like youtube "https://www.youtube.com/watch?v=95I5VaR7GeU"

<?php

if(isset($_POST['submit'])){

$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];



$post_slug = [WHAT CAN I DO HERE  ]  




if( $post_image==''    ) {
echo "<p>  upload an image please</p>";


}

else{

$insert ="insert into posts (post_image,post_slug) values ('$post_image','$post_slug' ) "; 

}


} ?>

1

There are 1 answers

0
N.B. On

Your best option is not to generate a random slug but to encode the value of primary key (id) using Hashids library.

Why? Because you remove the problem of generating a unique string. Since id is already unique, simply deliver it to the client encoded. When you receive this string, decode it. If decoding fails, your client provided an invalid hashid.

Encoding example

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(1);

Decoding example

use Hashids\Hashids;

$hashids = new Hashids();

$id = $hashids->encode(1); 
$number = $hashids->decode($id); 

This approach is quick and efficient and you can set your own custom alphabet for purposes of encoding.

If you go down the route of generating a unique string, you need to deal with unique keys and custom algorithm for generating this unique string. Since id will always be unique, you're going to repeat something that's done for you by MySQL.