Home Backend Development PHP Tutorial How to implement file management and basic function operations in PHP

How to implement file management and basic function operations in PHP

May 24, 2018 pm 04:43 PM
php Function Base

这篇文章通过实例代码给大家讲解了php文件管理与基础功能的实现,非常不错,具有参考借鉴价值,需要的朋友参考下

文件的基本操作

先来看一下PHP文件基础操作,请看强大注释

<body>
<?php
var_dump(filetype("./img/11.png"));
//判断返回得是文件还是目录,返回sile为文件,dir为目录(文件夹)
var_dump(is_dir("./img/11.png"));
//判断给的文件是不是一个目录,目录为ture,文件为false
var_dump(is_file("./img"));
//判断是否为文件,同上
var_dump(date("Y-m-d H:i:s",fileatime("./img/11.png")));
//上次访问时间
var_dump(date("Y-m-d H:i:s",filectime("./img/11.png")));
//创建时间
var_dump(date("Y-m-d H:i:s",filemtime("./img/11.png")));
//修改时间
var_dump(filesize("./img/11.png"));
//获取文件大小
var_dump(file_exists("/QQPCMgr/www/wenjian/img/22.png"));
//在php里面根/则是磁盘
echo $_SERVER[&#39;DOCUMENT_ROOT&#39;];
//获取到服务器根路径
echo basename("/QQPCMgr/www/wenjian/img/22.png");
//返回22.png带后缀的文件名
echo basename("/QQPCMgr/www/wenjian/img/22.png",".png");
//扔上后缀之后只显示文件名(获取文件名)
echo dirname("/QQPCMgr/www/wenjian/img/22.png");
//返回的是不包含文件名的路径(获取文件名以上的)
var_dump(pathinfo("/QQPCMgr/www/wenjian/img/22.png"));
//这个获取的很全面,都能获取到
echo realpath("./img/11.png");
//真实路径:可以把相对路径转换为绝对路径
var_dump(glob("./ce/*"));
//取到这个文件夹里所有的文件,加后缀为条件
 ?>
<!--<img src="/wenjian/img/11.png" />-->
<!--在网页里根/代表的是www目录-->
</body>
Copy after login

文件整体操作:

<?php
//touch("./11.txt");
//创建文件
//copy("11.txt","./ce/11.txt");
//复制文件
//unlink("./11.txt");
//删除文件
//echo file_get_contents("./ce/11.txt");本地
//echo file_get_contents("http://www.baidu.com");远程
//读取文件所有内容
//file_put_contents("./11.txt","Myshao");
//往文件里面存储内容
//readfile("./11.txt");
//读取并输出
//$arr = file("./shouye.php");
//var_dump($arr);
//读取文件内所有内容,并扔到数组显示
//$ff = fopen("./11.txt","a");
//打开文件资源,详情见注1;
//echo fgetc($ff);
//读取一个字符
//echo fgets($ff);
//读取一行字符
//echo fread($ff,2);
//规定读多长
//fwrite($ff,"shao");
//写入内容
Copy after login

注1:打开和读取文件

php使用fopen()函数的方式,语法结构如下

Resource fopen (string $filename,string $mode) Filename是目标文件名,打开本地文件也可以打开远程文件,打开远程文件需要采用http://...形式,假如目标文件在

ftp服务器上,则采用形式ftp://...。

参数mode是目标文件打开形式,参数$mode是可以接收的模式。

文件打开方式表:

目录资源的打开与关闭:但凡有开就有关,否则会影响到后面的删除等操作;

<?php
$fname = "./ce/gf";
$d = opendir($fname);
//打开文件资源
while ($url = readdir($d))
{
 echo $fname."/".$url."<br/>";
// 仅读取文件名,把路径拼上=完整路径
}
var_dump(glob("./*"));
closedir($d);
//关资源
Copy after login

以上就是一些基础的语句了,来做点练习:

例:返回一个文件夹下的所有文件数量;

如果想要计算出ajax目录下有多少的文件,可以用下面封装的方法shu()来遍历目录,可以计算出ce目录下其他的文件夹里面的文件的总和,

<?php
function shu($url)
{
 $sl = 0;
 $arr = glob($url);
 //循环遍历
 foreach($arr as $v)
 {
  //判断是不是一个文件
  if(is_file($v))
  {
   //如果是一个文件+1
   $sl++;
  }
  else
  {
   $sl +=shu($v."/*");
  }
 }
 return $sl;
}
echo shu("./ce/*");
//最后给方法一个路径进行查找
?>
Copy after login

看一下输出:

再来一个!

例:删除文件

<?php
$fname = "./ce/gf";
$d = opendir($fname);
//打开文件资源
while ($url = readdir($d))
{
 echo $fname."/".$url."<br/>";
// 仅读取文件名,把路径拼上=完整路径
}
var_dump(glob("./*"));
closedir($d);
//关资源
//删除文件夹(非空文件夹)
function shan($url)
{
// 清空文件夹
 $d = opendir($url);
// 打开
 while ($u = readdir($d))//$u现在是文件名
 {
//  排除...
  if($u!="." && $u!="..")
  {
   $fname = $url . "/" . $u;
   //完整带路径的文件名
   if (is_file($fname))//如果是一个文件
   {
    unlink($fname);
   } else //如果是一个文件夹
   {
    shan($fname);
   }
  }
 }
 closedir($d);
 //关闭
 rmdir($url);
}
shan("./122");
?>
Copy after login

这样122目录里面所有的东西,不管是文件夹还是文件都会被删除;

实现文件管理功能

1.先把查看文件的功能做出来,让他把所有的文件与文件夹啊显示出来;

<body>
<?php
//定义文件目录
$fname = "./ce";
//便利目录下的所有文件显示
$arr = glob($fname."/*");
foreach ($arr as $v)
{
 //从完整路径中取文件名
 $name = basename($v);
 echo "<p class=&#39;item&#39; url=&#39;{$v}&#39;>{$name}</p>";
}
?>
</body>
Copy after login

图:

接下来给文件夹特殊显示一下把:

输出之前需要判断,判断是不是一个文件夹:

//从完整路径中取文件名
 $name = basename($v);
 if(is_dir($v)){
  echo "<p class=&#39;item dir&#39; url=&#39;{$v}&#39;>{$name}</p>";
 }
 else {
  echo "<p class=&#39;item&#39; url=&#39;{$v}&#39;>{$name}</p>";
 }
Copy after login

如果是个文件夹,给他背景颜色改变一下就好啦

图:

2.给文件夹添加双击事件:

双击实现进入这个目录;

js代码:

<script>
 $(".dir").dblclick(function(){
  var url = $(this).attr("url");
  $.ajax({
   url:"chuli.php",
   data:{url:url},
   type:"POST",
   dataType:"TEXT",
   success:function(data)
   {
    window.location.href="wenwen.php" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ;

   }

  });
 })
</script>
Copy after login

处理页面:

<?php
session_start();
$url = $_POST["url"];
$_SESSION["fname"] = $url;
Copy after login
Copy after login


这样就可以实现双击进入此文件夹:

3.返回上一级,找到上一级目录,写个p

$pname = dirname($fname);
echo "<p id=&#39;shang&#39; url=&#39;{$pname}&#39;>返回上一级</p>";
Copy after login

图:

写双击事件:

<script>
 $("#shang").dblclick(function(){
  var url = $(this).attr("url");
  $.ajax({
   url:"chuli.php",
   data:{url:url},
   type:"POST",
   dataType:"TEXT",
   success:function(data)
   {
    window.location.href="wenwen.php" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ;
   }
  });
 })
</script>
Copy after login

返回到文件目录后使其隐藏:

//上一级的目录
$pname = dirname($fname);
if(realpath($fname)=="F:\\QQPCMgr\\WWW\\wenjian")
{}
else {
 echo "<p id=&#39;shang&#39; url=&#39;{$pname}&#39;>返回上一级</p>";
}
Copy after login

这样的话当我返回到wenjian目录的时候,使其隐藏:

4.删除功能

在文件p里面加删除按钮:

 echo "<p class=&#39;item&#39; url=&#39;{$v}&#39;>{$name}
<input type=&#39;button&#39; value=&#39;删除&#39; url=&#39;{$v}&#39; class=&#39;sc&#39;/>
</p>";
Copy after login


来写按钮的点击事件:

js代码:

$(".sc").click(function(){
   //确认删除提示
   var av = confirm("确定要删除");
   if(av){
   var url = $(this).attr("url");
   $.ajax({
    url: "shan.php",
    data: {url: url},
    type: "POST",
    dataType: "TEXT",
    success: function (data) {
     window.location.href = "wenwen.php";
    }

   });
   }
  })
Copy after login

删除的处理页面:

<?php
$url = $_POST["url"];
unlink($url);
Copy after login
Copy after login

这样完成后,当我点击删除:

再点击确定,即可删除

总代码:

管理查看页面:




 
 无标题文档
 
 


{$name}

"; } else { echo "

{$name}

"; } } ?> <script> $(".dir").dblclick(function(){ var url = $(this).attr("url"); $.ajax({ url:"chuli.php", data:{url:url}, type:"POST", dataType:"TEXT", success:function(data) { window.location.href="wenwen.php" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ; } }); }) $("#shang").dblclick(function(){ var url = $(this).attr("url"); $.ajax({ url:"chuli.php", data:{url:url}, type:"POST", dataType:"TEXT", success:function(data) { window.location.href="wenwen.php" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ; } }); }) $(".sc").click(function(){ //确认删除提示 var av = confirm("确定要删除"); if(av){ var url = $(this).attr("url"); $.ajax({ url: "shan.php", data: {url: url}, type: "POST", dataType: "TEXT", success: function (data) { window.location.href = "wenwen.php"; } }); } }) </script>
Copy after login

处理:

<?php
session_start();
$url = $_POST["url"];
$_SESSION["fname"] = $url;
Copy after login
Copy after login

删除:

<?php
$url = $_POST["url"];
unlink($url);
Copy after login
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

php传值方式和ajax实现验证功能的方法

地图搜租房功能实现

How to implement message boardfunction in php

##

The above is the detailed content of How to implement file management and basic function operations in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles