如何生成随机php slug / url并插入数据库?

时间:2017-01-01 09:04:20

标签: php random slug

当用户点击提交按钮时,我想为每个帖子生成6个字符的随机网址,如ac7Lmn,uYoXo等。

如果slug已存在于数据库中,则生成另一个。

我需要像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 个答案:

答案 0 :(得分:1)

您最好的选择不是生成随机slug,而是使用Hashids库对主键(id)的值进行编码。

为什么呢?因为您消除了生成唯一字符串的问题。由于id已经是唯一的,因此只需将其传递给编码的客户端即可。收到此字符串后,对其进行解码。如果解码失败,则客户端提供了无效的hashid。

编码示例

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(1);

解码示例

use Hashids\Hashids;

$hashids = new Hashids();

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

此方法快速有效,您可以设置自己的自定义字母表以进行编码。

如果沿着生成唯一字符串的路线走下去,则需要处理唯一键和自定义算法以生成此唯一字符串。由于id将始终是唯一的,因此您将重复MySQL为您完成的任务。