(七)文件——PHP

第七章 文件

1 文件包含

您可以在服务器执行PHP文件之前将其内容包含到另一个PHP文件中。有两个PHP函数可用于将一个PHP文件包含到另一个PHP中。

  • include()函数

  • require()函数

1.1 include()函数

include()函数获取指定文件中的所有文本,并将其复制到使用includ函数的文件中。如果加载文件时出现任何问题,则include()函数将生成警告,但脚本将继续执行。

<?php 
	//	main.php
	//	This is a main file
	include("header.php");
	echo "This is an example to show how to include php file";
 ?>
      
 
<?php 
	// header.php
	// The file is the included php file
	echo '<a href="www.baidu.com">百度</a>&emsp;' ;
	echo '<a href="www.sina.com">新浪</a>&emsp;';
	echo '<a href="www.qq.com">腾讯</a><br>';
	
 ?>
1.2 require()函数

require()函数获取指定文件中的所有文本,并将其复制到使用include函数的文件中。如果加载文件时出现任何问题,那么require()函数将生成致命错误并停止脚本的执行。

因此,require()和include()除了处理错误条件之外没有区别。建议使用require()函数而不是include(),因为如果文件丢失或命名错误,脚本不应继续执行。

<?php 
	//	main.php
	//	This is a main file
	require("unknown.php");  // 通过包含一个不存在的文件,可以发现include()函数和require()函数的区别
	echo "This is an example to show how to include php file";
 ?>
<?php 
	// header.php
	// The file is the included php file
	echo '<a href="www.baidu.com">百度</a>&emsp;' ;
	echo '<a href="www.sina.com">新浪</a>&emsp;';
	echo '<a href="www.qq.com">腾讯</a><br>';
 ?>

2 文件的读取和写入

fopen()函数用于打开文件。它需要两个参数,首先说明文件名,然后说明操作模式。

对打开的文件进行更改后,使用fclose()函数关闭它很重要。fclose()函数需要一个文件指针作为参数,然后在关闭成功时返回true,如果失败则返回false。

2.1 文件模式
ModePurpose
r以只读方式打开文件。
r+打开文件进行读取和写入
w打开文件仅写入。
将文件指针放在文件的开头。
并将文件截断为零长度。如果文件没有存在,然后尝试创建文件。
w+打开文件仅用于读取和写入。
将文件指针放在文件的开头。
并将文件截断为零长度。如果文件没有存在,然后尝试创建文件
a仅打开文件进行写入。
将文件指针放在文件的末尾。
如果文件不存在,则会尝试创建文件。
a+打开文件仅用于读取和写入。
将文件指针放在文件的末尾。
如果文件不存在,则会尝试创建文件
2.2 文件读取

下面是用PHP读取文件所需的步骤。

  • 使用fopen()函数打开文件。

  • 使用filesize()函数获取文件的长度。

  • 使用fread()函数读取文件的内容。

  • 使用fclose()函数关闭文件。

<?php 
	//	main.php
	$filename = "testFile.txt";
	$file = fopen($filename, "r");
	if($file == null){
		echo "Error in opening file";
		exit();
	}
	$filesize = filesize($filename);
	$filecontent = fread($file, $filesize);
	fclose($file);
	echo "File size:".$filesize." bytes.";
	echo "<br>";
	echo "File content:".$filecontent;
 ?>
// testFile.txt
This is the content to be read!
2.3 文件写入

fwrite()函数写入新文件或将文本附加到现有文件。此函数需要两个参数来指定文件指针和要写入的数据字符串。除此之外,可以包括第三个整数参数来指定要写入的数据的长度。如果包含第三个参数,则在达到指定长度后将停止写入。

//	写
<?php 
	$filename = "testFile.txt";
	$file = fopen($filename, "w");
	if($file == null){
		echo "error in opening file";
		exit();
	}
	$filecontent = "This is what I want to write";
	fwrite($file, $filecontent);
	fclose($file);

 ?>


//	读
<?php 
	//	main.php
	$filename = "testFile.txt";
	$file = fopen($filename, "r");
	if($file == null){
		echo "Error in opening file";
		exit();
	}
	$filesize = filesize($filename);
	$filecontent = fread($file, $filesize);
	fclose($file);
	echo "File size:".$filesize." bytes.";
	echo "<br>";
	echo "File content:".$filecontent;
 ?>

3 文件上传

PHP脚本可以与HTML表单一起使用,以允许用户将文件上传到服务器。一开始,文件被上传到临时目录,然后通过PHP脚本重新定位到目标位置。

通常,在写入文件时,临时位置和最终位置都必须设置允许文件写入的权限。如果其中一个设置为只读,则进程将失败。

上传的文件可以是文本文件图像文件任何文档

上传文件的过程遵循以下步骤:

  • 用户打开包含HTML表单的页面,该表单包含文本文件、浏览按钮和提交按钮。
  • 用户单击浏览按钮并选择要从本地PC上传的文件。
  • 选定文件的完整路径显示在文本字段中,然后用户单击提交按钮。
  • 选定的文件将发送到服务器上的临时目录。
  • 表单的action属性中指定为表单处理程序的PHP脚本会检查文件是否已到达,然后将文件复制到预期目录中。
  • PHP脚本向用户确认成功。
3.1 创建表单
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
      <form action="" method="post" enctype="multipart/form-data">
         <input type="file" name="image"><br>
         <input type="submit" name="submit">
      </form>
</body>
</html>
3.2 创建脚本

$_FILES是PHP的全局变量,这个变量是一个关联的二维数组,保存与上传文件相关的所有信息
例如,如果上传表单中输入的name属性值file,那么PHP将创建以下五个变量:

  • **$_FILES[ ‘file’ ] [ ‘tmp_name’ ]**− web服务器上临时目录中的临时文件
  • $_FILES[ ‘file’ ] [ ‘name’ ] − 上传文件的实际文件名
  • $_FILES[ ‘file’ ] [ ‘size’ ] − 上传文件的字节数
  • $_FILES[ ‘file’ ] [ ‘type’ ] − 上传文件的MIME类型
  • $_FILES[ ‘file’ ] [ ‘error’ ] − 与上传文件关联的错误代码
<?php 
   error_reporting(0);
   if (isset($_FILES['image'])) {                  // 判断name属性值是否是'image'
         $file_tmp = $_FILES['image']['tmp_name']; // 获取临时目录中的临时文件
         $file_name = $_FILES['image']['name'];    // 获取上传文件的实际文件名
         $file_size = $_FILES['image']['size'];    // 获取上传文件的字节大小
         $file_type = $_FILES['image']['type'];    // 获取上传文件的MIME类型
         $file_ext = strtolower(end(explode(".", $_FILES['image']['name'])));
         /*
            explode():以‘.’作为分割符,将字符串转化为数组
            end():获取数组最后一个元素
            strtolower():将全部字符变为小写

            $file_ext:获取文件名后缀
         */

         $errors = array();                       // 用于存储错误信息
         $extensions = array("jpg","jpeg","png"); // 标记文件扩展名 


         // 判断$file_ext是否存在指定的文件扩展名数组中
         if (in_array($file_ext, $extensions) == false) {
            $errors[] = "extension not allowed";
         }

         // 判断文件字节大小是否超过5MB
         if($file_size > 5098152){
            $errors[] = "it must be exactly 5MB";
         }

         // 判断$errors数组是否为空
         if (empty($errors) == true) {

            // 如果errors数组为空,即可将临时文件上传到指定位置
            move_uploaded_file($file_tmp, "images".$file_name);
         }else {

            // 如果errors数组不为空,则打印$errors数组中信息
            print_r($errors);
         }
   }
 ?>
3.3 实例
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body bgcolor="pink">
      <form action="" method="post" enctype="multipart/form-data">
         <input type="file" name="image"><br>
         <input type="submit" name="submit">
      </form>
      <ul>
         <li>临时目录中的临时文件:<?php echo $_FILES['image']['tmp_name'] ?></li>
         <li>实际文件名:<?php echo $_FILES['image']['name'] ?></li>
         <li>文件字节大小:<?php echo $_FILES['image']['size'] ?></li>
         <li>文件类型:<?php echo $_FILES['image']['type'] ?></li>
      </ul>
</body>
</html>

    
<?php 
   error_reporting(0);
   if (isset($_FILES['image'])) {                  // 判断name属性值是否是'image'
         $file_tmp = $_FILES['image']['tmp_name']; // 获取临时目录中的临时文件
         $file_name = $_FILES['image']['name'];    // 获取上传文件的实际文件名
         $file_size = $_FILES['image']['size'];    // 获取上传文件的字节大小
         $file_type = $_FILES['image']['type'];    // 获取上传文件的MIME类型
         $file_ext = strtolower(end(explode(".", $_FILES['image']['name'])));
         /*
            explode():以‘.’作为分割符,将字符串转化为数组
            end():获取数组最后一个元素
            strtolower():将全部字符变为小写

            $file_ext:获取文件名后缀
         */

         $errors = array();                       // 用于存储错误信息
         $extensions = array("jpg","jpeg","png"); // 标记文件扩展名 


         // 判断$file_ext是否存在指定的文件扩展名数组中
         if (in_array($file_ext, $extensions) == false) {
            $errors[] = "extension not allowed";
         }

         // 判断文件字节大小是否超过5MB
         if($file_size > 5098152){
            $errors[] = "it must be exactly 5MB";
         }

         // 判断$errors数组是否为空
         if (empty($errors) == true) {

            // 如果errors数组为空,即可将临时文件上传到指定位置
            move_uploaded_file($file_tmp, "images".$file_name);
         }else {

            // 如果errors数组不为空,则打印$errors数组中信息
            print_r($errors);
         }
   }
 ?>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来得晚一些也行

观众老爷,请赏~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值