PHP


PHP


概述

本php文章主要作为中间键连接后台和前端。

<?php
    header('Content-type:text/html;charset=utf-8');
    $username=$_POST[username];
    $password=$_POST[password];
    print_r($password);
    print_r($username);
    ?>

上传文件

先到服务器的tmp文件夹下,如果没有被使用,就会被删除。

文件有如下的几个信息:

  1. name:电脑上实际的名字
  2. tmp_name:文件上传保存的临时路径
  3. type:文件类型
  4. error:0为上传成功
  5. size:文件的大小
<form method="POST" enctype="multipart/form-data" action="test.php">	//加在html里
<input type="file" name="image"/>
<input type="submit" name="btn" value="上传文件"/>
</form>
<?php
    var_dump($_POST);
	var_dump($_FILES);
?>

移动文件到指定位置:

<?php
	$file=$_FILE['image'];
	if(is_uploaded_file($file['tmp_name'])){
        if(move_uploaded_file($file['tmp_name'],'path/'.$file[name]))	 echo 'success!';
        else	echo 'default';
    }else{
        echo '不是上传文件';
    }

多文件上传

)

<?php
	//不同名元素
		foreach($_FILES as $file){
			if(is_uploaded_file($file['tmp_name'])){
				move_uploaded_file($file['tmp_name'],'path/'.'$file['name']');
			}
		}
	//同名元素
	if(isset($_FILES['image']['name'])&&is_array($_FILES['image']['name'])){
		$images=array();
		foreach($_FILES['image']['name'] as $k => $file){
			$images[]=array(){
				'name' => $file,
				'tmp_name'=>$_FILES['image']['tmp_name'][$k],
				'type'=>$_FILES['image']['type'][$k],
				'error'=>$_FILES['image']['error'][$k],
				'size'=>$_FILES['image']['size'][$k]
			};
		}
	}
?>

函数封装:

<?php
    header('Content-type:text/html;charset=utf-8');
	//array_FILE mime_content_type 存储路径 错误原因 上传格式 允许上传的最大值
	function upload_single($file,$allow_type,$path,$error,$allow_format=array(),$max_size=2000000)
	{
		//是否有文件
		if(!is_array($file)||!isset($file['error'])){
			$error='文件无效';
			return false;
		}
		//判断路径
		if(!is_dir($path)){
			$error='路径无效';
			return false;
		}
		//判断error
		switch($file['error']){
			case 1:
			case 2:
				$error = '文件超出大小';
				return false;
			case 3:
				$error = '上传过程有问题,只提交了一部分';
				return false;
			case 4:
				$error = '用户没有选择要上传的文件';
				return false;
			case 6:
			case 7:
				$error = '文件保持失败';
				return false;
		}
		//MIME路径
		if(!in_array($file['type'],$allow_type)){
			$error = '文件类型不支持';
			return false;
		}
		//判断后缀,取出且无.
		$ext=ltrim(strrchr($file['name'],'.'),'.');
		if(!in_array($ext,$allow_format)&&!empty($allow_format))
		{
			$error = '文件格式不支持';
			return false;
		}
		//文件大小
		if($file['size']>$max_size)
		{
			$error = '文件最大允许'.$max_size.'bytes';
			return false;
		}
		//构造文件名称
		$fullname=strstr($file['type'],'/',TRUE).date('YYYYmmdd');
		for($i=0;$i<4;$i++)
		{
			$fullname.=chr(mt_rand(65,90));
		}
		$fullname.='.'.$ext;
		//移动到指定目录
		if(is_uploaded_file($file['tmp_name'])){
			if(move_uploaded_file($file['tmp_name'],'path/'.$fullname)){
				return $fullname;
			}
		}
	}
	$file=$_FILE['image'];
	$path='path/';
	$allow_format=array('jpg','gif','jpeg');
	$allow_type=array('image/jpg','image/jpeg','image/gif');
?>

MySQL

sql连接&&封装

<?php
    header('Content-type:text/html;charset=utf-8');
    $severname="localhost";
    $username="root";
    $pwd="pwd";
    $conn=mysqli_connect($severname,$username,$pwd);
    if(!$conn)    die();
    $conn->set_charset("utf8mb4");
    function my_sql($sql)
    {
        $res=mysqli_query($conn,$sql);
        if(!$res){
            echo($sql.mysqli_error());
        }
    }
    ?>

新闻插入数据

<?php
	header('Content-type:text/html;charset=utf-8');
	//接受数据
	$title=isset($_POST['title'])?trim($_POST['title']):'';	//trim去除空格
	$istop=isset($_POST['istop'])?(integer)$_POST['istop']:0;
	$content=isset($_POST['content'])?trim($_POST['content']):'';
	$publisher=isset($_POST['publisher'])?trim($_POST['publisher']):'none';
	//数据验证,当然可以加入其它的东西
	if(empty($title)||empty($content)){
		header('Refresh:3;href=path.html');
		exit('标题或内容不能为空!');
	}
	//引入数据库操作
	include_once 'new1.php';
	$time=time();
	$sql="insert into n_news values(null,'{$title}',{$istop},'{$content}','{$publisher}',$time);"
	$insert_id=my_sql($sql);
	//插入成功
	header('Refresh:3;href=path.php');
	exit('插入成功');
?>

读取所有数据

<?php
	header('Content-type:text/html;charset=utf-8');
	//查询插入的数据
	include_once 'new 2.php';
	$sql="select * from n_news";
	$res=my_sql($sql);
	//处理结果
	$news=array();
	while($row=mysqli_fetch_assoc($res))
	{
		$news[]=$row;
	}
	?>

表单格式(php套用html)

<?php foreach($news as $k => $new):?>
<tr>
    <td><?php echo $k+1;?></td>
    <td><?php echo $new['title'];?></td>
    <td><?php echo date('Y年m月d天i分s秒',$new['pub_time']);?></td>
    <td><?php echo $new['isTop']==1?'是':'否';?></td>
    <td><input type='text' id='title' value="<?php echo $new['title'];?>"</td>
</tr>

HTTP协议

Request Header

Host:主机地址
User-Agent:浏览器类型
Connection:连接情况

POST方式的内容:
......

响应消息

相应行:
200 OK
400 语法错误
401 请求未授权
403 禁止服务
404 没有找到相应文件
500 服务器发生错误
503 服务器相应不及时
Date:time
Server:服务器
Content-Length:字节数
Content-Type:数据格式

响应体
......

http响应设置

<?php
	//立即重定向,直接跳转
	header('Localtion:1.php');
	//延迟重定向,等待具体时间后进行
	header('Refresh:3;url=1.php');
	//文件下载
	header('Content-disposition:attachment;filename=test.php');
	?>

用curl模拟http连接

<?php
	header('Content-type:text/html;charset=utf-8');
	//开启会话
	$ch=curl_init();
	//设置连接选项
	curl_setopt($ch,CURLOPT_URL,'url');
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	curl_setopt($ch,CURLOPT_Header,1);
	
	//post方式
	curl_setopt($ch,CURLOPT_POST,TRUE);
	curl_setopt($ch,CURLOPT_POSTFIELDS,array());
	
	//执行
	$content = curl_exec($ch);
	
	//关闭资源
	curl_close($ch);
	?>

文件编程

目录操作

<?php
	//创建目录,@抑制错误
	$res = @mkdir('dir_name');
	//删除目录
	@rmdir('dir_name');
	//读取目录
	$res = opendir('name');
	//遍历结果
	while($file=readdir($res))
	{
		echo $file,'<br/>';
	}
	//关闭资源
	closedir($res);
	//其它函数
	dirname('path');	//得到文件当前目录
	realpath('path');	//得到全部路径,只能用于文件夹
	scandir('dir_name');//直接得到所有的文件,opendir+readdir。
	?>

递归文件

<?php
	$dir = './uploads';
	//创建函数能访问全部的文件
	function scan($dir)
	{
		//保证文件安全
		if(!is_dir($dir)){
			dir($dir);
		}
		$files = scandir($dir);
		foreach($files as $file){
			if($file=='.'||$file=='..')	continue;
			//构造文件
			$file_dir = $dir.'/'.$file;
			echo $file_dir.<br/>;
			if(is_dir($file_dir))	scan($file_dir);
		}
	}
	?>

文件操作

<?php
    $file='content.txt';
	$text="helloword";
	$res=file_put_contents($file,$text);	//写入
	$ret=file_get_contents($file);	//读取
	$f=fopen($file,'w||a');	//w会覆盖原内容
	$tmp=fread($f,len);
	fwrite($f,'text');
	fclose($f);
?>

其它函数

is_file()	//文件是否正确
filesize()	//文件大小
file_exists()	//文件是否存在
fgetc()		//获取一个字符
fgets()		//获取一行

文件下载

<?php
	header('Content-type:text/html;charset=utf-8');
	$file = 'path';
	//以文件流形式传输数据
	header('Content-type:application/octem-stream');
	//返回计算大小
	header('Accept-ranges:bytes');
	//附件下载
	header('Content-disposition:attachment;filename='.$file);
	//输出文件大小
	header('Accept-length:'.filesize($file));
	//如果为中文命名要调整格式:$file=iconv('GBK','UTF-8',$file);
	//文件较小时:
	echo file_get_contents($file);
	//文件大时:
	$f=@fopen($file,'r') or die();
	while($row=fread($f,1024))
	{
		echo $row;
	}
	fclose($f);
	?>

cookie是用户本机浏览器上的小文件数据内容,在访问服务器的时候会把cookie上交给服务器,对应的cookie拥有自己的生命周期,权限范围。可以把它理解为身份证的用途。当然第一次的时候服务器会把cookie交给用户。

cookie的基本使用:

<?php
    //setcookie(name,digit,time(时间戳),作用范围(文件),域名
    //cookie只能传数据和字符串,time默认浏览器关闭
    setcookie('a1',1,time()+24*60*60,'/',baidu.com);
    ?>

cookie的伪数组:

<?php
    setcookie('a1[0]',0);
	setcookie('a1[1]',1);
	setcookie('a1[2]',2);
	setcookie('a1[3]',3);
	print($_COOKIE);
?>

SESSION(跨脚本)

原理图:

)

基本使用:

$_session是通过session_start()函数调用产生的。

<?php
    //开启session,跨脚本的实现
    session_start();
	//设置session数据
	$_session['name']='aaa';
	$_session['thing']=array('1','2','3');
	//清除session
	unset($_session['name']);
	$_session=array();	//直接赋值清空
?>

基本配置(php.ini中):

session.name:session名字
session.auto_start:是否自动开启
session.save_handler:session保存方式
session.save_path:session文件存储位置
session.cookie_lifetime:cookie的生命周期,默认浏览器关闭
session.cookie_path:cookie的作用范围,默认为'/'
session.cookie_domain:是否可以跨子域

销毁session(删除文件):

<?php
    session_start();
	sleep(5);x
	session_destory();
?>

垃圾回收:

当session文件较长的时候,会形成残留僵尸文件,我们要进行删除。

禁用cookie使用session:

1.利用session函数直接去获取session_id和session_name来更改

2.用url直接将数据传递给另一个脚本,接收脚本为:

<?php
    $name=session_name();
	$id=$_GET[$name];
	session_id($id);
	session_start();
	?>

3.修改配置文件,开启其它的方式去实现session



文章作者: Dydong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Dydong !
  目录