本文整理汇总了PHP中rand函数的典型用法代码示例。如果您正苦于以下问题:PHP rand函数的具体用法?PHP rand怎么用?PHP rand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rand函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: ajoutLieu
function ajoutLieu()
{
require 'connect.php';
$requete = $bdd->query("SELECT \n\t\t\t\t\t\t\t\tVILID\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\tcommune");
$villes = $requete->fetchAll();
$requete->closeCursor();
$requete = $bdd->prepare("SELECT \n\t\t\t\t\t\t\t\tLIEUID\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\tLIEU\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tLIEUID=:lieuId\n\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\tVILID=:ville\n\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\tLIEUNOM=:nom");
$requeteSeconde = $bdd->prepare("INSERT INTO LIEU\n\t\t\t\t\t\t\t\t\t\t(LIEUID,\n\t\t\t\t\t\t\t\t\t\tVILID,\n\t\t\t\t\t\t\t\t\t\tLIEUNOM,\n\t\t\t\t\t\t\t\t\t\tLIEUCOORDGPS)\n\t\t\t\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t\t\t\t(:lieuId,\n\t\t\t\t\t\t\t\t\t\t:ville,\n\t\t\t\t\t\t\t\t\t\t:nom,\n\t\t\t\t\t\t\t\t\t\t:gps)");
for ($i = 0; $i < 100; $i++) {
echo $lieuId = $i;
echo $ville = $villes[rand(0, sizeof($villes) - 1)]['VILID'];
$lieuT = file('./generateurLieu.txt');
$lieu = array(trim($lieuT[rand(0, 93)]), trim($lieuT[rand(0, 93)]));
$lieu = implode("-", $lieu);
echo $nom = $lieu;
echo $gps = rand(0, 5000);
echo "<br />";
$requete->execute(array("ville" => $ville, "nom" => $nom));
if ($requete->fetch() == false) {
$requeteSeconde->execute(array("lieuId" => $lieuId, "ville" => $ville, "nom" => $nom, "gps" => $gps));
} else {
$i--;
}
}
$requete->closeCursor();
$requeteSeconde->closeCursor();
}
示例2: setUp
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$this->connection = Connection::get();
$this->userBook = new UserBook($this->connection);
$this->providerInfoBook = new ProviderInfoBook($this->connection);
$this->providerUserBook = new ProviderUserBook($this->connection);
foreach ($this->providerInfoBook->get() as $providerInfo) {
$this->providerInfoBook->delete($providerInfo);
}
foreach ($this->userBook->get() as $user) {
$this->userBook->delete($user);
}
for ($k = 0; $k < 10; $k++) {
$user = new User();
$user->setEnabled(RandomBook::getRandomBoolean())->setEnabledDate(RandomBook::getRandomDate())->setAccessFailedCount(rand(1, 5))->setEmail(RandomBook::getRandomEmail())->setPassword(RandomBook::getRandomString())->setPhoneNumber(RandomBook::getRandomPhoneNumber())->setTwoFactorEnabled(RandomBook::getRandomBoolean())->setUserName(RandomBook::getRandomString());
$user->setId($this->userBook->save($user));
$this->userList[] = $user;
for ($k = 0; $k < 10; $k++) {
$providerInfo = new ProviderInfo();
$providerInfo->setName(RandomBook::getRandomString())->setAppKey(RandomBook::getRandomString())->setSecretKey(RandomBook::getRandomString());
$providerInfo->setId((int) $this->providerInfoBook->save($providerInfo));
$this->providerInfoList[] = $providerInfo;
$providerUser = new ProviderUser();
$providerUser->setUserId($user->getId())->setProviderId($providerInfo->getId())->setProviderName($providerInfo->getName())->setProviderUserId(RandomBook::getRandomString());
$this->providerUserList[] = $providerUser;
}
}
}
示例3: testBuild
public function testBuild()
{
$type = 'history';
$userId = 1;
$user = $this->getMockBuilder('stdClass')->setMethods(['getId'])->getMock();
$user->expects($this->once())->method('getId')->will($this->returnValue($userId));
$token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
$token->expects($this->once())->method('getUser')->will($this->returnValue($user));
$this->tokenStorage->expects($this->once())->method('getToken')->will($this->returnValue($token));
$item = $this->getMock('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationItemInterface');
$this->factory->expects($this->once())->method('createItem')->with($type, [])->will($this->returnValue($item));
$repository = $this->getMockBuilder('Oro\\Bundle\\NavigationBundle\\Entity\\Repository\\HistoryItemRepository')->disableOriginalConstructor()->getMock();
$items = [['id' => 1, 'title' => 'test1', 'url' => '/'], ['id' => 2, 'title' => 'test2', 'url' => '/home']];
$repository->expects($this->once())->method('getNavigationItems')->with($userId, $type)->will($this->returnValue($items));
$this->em->expects($this->once())->method('getRepository')->with(get_class($item))->will($this->returnValue($repository));
$menu = $this->getMockBuilder('Knp\\Menu\\MenuItem')->disableOriginalConstructor()->getMock();
$childMock = $this->getMock('Knp\\Menu\\ItemInterface');
$childMock2 = clone $childMock;
$children = [$childMock, $childMock2];
$matcher = $this->getMock('\\Knp\\Menu\\Matcher\\Matcher');
$matcher->expects($this->once())->method('isCurrent')->will($this->returnValue(true));
$this->builder->setMatcher($matcher);
$menu->expects($this->exactly(2))->method('addChild');
$menu->expects($this->once())->method('setExtra')->with('type', $type);
$menu->expects($this->once())->method('getChildren')->will($this->returnValue($children));
$menu->expects($this->once())->method('removeChild');
$n = rand(1, 10);
$configMock = $this->getMockBuilder('Oro\\Bundle\\ConfigBundle\\Config\\UserConfigManager')->disableOriginalConstructor()->getMock();
$configMock->expects($this->once())->method('get')->with($this->equalTo('oro_navigation.maxItems'))->will($this->returnValue($n));
$this->manipulator->expects($this->once())->method('slice')->with($menu, 0, $n);
$this->builder->setOptions($configMock);
$this->builder->build($menu, [], $type);
}
示例4: slots
public function slots()
{
$user = Auth::user();
$location = $user->location;
$slot = Slot::where('location', '=', $location)->first();
$input = Input::get('wager');
$owner = User::where('name', '=', $slot->owner)->first();
$num1 = rand(1, 10);
$num2 = rand(5, 7);
$num3 = rand(5, 7);
if ($user->name != $owner->name) {
if ($num1 & $num2 & $num3 == 6) {
$money = rand(250, 300);
$payment = $money += $input * 1.75;
$user->money += $payment;
$user->save();
session()->flash('flash_message', 'You rolled three sixes!!');
return redirect('/home');
} else {
$user->money -= $input;
$user->save();
$owner->money += $input;
$owner->save();
session()->flash('flash_message_important', 'You failed to roll three sixes!!');
return redirect(action('SlotsController@show', [$slot->location]));
}
} else {
session()->flash('flash_message_important', 'You own this slot!!');
return redirect(action('SlotsController@show', [$slot->location]));
}
}
示例5: check_skill400_proc
function check_skill400_proc(&$pa, &$pd, $active)
{
if (eval(__MAGIC__)) {
return $___RET_VALUE;
}
eval(import_module('skill400', 'player', 'logger'));
if (!\skillbase\skill_query(400, $pa) || !check_unlocked400($pa)) {
return array();
}
$l400 = \skillbase\skill_getvalue(400, 'lvl', $pa);
if (rand(0, 99) < $procrate[$l400]) {
if ($active) {
if ($l400 >= 5) {
$log .= "<span class=\"yellow\">你朝{$pd['name']}打出了猛烈的一击!</span><br>";
} else {
$log .= "<span class=\"yellow\">你朝{$pd['name']}打出了重击!</span><br>";
}
} else {
if ($l400 == 5) {
$log .= "<span class=\"yellow\">{$pa['name']}朝你打出了猛烈的一击!</span><br>";
} else {
$log .= "<span class=\"yellow\">{$pa['name']}朝你打出了重击!</span><br>";
}
}
$dmggain = (100 + $attgain[$l400]) / 100;
return array($dmggain);
}
return array();
}
示例6: postContent
function postContent()
{
if (!($user = \Idno\Core\site()->session()->currentUser())) {
$this->setResponse(403);
echo 'You must be logged in to approve IndieAuth requests.';
exit;
}
$me = $this->getInput('me');
$client_id = $this->getInput('client_id');
$redirect_uri = $this->getInput('redirect_uri');
$state = $this->getInput('state');
$scope = $this->getInput('scope');
if (!empty($me) && parse_url($me, PHP_URL_HOST) == parse_url($user->getURL(), PHP_URL_HOST)) {
$indieauth_codes = $user->indieauth_codes;
if (empty($indieauth_codes)) {
$indieauth_codes = array();
}
$code = md5(rand(0, 99999) . time() . $user->getUUID() . $client_id . $state . rand(0, 999999));
$indieauth_codes[$code] = array('me' => $me, 'redirect_uri' => $redirect_uri, 'scope' => $scope, 'state' => $state, 'client_id' => $client_id, 'issued_at' => time(), 'nonce' => mt_rand(1000000, pow(2, 30)));
$user->indieauth_codes = $indieauth_codes;
$user->save();
if (strpos($redirect_uri, '?') === false) {
$redirect_uri .= '?';
} else {
$redirect_uri .= '&';
}
$redirect_uri .= http_build_query(array('code' => $code, 'state' => $state, 'me' => $me));
$this->forward($redirect_uri);
}
}
示例7: testAddTagSet
function testAddTagSet()
{
$this->webtestLogin();
$this->openCiviPage("admin/tag", "action=add&reset=1&tagset=1");
// take a tagset name
$tagSetName = 'tagset_' . substr(sha1(rand()), 0, 7);
// fill tagset name
$this->type("name", $tagSetName);
// fill description
$this->type("description", "Adding new tag set.");
// select used for contact
$this->select("used_for", "value=civicrm_contact");
// check reserved
$this->click("is_reserved");
// Clicking save.
$this->click("_qf_Tag_next");
$this->waitForPageToLoad($this->getTimeoutMsec());
// Is status message correct?
$this->assertTrue($this->isTextPresent("The tag '{$tagSetName}' has been saved."));
// sort by ID desc
$this->click("xpath=//table//tr/th[text()=\"ID\"]");
$this->waitForElementPresent("css=table.display tbody tr td");
// verify text
$this->waitForElementPresent("xpath=//table//tbody/tr/td[1][text()= '{$tagSetName}']");
$this->waitForElementPresent("xpath=//table//tbody/tr/td[1][text()= '{$tagSetName}']/following-sibling::td[2][text()='Adding new tag set. ']");
$this->waitForElementPresent("xpath=//table//tbody/tr/td[1][text()= '{$tagSetName}']/following-sibling::td[4][text()= 'Contacts']");
$this->waitForElementPresent("xpath=//table//tbody/tr/td[1][text()= '{$tagSetName}']/following-sibling::td[7]/span/a[text()= 'Edit']");
}
示例8: save_picture
/**
Upload a profile picture for the group
*/
function save_picture($ext)
{
global $cfg;
if (!$this->user->logged_in() || !$this->user->group) {
throw new Exception("Access denied!");
}
if (!isset($_SERVER["CONTENT_LENGTH"])) {
throw new Exception("Invalid parameters");
}
$size = (int) $_SERVER["CONTENT_LENGTH"];
$file_name = rand() . time() . "{$this->user->id}.{$ext}";
$file_path = "{$cfg['dir']['content']}{$file_name}";
// Write the new one
$input = fopen("php://input", "rb");
$output = fopen($file_path, "wb");
if (!$input || !$output) {
throw new Exception("Cannot open files!");
}
while ($size > 0) {
$data = fread($input, $size > 1024 ? 1024 : $size);
$size -= 1024;
fwrite($output, $data);
}
fclose($input);
fclose($output);
// Update the profile image
$this->group->update($this->user->group, array('picture' => $file_name));
}
示例9: image
/**
* Displays the captcha image
*
* @access public
* @param int $key Captcha key
* @return mixed Captcha raw image data
*/
function image($key)
{
$value = Jaws_Utils::RandomText();
$result = $this->update($key, $value);
if (Jaws_Error::IsError($result)) {
$value = '';
}
$bg = dirname(__FILE__) . '/resources/simple.bg.png';
$im = imagecreatefrompng($bg);
imagecolortransparent($im, imagecolorallocate($im, 255, 255, 255));
// Write it in a random position..
$darkgray = imagecolorallocate($im, 0x10, 0x70, 0x70);
$x = 5;
$y = 20;
$text_length = strlen($value);
for ($i = 0; $i < $text_length; $i++) {
$fnt = rand(7, 10);
$y = rand(6, 10);
imagestring($im, $fnt, $x, $y, $value[$i], $darkgray);
$x = $x + rand(15, 25);
}
header("Content-Type: image/png");
ob_start();
imagepng($im);
$content = ob_get_contents();
ob_end_clean();
imagedestroy($im);
return $content;
}
示例10: submit
function submit()
{
//Check required Fields
$missing = false;
if (!isset($_POST["sql"]) || strlen($_POST["sql"]) == 0) {
$missing = true;
}
if ($missing) {
$this->res->success = false;
$this->res->message = "missing required field!";
return null;
}
//get vars
$sql = $_POST["sql"];
$schema_id = $this->params['schema_id'];
$schema = Doo::db()->getOne('Schemata', array('where' => 'id = ' . $schema_id));
$async = isset($_POST['async']) ? $_POST['async'] : 0;
$coord_name = isset($_POST['coord_name']) ? $_POST['coord_name'] : null;
$query_id = isset($_POST["query_id"]) ? $_POST["query_id"] : strtoupper(md5(uniqid(rand(), true)));
//init
$shard_query = new ShardQuery($schema->schema_name);
//error!
if (!empty($shard_query->errors)) {
//return
$this->res->message = $shard_query->errors;
$this->res->success = false;
return null;
}
//set async
$shard_query->async = $async == true ? true : false;
//set coord shard
if (isset($coord_name)) {
$shard_query->set_coordinator($coord_name);
}
//execute query
$stmt = $shard_query->query($sql);
//error!
if (!$stmt && !empty($shard_query->errors)) {
//return
$this->res->message = $shard_query->errors;
$this->res->success = false;
return null;
}
//empty results
if ($stmt == null && empty($shard_query->errors)) {
$this->res->data = array();
}
//build data
if (!is_int($stmt)) {
$this->res->data = $this->json_format($shard_query, $stmt);
$shard_query->DAL->my_free_result($stmt);
} else {
//save job_id
$this->res->data = $stmt;
}
//save message
$this->res->message = $query_id;
//return
$this->res->success = true;
}
示例11: autoalias2_convert
/**
* Converts a title into an alias
*
* @param string $title Title
* @param int $id Page ID
* @param bool $duplicate TRUE if duplicate alias was previously detected
* @return string
*/
function autoalias2_convert($title, $id = 0, $duplicate = false)
{
global $cfg, $cot_translit, $cot_translit_custom;
if ($cfg['plugin']['autoalias2']['translit'] && file_exists(cot_langfile('translit', 'core'))) {
include cot_langfile('translit', 'core');
if (is_array($cot_translit_custom)) {
$title = strtr($title, $cot_translit_custom);
} elseif (is_array($cot_translit)) {
$title = strtr($title, $cot_translit);
}
}
$title = preg_replace('#[^\\p{L}0-9\\-_ ]#u', '', $title);
$title = str_replace(' ', $cfg['plugin']['autoalias2']['sep'], $title);
if ($cfg['plugin']['autoalias2']['lowercase']) {
$title = mb_strtolower($title);
}
if ($cfg['plugin']['autoalias2']['prepend_id'] && !empty($id)) {
$title = $id . $cfg['plugin']['autoalias2']['sep'] . $title;
} elseif ($duplicate) {
switch ($cfg['plugin']['autoalias2']['on_duplicate']) {
case 'ID':
if (!empty($id)) {
$title .= $cfg['plugin']['autoalias2']['sep'] . $id;
break;
}
default:
$title .= $cfg['plugin']['autoalias2']['sep'] . rand(2, 99);
break;
}
}
return $title;
}
示例12: log_ip
function log_ip($attribute, $multiple = 1)
{
if ($attribute == "TC") {
// Is Super Peer Enabled?
$super_peer_mode = mysql_result(mysql_query("SELECT field_data FROM `main_loop_status` WHERE `field_name` = 'super_peer' LIMIT 1"), 0, 0);
if ($super_peer_mode > 0) {
// Only count 1 in 4 IP for Transaction Clerk to avoid
// accidental banning of peers accessing high volume data.
if (rand(1, 4) != 4) {
return;
}
}
}
// Log IP Address Access
$sql = "INSERT INTO `ip_activity` (`timestamp` ,`ip`, `attribute`) VALUES ";
while ($multiple >= 1) {
if ($multiple == 1) {
$sql .= "('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', '{$attribute}')";
} else {
$sql .= "('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', '{$attribute}'),";
}
$multiple--;
}
mysql_query($sql);
return;
}
示例13: prepareSubject
/**
* Prepare a DatabaseConnection subject.
* Used by driver specific test cases.
*
* @param string $driver Driver to use like "mssql", "oci8" and "postgres7"
* @param array $configuration Dbal configuration array
* @return \TYPO3\CMS\Dbal\Database\DatabaseConnection|\PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface
*/
protected function prepareSubject($driver, array $configuration)
{
/** @var \TYPO3\CMS\Dbal\Database\DatabaseConnection|\PHPUnit_Framework_MockObject_MockObject|\TYPO3\CMS\Core\Tests\AccessibleObjectInterface $subject */
$subject = $this->getAccessibleMock(\TYPO3\CMS\Dbal\Database\DatabaseConnection::class, array('getFieldInfoCache'), array(), '', false);
$subject->conf = $configuration;
// Disable caching
$mockCacheFrontend = $this->getMock(\TYPO3\CMS\Core\Cache\Frontend\PhpFrontend::class, array(), array(), '', false);
$subject->expects($this->any())->method('getFieldInfoCache')->will($this->returnValue($mockCacheFrontend));
// Inject SqlParser - Its logic is tested with the tests, too.
$sqlParser = $this->getAccessibleMock(\TYPO3\CMS\Dbal\Database\SqlParser::class, array('dummy'), array(), '', false);
$sqlParser->_set('databaseConnection', $subject);
$sqlParser->_set('sqlCompiler', GeneralUtility::makeInstance(\TYPO3\CMS\Dbal\Database\SqlCompilers\Adodb::class, $subject));
$sqlParser->_set('nativeSqlCompiler', GeneralUtility::makeInstance(\TYPO3\CMS\Dbal\Database\SqlCompilers\Mysql::class, $subject));
$subject->SQLparser = $sqlParser;
// Mock away schema migration service from install tool
$installerSqlMock = $this->getMock(\TYPO3\CMS\Install\Service\SqlSchemaMigrationService::class, array('getFieldDefinitions_fileContent'), array(), '', false);
$installerSqlMock->expects($this->any())->method('getFieldDefinitions_fileContent')->will($this->returnValue(array()));
$subject->_set('installerSql', $installerSqlMock);
$subject->initialize();
// Fake a working connection
$handlerKey = '_DEFAULT';
$subject->lastHandlerKey = $handlerKey;
$adodbDriverClass = '\\ADODB_' . $driver;
$subject->handlerInstance[$handlerKey] = new $adodbDriverClass();
$subject->handlerInstance[$handlerKey]->DataDictionary = NewDataDictionary($subject->handlerInstance[$handlerKey]);
$subject->handlerInstance[$handlerKey]->_connectionID = rand(1, 1000);
return $subject;
}
示例14: preSave
public function preSave(PropelPDO $con = null)
{
if ($this->isNew()) {
$this->setUniqueHashForFeedUrl(md5(time() . rand(0, time())));
}
return parent::preSave($con);
}
开发者ID:EfncoPlugins,项目名称:Media-Management-based-on-Kaltura,代码行数:7,代码来源:UverseClickToOrderDistributionProfile.php
示例15: adodb_session_regenerate_id
function adodb_session_regenerate_id()
{
$conn =& ADODB_Session::_conn();
if (!$conn) {
return false;
}
$old_id = session_id();
if (function_exists('session_regenerate_id')) {
session_regenerate_id();
} else {
session_id(md5(uniqid(rand(), true)));
$ck = session_get_cookie_params();
setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
//@session_start();
}
$new_id = session_id();
$ok =& $conn->Execute('UPDATE ' . ADODB_Session::table() . ' SET sesskey=' . $conn->qstr($new_id) . ' WHERE sesskey=' . $conn->qstr($old_id));
/* it is possible that the update statement fails due to a collision */
if (!$ok) {
session_id($old_id);
if (empty($ck)) {
$ck = session_get_cookie_params();
}
setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
return false;
}
return true;
}