Home Backend Development PHP Tutorial Summary of methods for generating unique numeric IDs in php_php tips

Summary of methods for generating unique numeric IDs in php_php tips

May 16, 2016 pm 08:04 PM

Regarding the problem of generating a unique digital ID, do you need to use rand to generate a random number, and then query the database to see if there is such a number? This seems a bit time-consuming. Is there any other way?

Of course not, there are actually two ways to solve it.

1. If you only use PHP and not a database, then the timestamp random number is the best method and it does not repeat;

2. If you need to use a database, you also need to associate some other data with this ID. Then give the id of the table in the MySQL database an AUTO_INCREMENT (auto-increment) attribute. Each time a piece of data is inserted, the id automatically increases to 1, and then uses mysql_insert_id() or LAST_INSERT_ID() to return the auto-incremented id.

Of course, there is already a ready-made solution to this problem. Using the php uuid extension can perfectly solve this problem. This extension can generate a unique complete digital signature. .

If you don’t use composer, please refer to https://github.com/lootils/uuid,

If your project is based on composer, please refer to https://github.com/ramsey/uuid

I won’t move the specific source code, friends can just take it down and use it directly

PHP generated unique identifier code example:

1

2

3

4

5

6

7

8

9

10

11

< &#63;

//生成唯一标识符 

//sha1()函数, "安全散列算法(SHA1)" 

function create_unique() { 

$data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'

.time() . rand(); 

return sha1($data); 

//return md5(time().$data); 

//return $data; 

}

&#63;>

Copy after login

PHP generates unique identifier function description and examples

1

2

3

4

< &#63; 

$newhash = create_unique(); 

echo $newhash

&#63;>

Copy after login

Let me share one more with you

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

/*

 * 信号量(Semaphore)。

 * 这是一个包装类,用于解决不同平台下对“信号量”的不同实现方式。

 * 目前这个类只是象征性的,在 Windows 平台下实际是空跑(并没有真的实现互斥)。

 */

class SemWrapper

{

  private $hasSemSupport;

  private $sem;

  const SEM_KEY = 1;

 

  public function __construct()

  {

    $this->hasSemSupport = function_exists( 'sem_get' );

    if ( $this->hasSemSupport ) {

      $this->sem = sem_get( self::SEM_KEY );

    }

  }

 

  public function acquire() {

    if ( $this->hasSemSupport ) {

      return sem_acquire( $this->sem );

    }

    return true;

  }

 

  public function release() {

    if ( $this->hasSemSupport ) {

      return sem_release( $this->sem );

    }

    return true;

  }

}

 

/*

 * 顺序号发生器。

 */

class SeqGenerator

{

  const SHM_KEY = 1;

 

  /**

   * 对顺序号发生器进行初始化。

   * 仅在服务器启动后的第一次调用有效,此后再调用此方法没有实际作用。

   * @param int $start 产生顺序号的起始值。

   * @return boolean 返回 true 表示成功。

   */

  static public function init( $start = 1 )

  {

    // 通过信号量实现互斥,避免对共享内存的访问冲突

    $sw = new SemWrapper;

    if ( ! $sw->acquire() ) {

      return false;

    }

 

    // 打开共享内存

    $shm_id = shmop_open( self::SHM_KEY, 'n', 0644, 4 );

    if ( empty($shm_id) ) {

      // 因使用了 'n' 模式,如果无法打开共享内存,可以认为该共享内存已经创建,无需再次初始化

      $sw->release();

      return true;

    }

 

    // 在共享内存中写入初始值

    $size = shmop_write( $shm_id, pack( 'L', $start ), 0 );

    if ( $size != 4 ) {

      shmop_close( $shm_id );

      $sw->release();

      return false;

    }

 

    // 关闭共享内存,释放信号量

    shmop_close( $shm_id );

    $sw->release();

    return true;

  }

 

  /**

   * 产生下一个顺序号。

   * @return int 产生的顺序号

   */

  static public function next()

  {

    // 通过信号量实现互斥,避免对共享内存的访问冲突

    $sw = new SemWrapper;

    if ( ! $sw->acquire() ) {

      return 0;

    }

 

    // 打开共享内存

    $shm_id = shmop_open( self::SHM_KEY, 'w', 0, 0 );

    if ( empty($shm_id) ) {

      $sw->release();

      return 0;

    }

 

    // 从共享内存中读出顺序号

    $data = shmop_read( $shm_id, 0, 4 );

    if ( empty($data) ) {

      $sw->release();

      return 0;

    }

 

    $arr = unpack( 'L', $data );

    $seq = $arr[1];

 

    // 把下一个顺序号写入共享内存

    $size = shmop_write( $shm_id, pack( 'L', $seq + 1 ), 0 );

    if ( $size != 4 ) {

      $sw->release();

      return 0;

    }

 

    // 关闭共享内存,释放信号量

    shmop_close( $shm_id );

    $sw->release();

    return $seq;

  }

}

 

$a = SeqGenerator::init( time() );

var_dump($a);

 

for ( $i=0; $i < 10; $i++ ) {

  $seq = SeqGenerator::next();

  var_dump($seq);

}

Copy after login

Okay, let’s stop here today, I hope it will be helpful to everyone learning PHP

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles