关于http协议的理解

时间:2023-03-09 14:30:23
关于http协议的理解

一.状态码

1.200:请求成功。

2.302:浏览器进行重定向。

3.304:资源已使用,即有缓存。

4.404:请求失败,请求的资源未在服务器上发现。

5.500:服务器端发生错误。

二.php获取http内容

$_SERVER中比较重要的属性

$_SERVER['REMOTE_ADDR']:当前浏览器的IP地址

$_SERVER['DOCUMENT_ROOT']:获得Apach的主目录

$_SERVER['REQUEST_URL']:可以获得请求的资源名

$_SERVER['HTTP_REFERER']:页面的来源

三.防盗链

test.php
<?php if(isset($_SERVER['HTTP_REFERER'])) {//是否存在
if(strpos($_SERVER['HTTP_REFERER'], 'http://localhost/test') == 0) {//是否已http://localhost/test开头
echo "aaa";
}else {
header("Location: http://baidu.com/");//重定向
}
}else {
header("Location: http://baidu.com/");//重定向
}
?>

如果要访问test.php这个页面,来源需要以http://localhost/test开头。

四.重定向

一般重定向:header("Location: b.php");

控制一定时间去跳转 header("Reflash: 3;url=http://baidu.com");

五.控制缓存

header("Expire: -1");
header("Cache-Control: no-cache");
header("Pragma: no-cache");//三个均代表禁用缓存,兼容不同的浏览器

六.文件下载

<?php

function downFile($filename, $root) {
$file_name = $filename; //文件为中文名
$file_name = iconv("utf-8", "gb2312", $file_name); //绝对路径
$file_path = $_SERVER['DOCUMENT_ROOT'].$root.$file_name; if(!file_exists($file_path)) {
echo "文件不存在";
return;
} $fp = fopen($file_path, "r");
//计算文件的大小
$file_size = filesize($file_path); if($file_size > 10*1024*1024) {
echo "文件过大不下载";
return;
} header("Content-type: application/octet-stream");//返回的文件
header("Accept-Ranges: bytes");//按照字节大小返回
header("Accept-Length: $file_size");//返回文件的大小
header("Content-Disposition: attachment; filename=.$file_name");//客户端对应的文件名 //下载量为1024字节
$buffer = 1024; while(!feof($fp)) {
$file_data = fread($fp, $buffer);
echo $file_data;
} fclose($fp);
} downFile("啊啊.jpg", "test/img/");//封装函数
?>

源码下载,将其放在www目录下。

七.乱码解决方案

<meta http-equiv = "content-type" content="text/html;charset=utf-8"/>
<?php
header("Content-Type: text/html; charset=utf-8");
?>