本文整理汇总了PHP中srand函数的典型用法代码示例。如果您正苦于以下问题:PHP srand函数的具体用法?PHP srand怎么用?PHP srand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了srand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: quoteFromDir
function quoteFromDir($dir)
{
$amount = 0;
$index = 0;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (strpos($file, ".dat") != false) {
$len = strlen($file);
if (substr($file, $len - 4) == ".dat") {
$number = $this->getNumberOfQuotes($dir . "/" . $file);
$amount += $number;
$quotes[$index] = $amount;
$files[$index] = $file;
$index++;
}
}
}
srand((double) microtime() * 1000000);
$index = rand(0, $amount);
$i = 0;
while ($quotes[$i] < $index) {
$i++;
}
return $this->getRandomQuote($dir . "/" . $files[$i]);
}
return -1;
}
示例2: create_captcha
function create_captcha($width = 60, $height = 32)
{
session_start();
//生成验证码图片
Header("Content-type: image/PNG");
$im = imagecreate($width, $height);
// width and height of image
$back = ImageColorAllocate($im, 245, 245, 245);
// specify background color
imagefill($im, 0, 0, $back);
// fill the background color into image
$vcodes = "";
srand((double) microtime() * 1000000);
//生成4位数字
for ($i = 0; $i < 4; $i++) {
$font = ImageColorAllocate($im, rand(100, 255), rand(0, 100), rand(100, 255));
// 生成随机颜色
$authnum = rand(1, 9);
$vcodes .= $authnum;
imagestring($im, 5, 2 + $i * 10, 1, $authnum, $font);
}
for ($i = 0; $i < 100; $i++) {
// interuppting
$randcolor = ImageColorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($im, rand() % 70, rand() % 30, $randcolor);
// 画像素点函数
}
ImagePNG($im);
ImageDestroy($im);
$_SESSION['captcha'] = $vcodes;
}
示例3: check
function check($text)
{
$this->errors = array();
$this->command = '';
if (preg_match('/^([0-9]+)d([0-9]{1,3})([\\+-][0-9]+)?$/', $text, $matches)) {
$this->command['launch'] = (int) $matches[1];
$this->command['faces'] = (int) $matches[2];
// Now go for corrections
if (count($matches) == 4) {
$this->command['bias'] = $matches[3];
}
if (!($this->command['launch'] && $this->command['faces'])) {
//print_r($matches);
$this->errors[] = "Be serious, not null dice please.";
return false;
}
} else {
//print_r($matches);
// Too long
//$this->errors[] = "'$text' is not a valid string for a dice launch. Valid strings match the following patterns xdyyy, xdyyy+z or xdyyy-z where x, y and z are digits, you can have up to three y.";
$this->errors[] = 'Not valid. Valid launches are like xdyyy';
return false;
}
$this->text = $text;
srand((double) microtime() * 1000000);
return true;
}
示例4: jetpack_photon_url
/**
* Generates a Photon URL.
*
* @see http://developer.wordpress.com/docs/photon/
*
* @param string $image_url URL to the publicly accessible image you want to manipulate
* @param array|string $args An array of arguments, i.e. array( 'w' => '300', 'resize' => array( 123, 456 ) ), or in string form (w=123&h=456)
* @return string The raw final URL. You should run this through esc_url() before displaying it.
*/
function jetpack_photon_url($image_url, $args = array(), $scheme = null)
{
$image_url = trim($image_url);
$image_url = apply_filters('jetpack_photon_pre_image_url', $image_url, $args, $scheme);
$args = apply_filters('jetpack_photon_pre_args', $args, $image_url, $scheme);
if (empty($image_url)) {
return $image_url;
}
$image_url_parts = @parse_url($image_url);
// Unable to parse
if (!is_array($image_url_parts) || empty($image_url_parts['host']) || empty($image_url_parts['path'])) {
return $image_url;
}
if (is_array($args)) {
// Convert values that are arrays into strings
foreach ($args as $arg => $value) {
if (is_array($value)) {
$args[$arg] = implode(',', $value);
}
}
// Encode values
// See http://core.trac.wordpress.org/ticket/17923
$args = rawurlencode_deep($args);
}
// You can't run a Photon URL through Photon again because query strings are stripped.
// So if the image is already a Photon URL, append the new arguments to the existing URL.
if (in_array($image_url_parts['host'], array('i0.wp.com', 'i1.wp.com', 'i2.wp.com'))) {
$photon_url = add_query_arg($args, $image_url);
return jetpack_photon_url_scheme($photon_url, $scheme);
}
// This setting is Photon Server dependent
if (!apply_filters('jetpack_photon_any_extension_for_domain', false, $image_url_parts['host'])) {
// Photon doesn't support query strings so we ignore them and look only at the path.
// However some source images are served via PHP so check the no-query-string extension.
// For future proofing, this is a blacklist of common issues rather than a whitelist.
$extension = pathinfo($image_url_parts['path'], PATHINFO_EXTENSION);
if (empty($extension) || in_array($extension, array('php'))) {
return $image_url;
}
}
$image_host_path = $image_url_parts['host'] . $image_url_parts['path'];
// Figure out which CDN subdomain to use
srand(crc32($image_host_path));
$subdomain = rand(0, 2);
srand();
$photon_url = "http://i{$subdomain}.wp.com/{$image_host_path}";
// This setting is Photon Server dependent
if (isset($image_url_parts['query']) && apply_filters('jetpack_photon_add_query_string_to_domain', false, $image_url_parts['host'])) {
$photon_url .= '?q=' . rawurlencode($image_url_parts['query']);
}
if ($args) {
if (is_array($args)) {
$photon_url = add_query_arg($args, $photon_url);
} else {
// You can pass a query string for complicated requests but where you still want CDN subdomain help, etc.
$photon_url .= '?' . $args;
}
}
return jetpack_photon_url_scheme($photon_url, $scheme);
}
示例5: _reset
private function _reset()
{
$db = Database::instance();
// Drop all tables
foreach ($db->list_tables() as $table) {
$db->query("DROP TABLE IF EXISTS `{$table}`");
}
// Clean out data
dir::unlink(VARPATH . "uploads");
dir::unlink(VARPATH . "albums");
dir::unlink(VARPATH . "resizes");
dir::unlink(VARPATH . "thumbs");
dir::unlink(VARPATH . "modules");
dir::unlink(VARPATH . "tmp");
$db->clear_cache();
module::$modules = array();
module::$active = array();
// Use a known random seed so that subsequent packaging runs will reuse the same random
// numbers, keeping our install.sql file more stable.
srand(0);
gallery_installer::install(true);
module::load_modules();
foreach (array("user", "comment", "organize", "info", "rss", "search", "slideshow", "tag") as $module_name) {
module::install($module_name);
module::activate($module_name);
}
}
示例6: _create_media_record
function _create_media_record($tmp_file_path, $file_name, $mime_type)
{
if (!file_exists($tmp_file_path)) {
debug::write_error('tmp file not found', __FILE__ . ' : ' . __LINE__ . ' : ' . __FUNCTION__, array('tmp_file' => $tmp_file_path));
return false;
}
srand(time());
$media_id = md5(uniqid(rand()));
dir::mkdir(MEDIA_DIR);
if (!copy($tmp_file_path, MEDIA_DIR . $media_id . '.media')) {
debug::write_error('copy failed', __FILE__ . ' : ' . __LINE__ . ' : ' . __FUNCTION__, array('dst' => MEDIA_DIR . $media_id . '.media', 'src' => $tmp_file_path));
return false;
}
if (function_exists('md5_file')) {
$etag = md5_file($tmp_file_path);
} else {
$fd = fopen($tmp_file_path, 'rb');
$contents = fread($fd, filesize($tmp_file_path));
fclose($fd);
$etag = md5($contents);
}
$media_db_table = db_table_factory::instance('media');
$media_db_table->insert(array('id' => $media_id, 'file_name' => $file_name, 'mime_type' => $mime_type, 'size' => filesize($tmp_file_path), 'etag' => $etag));
$this->set_attribute('etag', $etag);
return $media_id;
}
示例7: seed
function seed()
{
if ($this->makeMoreRandom) {
usleep(1);
srand((double) microtime() * 1000000);
}
}
示例8: tpl_function_adsense
function tpl_function_adsense($params, &$tpl)
{
// check to make sure this is a full story
if (strcasecmp(pagename, "story") != 0) {
// not a full story, no adsense sharing
$tpl->assign($params['assign'], 0);
return;
}
// check to see if the author has an adsense id on their profile
if ($tpl->get_template_vars("google_adsense_id") == "") {
// this author hasn't provided their adsense id, no sharing
$tpl->assign($params['assign'], 0);
return;
}
// make sure the logged in user isn't the same user who submitted the story
// using a case insensitive compare because the user name isn't case sensitive
if (strcasecmp($tpl->get_template_vars("user_logged_in"), $tpl->get_template_vars("link_submitter")) == 0) {
// the user viewing the story is also the author, can't show them their own ads, no sharing
$tpl->assign($params['assign'], 0);
return;
}
// generate a random number between 1 and 100
srand((double) microtime() * 10000000);
$random = rand(1, 100);
// check the random number against their adsense percent (defaults to 50% but can be adjusted)
if ($random > $tpl->get_template_vars("google_adsense_percent")) {
// if the random number is higher than their percent of revenue sharing, no sharing this time
$tpl->assign($params['assign'], 0);
return;
}
// passed all checks, use the users adsense ID for this page
$tpl->assign($params['assign'], 1);
return;
}
示例9: generate_code
function generate_code()
{
$hours = date("H");
// час
$minuts = substr(date("H"), 0, 1);
// минута
$mouns = date("m");
// месяц
$year_day = date("z");
// день в году
$str = $hours . $minuts . $mouns . $year_day;
//создаем строку
$str = md5(md5($str));
//дважды шифруем в md5
$str = strrev($str);
// реверс строки
$str = substr($str, 3, 6);
// извлекаем 6 символов, начиная с 3
// Вам конечно же можно постваить другие значения, так как, если взломщики узнают, каким именно способом это все генерируется, то в защите не будет смысла.
$array_mix = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
srand((double) microtime() * 1000000);
shuffle($array_mix);
//Тщательно перемешиваем, соль, сахар по вкусу!!!
return implode("", $array_mix);
}
示例10: __construct
public function __construct($seed = null)
{
if ($seed === null) {
$seed = time();
}
srand($seed);
}
示例11: insert_user
function insert_user($added_name, $password, $gradyear, $email, $type, $status = '')
{
if (!$password) {
srand(time());
$password = rand(0, 999999);
}
if (!$email) {
$email = $added_name . "@grinnell.edu";
}
$crpassword = User::hashPassword($password);
$dbh = db_connect();
$myrow = array("", $added_name, "", $crpassword, $email, "", "", "", "", "", "", $gradyear, "70", "14", "", "", $type, "", "", 0);
add_row($dbh, "accounts", $myrow);
mysql_query("UPDATE accounts SET created = NOW() WHERE\n\t\t\tusername = '{$added_name}'");
$added_id = get_item($dbh, "userid", "accounts", "username", $added_name);
mysql_query("INSERT INTO plans (user_id) VALUES ({$added_id})");
add_row($dbh, "display", array($added_id, "6", "7"));
foreach (array(2, 4, 6, 8, 14, 15, 16) as $opt_link) {
$myrow = array($added_id, $opt_link);
add_row($dbh, "opt_links", $myrow);
}
$myrow = array($added_id, $status);
add_row($dbh, "perms", $myrow);
return array($password, $email);
}
示例12: post_id_reset_handler
protected function post_id_reset_handler()
{
$newpass = '';
srand();
for ($i = 0; $i < 8; $i++) {
switch (rand(1, 3)) {
case 1:
// digit
$newpass .= chr(48 + rand(0, 9));
break;
case 2:
// uppercase
$newpass .= chr(65 + rand(0, 25));
break;
case 3:
$newpass .= chr(97 + rand(0, 25));
break;
}
}
$changed = changeAnyPassword($this->id, $newpass);
if ($changed) {
$this->add_onload_command("showBootstrapAlert('#btn-bar', 'success', 'New password for {$this->id} is {$newpass}');\n");
} else {
$this->add_onload_command("showBootstrapAlert('#btn-bar', 'danger', 'Error changing password for {$this->id}');\n");
}
return true;
}
示例13: __construct
/**
* Constructor.
*
* @param BASE_CommentsParams $params
*/
public function __construct(BASE_CommentsParams $params)
{
parent::__construct();
$this->params = $params;
$this->batchData = $params->getBatchData();
$this->staticData = empty($this->batchData['_static']) ? array() : $this->batchData['_static'];
$this->batchData = isset($this->batchData[$params->getEntityType()][$params->getEntityId()]) ? $this->batchData[$params->getEntityType()][$params->getEntityId()] : array();
srand(time());
$this->id = $params->getEntityType() . $params->getEntityId() . rand(1, 10000);
$this->cmpContextId = "comments-{$this->id}";
$this->assign('cmpContext', $this->cmpContextId);
$this->assign('wrapInBox', $params->getWrapInBox());
$this->assign('topList', in_array($params->getDisplayType(), array(BASE_CommentsParams::DISPLAY_TYPE_WITH_LOAD_LIST, BASE_CommentsParams::DISPLAY_TYPE_WITH_LOAD_LIST_MINI)));
$this->assign('bottomList', $params->getDisplayType() == BASE_CommentsParams::DISPLAY_TYPE_WITH_PAGING);
$this->assign('mini', $params->getDisplayType() == BASE_CommentsParams::DISPLAY_TYPE_WITH_LOAD_LIST_MINI);
$this->isAuthorized = OW::getUser()->isAuthorized($params->getPluginKey(), 'add_comment') && $params->getAddComment();
if (!$this->isAuthorized) {
$errorMessage = $params->getErrorMessage();
if (empty($errorMessage)) {
$status = BOL_AuthorizationService::getInstance()->getActionStatus($params->getPluginKey(), 'add_comment');
$errorMessage = OW::getUser()->isAuthenticated() ? $status['msg'] : OW::getLanguage()->text('base', 'comments_add_login_message');
}
$this->assign('authErrorMessage', $errorMessage);
}
$this->initForm();
}
示例14: cc_bill
function cc_bill($cc_info, $member, $amount, $currency, $product_description, $charge_type, $invoice, $payment)
{
global $config;
$log = array();
//////////////////////// cc_bill /////////////////////////
srand(time());
if ($cc_info['cc_name_f'] == '') {
$cc_info['cc_name_f'] = $member['name_f'];
$cc_info['cc_name_l'] = $member['name_l'];
}
$vars = array("merchant" => $this->config['login'], "ticket" => $payment['payment_id'], "amount" => $amount, "card" => $cc_info['cc_number'], "expdate" => $cc_info['cc-expire'], "cardname" => $cc_info['cc_name_f'] . " " . $cc_info['cc_name_l'], "address" => $cc_info['cc_street'], "zip" => $cc_info['cc_zip'], "authenticator" => md5($this->config['secret'] . $this->config['login'] . $payment[payment_id] . $amount));
if ($cc_info['cc_code']) {
$vars['cvd'] = $cc_info['cc_code'];
}
// prepare log record
$vars_l = $vars;
$vars_l['card'] = $cc_info['cc'];
if ($vars['cvd']) {
$vars_l['cvd'] = preg_replace('/./', '*', $vars['cvd']);
}
$log[] = $vars_l;
/////
$res = $this->run_transaction($vars);
$log[] = $res;
if (preg_match("/Approved/i", $res[RESULT])) {
return array(CC_RESULT_SUCCESS, "", $res['PNREF'], $log);
} elseif (preg_match("/Declined/i", $res[RESULT])) {
return array(CC_RESULT_DECLINE_PERM, $res['RESPMSG'] ? $res[RESPMSG] : $res[RESULT], "", $log);
} else {
return array(CC_RESULT_INTERNAL_ERROR, $res['RESPMSG'] ? $res[RESPMSG] : $res[RESULT], "", $log);
}
}
示例15: sendnewpassword
function sendnewpassword($mail)
{
global $lang;
$ExistMail = doquery("SELECT `email` FROM {{table}} WHERE `email` = '" . $mail . "' LIMIT 1;", 'users', true);
if (empty($ExistMail['email'])) {
message($lang['mail_not_exist'], "index.php?modo=claveperdida", 2, false, false);
} else {
$Caracters = "aazertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890";
$Count = strlen($Caracters);
$NewPass = "";
$Taille = 6;
srand((double) microtime() * 1000000);
for ($i = 0; $i < $Taille; $i++) {
$CaracterBoucle = rand(0, $Count - 1);
$NewPass = $NewPass . substr($Caracters, $CaracterBoucle, 1);
}
$Title = $lang['mail_title'];
$Body = $lang['mail_text'];
$Body .= $NewPass;
mail($mail, $Title, $Body);
$NewPassSql = md5($NewPass);
$QryPassChange = "UPDATE {{table}} SET ";
$QryPassChange .= "`password` ='" . $NewPassSql . "' ";
$QryPassChange .= "WHERE `email`='" . $mail . "' LIMIT 1;";
doquery($QryPassChange, 'users');
}
}