Hướng dẫn is php timestamp unique?
uniqid() in PHP generates a unique ID based on the current timestamp in microseconds. Is that really a foolproof way to generate a unique ID? Even assuming there's a single user running a single script with a loop generating a timestamp in microseconds, can there still really be a theoretical guarantee that it's unqiue? And in practice, is the likelihood completely negligible? For clarity, say your loop is nothing more than this:
is there any theoretical chance it might not be unique and, if so, how realistic is it in practice? asked Nov 12, 2014 at 8:57
vanamerongenvanamerongen 7883 gold badges10 silver badges27 bronze badges 1 Microsecond based ids are only guaranteed to be unique within limits. A single threaded scripts on a single computer is probably pretty safe in this regard. However, as soon as you start talking about parallel execution, be that simply on multiple CPUs within the same machine or especially across multiple machines, all bets are off. So it depends on what you want to use this id for. If you're just using it to generate an id which is used only within the same script, it's probably safe enough. For example:
You very likely won't encounter any problems here with this limited use. However, if you start generating file names using answered Nov 12, 2014 at 9:05
deceze♦deceze 497k81 gold badges718 silver badges865 bronze badges 1 Ask yourself why you need uniqid in the first place. For instance, I use uniquid as the filename of uploads to my website. There can be any number of users who upload at the same time so what I am concerned with is two or more files having the same id, BUT I know that a single user can only upload one file at a time. So, I prepend the username in front and will always have uniqueness.
Of course, you should always ask yourself if you need to use uniquid in the first place. If you know the reason you are creating the id can only happen every x seconds, minutes, etc then you can create an id the same way just use time :
answered Oct 17, 2015 at 6:14
user756659user756659 3,08011 gold badges46 silver badges104 bronze badges 1. Chức năng của hàm uniqid()Hàm uniqid() trong PHP có chức năng tạo ra một chuỗi ký tự duy nhất dựa vào thời gian hiện tại tính theo micro giây. Chuỗi ký tự được tạo ra thường dùng làm định danh duy nhất (unique ID), có thể dùng làm khóa chính trong cơ sở dữ liệu. 2. Cú pháp của hàm uniqid()
Trong đó:
Lưu ý: Hàm 3. Một số ví dụ sử dụng hàm uniqid()Chạy hàm uniqid() không có $prefix
Chạy hàm
Trong PHP, bạn có thể sử dụng những hàm như random_int(), random_bytes() hoặc openssl_random_pseudo_bytes()để thay cho uniqid(). Những hàm này giúp bạn tạo những mật mã an toàn ngẫu nhiên có tính duy nhất được đảm bảo hơn hàm uniqid() trong PHP.
|