php生成随机数 mt_rand() rand() mt_srand()函数

 更新时间:2016年11月25日 17:32  点击:1314

mt_rand() 使用 mersenne twister 算法返回随机整数。

语法
mt_rand(min,max)说明
如果没有提供可选参数 min 和 max,mt_rand() 返回 0 到 rand_max 之间的伪随机数。例如想要 5 到 15(包括 5 和 15)之间的随机数,用 mt_rand(5, 15)。

*/
echo mt_rand();        //生成随机数
echo "<br/>";
echo mt_rand();        //生成随机数
echo "<br/>";
echo mt_rand(10,100);       //生成10~00之间的随机数

/*
mt_srand() 播种 mersenne twister 随机数生成器。

语法
mt_srand(seed)参数 描述
seed 必需。用 seed 来给随机数发生器播种。

说明
从 php教程 4.2.0 版开始,seed 参数变为可选项,当该项为空时,会被设为随时数。

*/

function make_seed()          //生成一个随机数种子
{
  list($usec,$sec)=explode(' ',microtime());      //分割当前的毫秒数
  return(float) $sec+((float)$usec*100000);      //返回值
}
mt_srand(make_seed());          //为随机数发生器播种
$randval=mt_rand();           //生成随机数
echo $randval;            //输出结果

/*
rand() 函数返回随机整数。

语法
rand(min,max)参数 描述
min,max 可选。规定随机数产生的范围。

说明
如果没有提供可选参数 min 和 max,rand() 返回 0 到 rand_max 之间的伪随机整数。例如,想要 5 到 15(包括 5 和 15)之间的随机数,用 rand(5, 15)。

*/

echo rand();        //生成随机数
echo "<br/>";
echo rand();        //生成随机数
echo "<br/>";
echo rand(5,15);       //生成5~15之间的随机数

/*
注释:在某些平台下(例如 windows)rand_max 只有 32768。如果需要的范围大于 32768,那么指定 min 和 max 参数就可以生成大于 rand_max 的数了,或者考虑用 mt_rand() 来替代它
*/

//初始化session
session_start();
//添加url rewrite的值
output_add_rewrite_var('var','value');
//插入一个连接
echo '<a href="file.php教程">link</a>';
//发送缓冲区数据
ob_flush();
//重置url rewrite的值
output_reset_rewrite_vars();
//插入一个连接
echo '<a href="file.php">link</a>';

/*

*/

print_r(ob_list_handlers());     //列出使用的输出句柄,将输出default output handler
ob_end_flush();        //发送缓冲区数据并关闭缓冲区
ob_start("ob_gzhandler");      //打开缓冲区,并使用ob_gzhandler
print_r(ob_list_handlers());     //列出输出句柄,将输出ob_gzhandler
ob_end_flush();        //发送缓冲区数据并关闭缓冲区
ob_start(create_function('$string','return $string;')); //打开缓冲区
print_r(ob_list_handlers());     //列出使用的输出句柄,将输出default output handler
ob_end_flush();        //发送缓冲区数据并关闭缓冲区

/*

*/

if(ob_get_level()==0)      //判断缓冲区等级,如果没有活动缓冲区
ob_start();        //打开缓冲区
for($i=0;$i<10;$i++)      //循环执行操作
{
  echo "<br>line to show.";    //输出内容
  echo str_pad('',4096)."n";    //输出生成的字符串
  ob_flush();       //发送缓冲区数据
  flush();        //刷新缓冲区
  sleep(1);       //暂停1秒
}
echo "done.";       //输出操作完成标记
ob_end_flush();       //发送缓冲区数据,并关闭缓冲区

?>

<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title>insert title here</title>
<script type="text/网页特效">
function checkusername(input){
 var name = input.value;
 var url = 'checkusername.php教程?username=' + name;

 var xmlhttp = getxmlhttpobject();
 xmlhttp.onreadystatechange = function(){
  if (xmlhttp.readystate==4){
   $$("pmt_username").innerhtml = xmlhttp.responsetext;
  }
 }
 xmlhttp.open("get",url,true);
 xmlhttp.send(null);
}
function getxmlhttpobject(){
 var xmlhttp=null;
 try{
  // firefox, opera 8.0+, safari
  xmlhttp=new xmlhttprequest();
 }catch (e){
  // internet explorer
  try{
   xmlhttp=new activexobject("msxml2.xmlhttp");
  }catch (e){
   xmlhttp=new activexobject("microsoft.xmlhttp");
  }
 }
 return xmlhttp;
}
function checkform(form){
 try{
  assertnonempty(form.username);
  assertnonempty(form.pwd);
//  assertint(form.mobile);
 } catch(e){
  return false;
 }
 return true;
}
function assertnonempty(obj){
 if(obj.value == ''){
  var tds = gettdelems(obj);
  var text = tds[0].innerhtml;
  
  tds[1].innerhtml = text.slice(0,-1) + '不能为空';
  obj.focus();
  obj.select();
  
  throw new exception();
 }
}
function assertint(obj){
 var v = obj.value;
 if(/d{11}/.test(v)){
  alert('ok');
 } else {
  alert('error');
 }
 if(number(v) != v){
  var tds = gettdelems(obj);
  var text = tds[0].innerhtml;
  
  tds[1].innerhtml = text.slice(0,-1) + '应该是数值';
  
  obj.focus();
  obj.select();
  throw new exception();
 }
}
window.onload = function(){
// alert($$('username').type);
// $$('abc').onkeydown = mobilekeydown;
}
function gettdelems(obj){
 var tr = obj.parentnode.parentnode;
 var tds = tr.getelementsbytagname('td');
 return [tds[0],tds[2]];
}
function mobilekeydown(e){
 e = e || event;
 return e.keycode >47 && e.keycode < 59;
}

function $$(id){
 return document.getelementbyid(id);
}
function checkcode(input){
 var name = input.value;
 var url = 'checkcode.php?code=' + name;

 var xmlhttp = getxmlhttpobject();
 xmlhttp.onreadystatechange = function(){
  if (xmlhttp.readystate==4){
   $$("code").innerhtml = xmlhttp.responsetext;
  }
 }
 xmlhttp.open("get",url,true);
 xmlhttp.send(null);
}
</script>
</head>
<body>
<form method="post" action='register.php' enctype="multipart/form-data" onsubmit='return checkform(this)'>
 <table>
  <tr>
   <td>用户名:</td>
   <td><input type='text' name='username' onblur='checkusername(this)'></td>
   <td id='pmt_username'></td>
  </tr>
  <tr>
   <td>密码:</td>
   <td><input type='password' name='pwd'></td>
   <td id='pmt_pwd'></td>
  </tr>
  <tr>
   <td>重复密码:</td>
   <td><input type='password' name='pwd2'></td>
   <td></td>
  </tr>
  <tr>
   <td>姓名:</td>
   <td><input type='text' name='name'></td>
   <td></td>
  </tr>
  <tr>
   <td>性别:</td>
   <td>
    <input id='sex_m' checked type='radio' name='sex' value='男'><label for='sex_m'> 男 </label>
    <label><input type='radio' name='sex' value='女'>女</label>
   </td>
   <td></td>
  </tr>
  <tr>
   <td>年龄:</td>
   <td><input type='text' name='age'></td>
   <td id='pmt_age'></td>
  </tr>
  <tr>
   <td>手机:</td>
   <td><input type='text' name='mobile'></td>
   <td></td>
  </tr>
  <tr>
   <td>通信地址:</td>
   <td><input type='text' name='address'></td>
   <td></td>
  </tr>
  <tr>
   <td>邮件地址:</td>
   <td><input type='text' name='email'></td>
   <td></td>
  </tr>
  <tr>
   <td>用户照片:</td>
   <td><input type='file' name='photo'></td>
   <td></td>
  </tr>
  <tr>
   <td>出生日期:</td>
   <td><input type='text' name='birthday'></td>
   <td></td>
  </tr>
  <tr>
   <td>验证码:</td>
   <td><input type='text' name='verifycode' onblur='checkcode(this)'><img src='verifycode.php'></td>
   <td id='code'></td>
  </tr>
  <tr>
   <td colspan='3'><input type='submit' value='注册'> <input type='reset' value='重置'></td>
  </tr>
 </table>
</form>

</body>
</html>

checkusername.php文件

<?php
 $username = $_get['username'];
 mysql教程_connect('127.0.0.1', 'root', '') or die('could not connect: ' . mysql_error());
 mysql_select_db('test');
 
 //拼接sql语句时必须将用户输入的值做处理,替换特殊字符,用引号包含
 $username = htmlentities($username,ent_quotes);
 $sql = "select count(*) from user where username ='{$username}'";
 
 $result = mysql_query($sql);
 if($row = mysql_fetch_array($result, mysql_num)){
  $cnt = $row[0];
  if($cnt == 0) {
   echo '用户名未被使用';
  } else {
   echo '用户名已被使用,请改换用户名';
  }
 }
?>

verifycode.php验证码程序


<?php
session_start();

$rnd = array_merge(range(0,9),range('a','z'));
shuffle($rnd);

$code = implode('',$rnd);
$code = substr($code,0,4);

$_session['verifycode'] = $code;

header("content-type: image/png");
$im = @imagecreate(50, 25) or die("cannot initialize new gd image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 5, 5, 5,  $code, $text_color);
imagepng($im);
imagedestroy($im);


?>
checkcode.php 检测用户输入的验证码是否一致
<?php
 session_start();
 
 $code = $_get['code'];
 
 echo strtoupper($code) == $_session['verifycode'] ? '验证码正确' : '验证码错误';
?>

register.php注册处理程序

<?php
session_start();

$filename = '';
if(isset($_files['photo'])){
 $uploaddir = dirname(__file__) . directory_separator . 'upload';
 $originfilename = $_files['photo']['name'];
 $extname = strtolower(substr($originfilename,strrpos($originfilename,'.')+1));
 
 $filename = time() . '.' . $extname;
 
 $validext = array('jpg','jpeg','gif','png');
 if(!in_array($extname,$validext)){
  errormsg("错误的文件类型");
 }
 
 if($_files['photo']['size'] > 100*1024){
  errormsg("文件太大,超过了100k");
 }
 $uploadfile = $uploaddir . directory_separator . $filename;
 
 if(!move_uploaded_file($_files['photo']['tmp_name'], $uploadfile)) {
  errormsg("照片上传失败");
 }
}

$code = $_post['verifycode'];
if($code != $_session['verifycode']){
 errormsg("验证码输入不正确");
}

mysql_connect('127.0.0.1', 'root', '');
mysql_select_db('test');
mysql_query('set names utf8');

$username = addslashes($_post['username']);
$pwd = md5($_post['pwd']);
$name = addslashes($_post['name']);
$sex = addslashes($_post['sex']);
$age = intval($_post['age']);
$mobile = addslashes($_post['mobile']);
$address = addslashes($_post['address']);
$email = addslashes($_post['email']);
$photo = $filename;
$birthday = addslashes($_post['birthday']);

$sql = "insert into user(username,pwd,name,sex,age,mobile,address,email,photo,birthday)
 values('$username','$pwd','$name','$sex',$age,'$mobile','$address','$email','$photo','$birthday')";

if(!mysql_query($sql)){
 errormsg('数据库教程写入不成功!');
}

$sql = 'select * from user';
$res = mysql_query($sql);
echo '
 <table>
  <tr>
   <td>用户名</td>
   <td>姓名</td>
   <td>性别</td>
   <td>年龄</td>
   <td>手机</td>
   <td>通信地址</td>
   <td>邮件地址</td>
   <td>出生日期</td>
<!--   <td>照片</td> -->
  </tr>
';
while($row = mysql_fetch_assoc($res)){
 $photo = $row['photo'] ? "<img src='./upload/{$row['photo']}'>" : '';
 echo "
  <tr>
   <td>{$row['username']}</td>
   <td>{$row['name']}</td>
   <td>{$row['sex']}</td>
   <td>{$row['age']}</td>
   <td>{$row['mobile']}</td>
   <td>{$row['address']}</td>
   <td>{$row['email']}</td>
   <td>{$row['birthday']}</td>
<!--   <td>$photo</td> -->
  </tr>
 ";
 
}

echo '</table>';


function errormsg($str){
 die('<script type="text/javascript">alert("' . $str . '");</script>');
}


?>

最简单数据库结构

drop database if exists test;
create database test character set utf8 collate utf8_general_ci;

use test;

create table user(
 username char(10) primary key
 ,pwd char(32) not null
 ,name char(10) not null
 ,sex char(1) not null
 ,mobile char(11)
 ,age smallint
 ,address varchar(50)
 ,email varchar(30)
 ,photo varchar(20)
 ,birthday date
);

http://down.111cn.net/down/code/php/qitayuanma/2010/1220/22331.html

 php教程 session 变量用于存储有关用户会话的信息,或更改用户会话的设置。session 变量保存的信息是单一用户的,并且可供应用程序中的所有页面使用。
php session 变量
当您运行一个应用程序时,您会打开它,做些更改,然后关闭它。这很像一次会话。计算机清楚你是谁。它知道你何时启动应用程序,并在何时终止。但是在因特网上,存在一个问题:服务器不知道你是谁以及你做什么,这是由于 http 地址不能维持状态。

通过在服务器上存储用户信息以便随后使用,php session 解决了这个问题(比如用户名称、购买商品等)。不过,会话信息是临时的,在用户离开网站后将被删除。如果您需要永久储存信息,可以把数据存储在数据库教程中。

session 的工作机制是:为每个访问者创建一个唯一的 id (uid),并基于这个 uid 来存储变量。uid 存储在 cookie 中,亦或通过 url 进行传导。

*/

class my_session
{
 function my_session()
 {
  // destroy sessions started with session.auto_start
  if( session_id() )
  {
   session_unset();
   session_destroy();
  }
 
  session_start();
 }

 function set($name, $value)
 {
  $_session[$name] = $value;
 }

 function get($name)
 {
  if(isset($_session[$name]))
   return $_session[$name];
  else
   return false;
 }

 function del($name)
 {
  unset($_session[$name]);
 }

 function destroy()
 {
  $_session = array();
  session_destroy();
 }
 
}

语法
header(string,replace,http_response_code)参数 描述
string 必需。规定要发送的报头字符串。
replace 可选。指示该报头是否替换之前的报头,或添加第二个报头。

默认是 true(替换)。false(允许相同类型的多个报头)。
 
http_response_code 可选。把 http 响应代码强制为指定的值。(php 4 以及更高版本可用)


header() 函数向客户端发送原始的 http 报头。

认识到一点很重要,即必须在任何实际的输出被发送之前调用 header() 函数(在 php 4 以及更高的版本中,您可以使用输出缓存来解决此问题):


*/
header("x-sample-test:foo");       //发送http标头
header('content-type:text/plain');      //发送http标头
var_dump(headers_list());        //返回已发送的标头列表

if(!headers_sent())          //如果标头没有发送
{
  header('location:http://www.example.com/');     //发送标头
  exit;            //结束php代码
}
if(!headers_sent($filename,$linenum))      //如果没有输出指定文件
{
  header('location:http://www.example.com/');     //发送标头
  exit;            //结束php代码
}
else             //如果已经输出到指定文件
{
  echo "headers already sent in $filename on line $linenumn".
  "cannot redirect,for now please click this <a".
  "href="http://www.example.com">link</a>insteadn";   //输出提示信息
  exit;            //结束php代码
}
/*
注释:从 php 4.4 之后,该函数防止一次发送多个报头。这是对头部注入攻击的保护措施。

*/

[!--infotagslink--]

相关文章

  • php正确禁用eval函数与误区介绍

    eval函数在php中是一个函数并不是系统组件函数,我们在php.ini中的disable_functions是无法禁止它的,因这他不是一个php_function哦。 eval()针对php安全来说具有很...2016-11-25
  • php中eval()函数操作数组的方法

    在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 金额阿拉伯数字转换为中文的自定义函数

    CREATE FUNCTION ChangeBigSmall (@ChangeMoney money) RETURNS VarChar(100) AS BEGIN Declare @String1 char(20) Declare @String2 char...2016-11-25
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • C++中 Sort函数详细解析

    这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
  • PHP用strstr()函数阻止垃圾评论(通过判断a标记)

    strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。语法:strstr(string,search)参数string,必需。规定被搜索的字符串。 参数sea...2013-10-04
  • PHP函数分享之curl方式取得数据、模拟登陆、POST数据

    废话不多说直接上代码复制代码 代码如下:/********************** curl 系列 ***********************///直接通过curl方式取得数据(包含POST、HEADER等)/* * $url: 如果非数组,则为http;如是数组,则为https * $header:...2014-06-07
  • php中的foreach函数的2种用法

    Foreach 函数(PHP4/PHP5)foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。...2013-09-28
  • php二维码生成

    本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
  • C语言中free函数的使用详解

    free函数是释放之前某一次malloc函数申请的空间,而且只是释放空间,并不改变指针的值。下面我们就来详细探讨下...2020-04-25
  • Java生成随机姓名、性别和年龄的实现示例

    这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
  • PHP函数strip_tags的一个bug浅析

    PHP 函数 strip_tags 提供了从字符串中去除 HTML 和 PHP 标记的功能,该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP 标记后的结果。由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数...2014-05-31
  • SQL Server中row_number函数的常见用法示例详解

    这篇文章主要给大家介绍了关于SQL Server中row_number函数的常见用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • C#生成随机数功能示例

    这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C# 生成随机数的代码

    这篇文章主要介绍了C# 生成随机数的代码的相关资料,非常的简单实用,需要的朋友可以参考下...2020-06-25
  • php的mail函数发送UTF-8编码中文邮件时标题乱码的解决办法

    最近遇到一个问题,就是在使用php的mail函数发送utf-8编码的中文邮件时标题出现乱码现象,而邮件正文却是正确的。最初以为是页面编码的问题,发现页面编码utf-8没有问题啊,找了半天原因,最后找到了问题所在。 1.使用 PEAR 的...2015-10-21