当用户点击提交按钮时,我想为每个帖子生成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' ) ";
}
} ?>
答案 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为您完成的任务。