Simple interaction between PHP and server file system
php.ini中关于文件上传的设置指令
文件上传过程
(1)上传文件提交表单html代码:
<!--向服务器上传文件的HTML表单(限制为文本文件)--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Adminstration - upoload new files</title> </head> <body> <h1>Upload new files</h1> <form action="upload.php" method="post" enctyple="multipart/form-data" > <!--enctyple:规定在发送到服务器之前对表单数据进行编码的方式(在上传控件时必须按照以上方式设置该属性)--> <div> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <!--规定传输文件的最大字节数--> <label for="userfile">Upload a file</label> <!--在<label>内点击文本,会触发该控件,此时浏览器会自动对焦到标签for属性所指向的表单控件上面--> <input type="file" name="userfile" id="userfile"> <!--id属性为<label>标签for所指向控件元素的id号--> <input type="submit" value="Send File"> </div> </form> </body> </html>
(2)php处理上传文件代码
①在php脚本中,需要处理的数据保存在超级变量数组$_FILES中,开启register_globals指令可以直接通过变量名访问这些信息;
②假如表单变量名为“username“则有:
$_FILES['userfile']['tmp_name']:储存文件在Web服务器中的临时保存位置;
$_FILES['userfile']['name']:储存用户系统中文件的名称;
$_FILES['userfile']['size']:储存文件的大小;
$_FILES['userfile']['type']:储存文件的类型;
$_FILES['userfile']['error]:储存任何与文件上传相关的错误代码;
错误类型说明:
UPLOAD_ERR_INI_SIZE:1,上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
UPLOAD_ERR_FORM_SIZE:2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
UPLOAD_ERR_PARTIAL:3,文件只有部分被上传。
UPLOAD_ERR_NO_FILE:4,没有文件被上传。
UPLOAD_ERR_NO_TMP_DIR:6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。
UPLOAD_ERR_CANT_WRITE:7,文件写入失败。PHP 5.1.0 引进。
③php代码
<?php //检验文件传输异常 if($_FILES['userfile']['error']>0){ echo 'Problem'; switch($_FILES['userfile']['error']){ case 1: echo 'File exceeded upload_max_filesize';break; case 2: echo 'File exceeded max_file_size';break; case 3: echo 'File only partially upload';break; case 4: echo 'No file uploaded';break; case 6: echo 'Cannot upload file: No temp directory specified';break; case 7: echo 'Upload failed:Cannot write to disk';break; } exit; } //检验传输的文件是否为文本文件 if($_FILES['userfile']['type'] != 'text/plain'){ echo 'Problem: file is not plain text'; exit; } //将上传文件包含在服务器中/uploads/的目录下(该目录必须独立于Web文档树) $upfile = '/uploads/'.$_FILES['userfile']['name']; //在指定目录下以传输文件的文件名创建一个新文件 if(is_uploaded_file($_FILES['userfile']['tmp_name'])){ if(! move_uploaded_file($_FILES['userfile']['tmp_name'],$upfile)){ //将传输文件的临时文件移动到创建的新文件 echo 'Problem: Could not move file to destination directory'; exit; } } else{ echo 'Problem: Possible file upload attack.Filename:'; echo $_FILES['username']['name']; exit; } echo "File uploaded seuucessfully<br/><br/>"; //对传输文件清除html和php标记 $contents = file_get_contents($upfile); //将文件内容提取为一个字符串; $contents = strip_tags($contents); //对该字符串擦除html和tags标记; file_put_contents($_FILES['userfile']['name'],$contents); //将该字符串重新写入文件中; //在浏览器上显示传输的文本文件内容 echo "<p>Preview of uploaded file contents:<br/><hr>>"; echo nl2br($contents); echo "</br></hr>";
3、使用目录函数
(1)从目录中读取文件名
①使用opendir(),readdir(),closedir()函数;
<?php $current_dir = '/uploads/'; //创建目录url对象 $dir = opendir($current_dir); //打开目录,结果返回一个目录对象 echo "<p>Upload directory is $current_dir</p>"; echo "<p>Directory Listing:</p><ul>"; while(($file = readdir($dir)) !== false){ //读取目录对象 if($file != "." && $file != ".."){ //过滤当前目录和上一级目录 echo "<li>$file</li>"; echo "<a href=\"filedetails.php?file=\'.$file.\'\">".$file."</a><br/>"; } } echo "</ul>"; closedir($dir); //关闭目录; ?>
②使用php的dir类
<?php $current_dir = '/uploads/'; //创建目录url对象 $dir = dir($current_dir); //创建dir对象 echo "<p>Handle is $dir->handle</p>"; echo "<p>Upload directory is $current_dir</p>"; echo "<p>Directory Listing:</p><ul>"; while(($file = $dir->read()) !== false){ //通过dir对象读取目录下的文件名 if($file != "." && $file != ".."){ echo "<li>$file</li>"; } } echo "</ul>"; $dir->close(); //关闭目录 ?>
(2)使用scandir()函数对文本名称进行字母表的排序方式
<?php $current_dir = '/uploads/'; //创建目录url对象 $files1 = scandir($current_dir); //将指定目录下的文件名保存为一个数组,默认以字母升序排序 $files2 = scandir($current_dir,1); //将指定目录下的文件名保存为一个数组,以字母降序排序 echo "<p>Upload directory is $current_dir</p>"; echo "<p>Directory Listing in alphabetical order,ascending:</p><ul>"; foreach($files1 as $file1) { if($file1 != "." && $file1 != "..") echo "<li>$file1</li>"; } echo "</ul>"; ?>
(3)获取当前目录的其他信息
dirname($path):返回路径的目录部分;
basename($path):返回路径的名称部分;
disk_free_space($path):返回路径所在磁盘可以保存上传文件的容量;
(4)创建和删除目录
①mkdir():创建目录;
代码:
$oldumask = umask(0); //重置当前权限码 mkdir("/tmp/testing",0777); //创建目录 umask($oldumask); //恢复当前权限码
②rmdir():删除目录;
代码:
rmdir("/temp/testing"); 或rmdir("c:\\tmp\\testing');
※要删除的目录必须是空目录;
4、与文件系统的交互
(1)获取文件信息:
while(($file = readdir($dir)) !== false){ echo "<a href=\"filedetails.php?file=\'.$file.\'\">".$file."</a><br/>"; } <?php $current_dir = '/uploads/'; $file = basename($file); //获取文件文件名 echo "<h1>Details of file</h1>"; echo "<h2>File data</h2>"; echo 'File last accessed: '.date('j F Y H:i',fileatime($file))."<br>"; //返回最近访问的时间戳 echo 'File last modifixed: '.date('j F Y H:i',filemtime($file))."<br>"; //返回最近修改的时间戳 $user = posix_getpwuid(fileowner($file)); //返回用户标识uid echo 'File owner: '.$user['name']."<br/>"; $group = posix_getgrgid(filegroup($file)); //返回组织标识gid echo 'File group: '.$group['name']."<br/>"; echo 'File permissions: '.decoct(fileperms($file))."<br/>"; //返回8位的权限码 echo 'File type'.filetype($file)."<br/>"; //返回文件类型 echo 'File size'.filesize($file)."<br/>"; //返回文件字节数 echo "<h2>File Tests</h2>"; echo 'is_dir?'.(is_dir($file) ? 'true':'false')."<br/>"; echo 'is_executable?'.(is_executable($file) ? 'true':'false')."<br/>"; //判断文件是否可执行; echo 'is_file?'.(is_file($file) ? 'true':'false')."<br/>"; echo 'is_link?'.(is_link($file) ? 'true':'false')."<br/>"; echo 'is_readable?'.(is_readable($file) ? 'true':'false')."<br/>"; echo 'is_writable?'.(is_writable($file) ? 'true':'false')."<br/>"; ?>
(2)更改文件属性
chgrp(file,group):修改文件的分组;
chmod(file,permissions):修改文件的权限;
chown(file,user):修改文件的所有者;
(3)创建、删除和移动文件
bool touch($filename,[int time,[ int atime]]):创建一个文件(time指定创建时间戳,atime指定可选时间戳)
unlink($filename):删除一个文件
copy($source_path,$destination_path):复制一个文件
rename($oldfile,$newfile):重命名一个文件;
(4)使用程序执行函数
①String exec(String command[ ,array result [ ,int result_value]])
返回命名结果的最后一行,result变量可以返回字符组数,这些字符串代表输出的每一行,result_value获取返回代码;
②void passthru(String command[ ,int result_value])
结果直接输出到浏览器;
③String system(string command[ ,int return_value])
输出结果到浏览器,返回命令结果的最后一行或false;
※在用户提交的数据包括执行命令的一部分,应该进行以下包装:
system(escapeshellcmd($command));
5、与环境变量交互
phpinfo()函数:获取php的所有变量列表;
getenv("$key_name"):
setenv("$key_name=$value");

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
