php-src/ext/standard/uniqid.c

85 lines
2.5 KiB
C
Raw Normal View History

/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
2006-01-01 12:51:34 +00:00
| This source file is subject to version 3.01 of the PHP license, |
1999-07-16 13:13:16 +00:00
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
2006-01-01 12:51:34 +00:00
| http://www.php.net/license/3_01.txt |
1999-07-16 13:13:16 +00:00
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
2017-01-02 15:30:12 +00:00
| Author: Stig Sæther Bakken <ssb@php.net> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include <stdlib.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <errno.h>
#include <stdio.h>
2000-02-11 15:59:30 +00:00
#ifdef PHP_WIN32
#include "win32/time.h"
#else
#include <sys/time.h>
#endif
#include "php_lcg.h"
#include "uniqid.h"
#ifdef HAVE_GETTIMEOFDAY
ZEND_TLS struct timeval prev_tv = { 0, 0 };
2008-05-04 21:17:33 +00:00
/* {{{ proto string uniqid([string prefix [, bool more_entropy]])
2001-10-19 18:42:25 +00:00
Generates a unique ID */
1999-05-16 11:19:26 +00:00
PHP_FUNCTION(uniqid)
{
char *prefix = "";
zend_bool more_entropy = 0;
2014-05-09 16:43:02 +00:00
zend_string *uniqid;
int sec, usec;
size_t prefix_len = 0;
struct timeval tv;
1999-08-31 15:20:21 +00:00
2016-12-31 02:03:33 +00:00
ZEND_PARSE_PARAMETERS_START(0, 2)
Z_PARAM_OPTIONAL
Z_PARAM_STRING(prefix, prefix_len)
Z_PARAM_BOOL(more_entropy)
ZEND_PARSE_PARAMETERS_END();
1999-08-31 15:20:21 +00:00
/* This implementation needs current microsecond to change,
* hence we poll time until it does. This is much faster than
* calling usleep(1) which may cause the kernel to schedule
* another process, causing a pause of around 10ms.
*/
do {
(void)gettimeofday((struct timeval *) &tv, (struct timezone *) NULL);
} while (tv.tv_sec == prev_tv.tv_sec && tv.tv_usec == prev_tv.tv_usec);
prev_tv.tv_sec = tv.tv_sec;
prev_tv.tv_usec = tv.tv_usec;
sec = (int) tv.tv_sec;
usec = (int) (tv.tv_usec % 0x100000);
/* The max value usec can have is 0xF423F, so we use only five hex
1999-08-31 15:20:21 +00:00
* digits for usecs.
*/
if (more_entropy) {
uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, php_combined_lcg() * 10);
1999-08-31 15:20:21 +00:00
} else {
2014-05-09 16:43:02 +00:00
uniqid = strpprintf(0, "%s%08x%05x", prefix, sec, usec);
1999-08-31 15:20:21 +00:00
}
2014-05-09 16:43:02 +00:00
RETURN_STR(uniqid);
}
#endif
/* }}} */