php之readdir函数用法实例(php readdir函数)
25-02-19
17
针对php之readdir函数用法实例和phpreaddir函数这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展4个php遍历函数opendir()、readdir()、closedir()
针对php之readdir函数用法实例 和php readdir函数 这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展4个php遍历函数opendir()、readdir()、closedir()、rewinddir()用法实例汇总、C/C++的readdir和readdir_r函数(遍历目录)、php header函数用法、PHP header函数用法举例 等相关知识,希望可以帮助到你。
本文目录一览:
php之readdir函数用法实例(php readdir函数) 《:PHP之readdir函数用法实例》要点: 本文介绍了:PHP之readdir函数用法实例,希望对您有用。如果有疑问,可以联系我们。
PHP学习 本文实例讲述了PHP中readdir函数用法.分享给大家供大家参考.具体用法分析如下:
定义和用法:readdir() 函数返回由 opendir() 打开的目录句柄中的条目,若成功,则该函数返回一个文件名,否则返回 false.
实例一,代码如下:
代码如下:
$dir = "readdir/";
// 判断是否为目录
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . " ";
}
closedir($dh);
}
}
实例二,
注意在 4.0.0-RC2 之前不存在 !== 运算符, 代码如下:
代码如下:
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle ";
echo "Files: ";
/* 这是正确地遍历目录办法 */
while (false !== ($file = readdir($handle))) {
echo "$file ";
}
/* 这是错误地遍历目录的办法 */
while ($file = readdir($handle)) {
echo "$file ";
}
closedir($handle);
}
实例三,readdir() 将会返回 . 和 .. 条目,如果不想要它们,只要过滤掉即可,例子 2. 列出当前目录的所有文件并去掉 . 和 ..,代码如下:
代码如下:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file ";
}
}
closedir($handle);
}
注:
readdir必须与opendir配合使用才行.
希望本文所述对大家的PHP程序设计有所帮助.
小编培训学院每天发布《:PHP之readdir函数用法实例》等实战技能,PHP、MysqL、LINUX、APP、JS,CSS全面培养人才。
4个php遍历函数opendir()、readdir()、closedir()、rewinddir()用法实例汇总 这篇文章主要介绍了php遍历目录函数opendir()、readdir()、closedir()、rewinddir()总结,并给出了一个综合使用这些函数的例子做了一个简易文件浏览器,需要的朋友可以参考下
在进行PHP编程时,需要对服务器某个目录下面的文件进行浏览,通常成为遍历目录。取得一个目录下的文件和子目录,就需要用到opendir()函数、readdir()函数、closedir()函数和rewinddir()函数。
①函数opendir()
函数opendir()用于打开指定目录,接受一个目录的路径及目录名作为参数,函数返回值为可供其他目录函数使用的目录句柄(资源类型)。如果该目录不存在或者没有访问权限,则返回FALSE。
②函数readdir()
立即学习 “PHP免费学习笔记(深入)”;
函数readdir()用于读取指定目录,接受已经用opendir()函数打开的可操作目录句柄作为参数,函数返回当前目录指针位置的一个文件名,并将目录指针向后移动一位。当指针位于目录的结尾时,因为没有文件存在则返回FALSE。
③函数closedir()
函数closedir()关闭指定目录,接受已经用opendir()函数打开的可操作目录句柄作为参数。函数无返回值,运行后关闭打开的目录。
④函数rewinddir()
函数reweinddir()倒回目录句柄,接受已经用opendir()函数打开的可操作目录句柄作为参数。将目录指针重置目录到开始处,即倒回目录的开头。
下面用一个实例来说明以上几个函数的使用方法。注意,在使用该例子前请确保同意目录下有phpMyAdmin文件夹。代码如下所示:
代码如下:
<?php
$num = 0; //用来统计子目录和文件的个数
$dirname = 'phpMyAdmin'; //保存当前目录下用来便利的一个目录名
$dir_handle = opendir($dirname); //用opendir打开目录
//将遍历的目录和文件名使用表格格式输出
echo '<table border="0" align="center" width="600" cellspacing="0" cellpadding="0">';
echo '<caption><h2>目录'.$dirname.'下面的内容</h2></caption>';
echo '<tr align="left" bgcolor="#cccccc">';
echo '<th>文件名</th><th>文件大小</th><th>文件类型</th><th>修改时间</th>';
//使用readdir循环读取目录里的内容
while($file = readdir($dir_handle)){
//将将目录下的文件和当前目录连接起来,才能在程序中使用
$dirFile = $dirname."/".$file;
$bgcolor = $num+%2==0 ? '#FFFFFF' : '#CCCCCC'; //各行一种颜色
echo '<tr bgcolor='.$bgcolor.'>';
echo '<td>'.
filesize
($dirFile).'</td>'; //显示文件名
echo '<td>'.
filetype
($dirFile).'</td>'; //显示文件大小
echo '<td>'.date("Y/n/t",
filemtime
($dirFile)).'</td>'; //格式化显示文件修改时间
echo '</tr>';
}
echo '</table>';
closedir($dir_handle); //关闭文件操作句柄
echo '在<b>'.$dirname.'</b>目录下的子目录和文件共有<b>'.$num.'</b>个';
?> 登录后复制
上述程序首先打开一个目录指针,并对其进行遍历。遍历目录时,会包括“.”和“..”两个特殊的目录,如果不需要这俩个目录,可以将其屏蔽。当然显示细节会因为文件夹中内容的不同而有所不同。通过上例可见,在PHP中浏览文件夹中的内容也并不是一件多么复杂的事情。而且PHP还提供了一种面向对象的方式用于目录的遍历,通过使用“dir”类完成。不仅如此,PHP也可以按用户的要求检索目录下指定的内容,提供了glob()函数检索指定的目录。该函数最终返回一个包含检索结果的数组。
以上就是4个php遍历函数opendir()、readdir()、closedir()、rewinddir()用法实例汇总的详细内容,更多请关注php中文网其它相关文章!
C/C++的readdir和readdir_r函数(遍历目录) 1.首先要打开目录文件
DIR *opendir( const char *name);
DIR *fdopendir( int fd);
2.读取目录文件信息的函数
注意:这是个库函数
struct dirent *readdir( DIR *dirp);
int readdir_r( DIR *dirp, struct dirent *entry, struct dirent **result);
文件目录结构体:
struct dirent {
ino_t d_ino; /* inode number 索引节点号*/
off_t d_off; /* not an offset; see NOTES 在目录文件中的偏移*/
unsigned short d_reclen; /* length of this record 文件名长*/
unsigned char d_type; /*type of file; not supported by all filesystem types 文件类型*/
char d_name[256]; /* filename 文件名,最长255字符*/
};
d_type的值为:
DT_BLK This is a block device.
DT_CHR This is a character device.
DT_DIR This is a directory.
DT_FIFO This is a named pipe (FIFO).
DT_LNK This is a symbolic link.
DT_REG This is a regular file.
DT_SOCK This is a UNIX domain socket.
DT_UNKNowN The file type is unkNown.
readdir()函数实例:
注意:
每次使用readdir后,readdir会读到下一个文件,readdir是依次读出目录中的所有文件,每次只能读一个
这个特性和readdir_r()一样
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc,char **argv)
{
DIR *pDir = NULL;
struct dirent * pEnt = NULL;
unsigned int cnt = 0;
if (argc != 2)
{
printf("usage: %s dirname\n",argv[0]);
return -1;
}
pDir = opendir(argv[1]);
if (NULL == pDir)
{
perror("opendir");
return -1;
}
while (1)
{
pEnt = readdir(pDir);
if(pEnt != NULL)
{
if (pEnt->d_type == DT_REG)
{
printf("是普通文件:");
}
else
{
printf("不是普通文件:");
}
printf("name:[%s] \n",pEnt->d_name);
cnt++;
}
else
{
break;
}
};
printf("总文件数为:%d\n",cnt);
return 0;
}
结果:
$ ./a.out .
是普通文件:name:[a.c]
不是普通文件:name:[.]
不是普通文件:name:[..]
是普通文件:name:[a.out]
不是普通文件:name:[12_sr]
不是普通文件:name:[10_sr]
不是普通文件:name:[17_sr]
不是普通文件:name:[15_sr]
不是普通文件:name:[14.sr]
不是普通文件:name:[18_sr]
不是普通文件:name:[udp]
不是普通文件:name:[16_sr]
不是普通文件:name:[tcp]
总文件数为:13
C++
#include <iostream>
#include <string>
using namespace std;
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <dirent.h>
void search(string commonXmlPath){
{
string ectPath = commonXmlPath;
string subdistrictXmlPath;
DIR* dir_pointer = opendir(ectPath.c_str());
if (!dir_pointer)
return;
for (dirent* dp = readdir(dir_pointer); dp != NULL; dp = readdir(dir_pointer))
{
std::string filename = dp->d_name;
if (filename == "." || filename == "..")
{
continue;
}
if (dp->d_type == 8)//?录镁
{
int split = filename.find('.');
if (split == -1)
continue;
string pp = ectPath + filename;
cout << pp.c_str() <<"\n";
}
if(dp->d_type == 4)//目录拢卢?么录?酶碌梅 {
//每赂枚募镁录?路戮露
subdistrictXmlPath = ectPath + string("/") + dp->d_name;
search(subdistrictXmlPath);
}
}
//closedir(dir_pointer);
}
int main(){
search(string("/data/home/android/configserver/common_xmls/etc"));
return 0;
}
readdir_r():
注意:
这三个参数
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
DIR *pDir = NULL;
struct dirent * pEnt = NULL;
struct dirent *entry = (struct dirent *)malloc(sizeof(struct dirent));
struct dirent **result = (struct dirent **)malloc(sizeof(struct dirent));
unsigned int cnt = 0;
unsigned int ret = 0;
if (argc != 2)
{
printf("usage: %s dirname\n",argv[0]);
return -1;
}
pDir = opendir(argv[1]);
if (NULL == pDir)
{
perror("opendir");
return -1;
}
ret = readdir_r(pDir,entry,result);
printf("return :%d \n",ret);
printf("name :[%s] \n",entry->d_name);
printf("name :[%s] \n",result[0]->d_name);
ret = readdir_r(pDir,result[0]->d_name);
return 0;
}
结果:
本文分享几个php header函数的例子,有需要的朋友参考学习下。
转自:
http://www.jbxue.com/article/php_header_x5hV63c.html
1,可以使用heder命令,强制使浏览器使用新鲜的内容(无缓存) 。 也可以给网址增加了一个唯一的编号,使其每次都读取新的内容,避免缓存。 例子:
复制代码 代码示例:
<? print“<img src=’yourfile.jpg’>”; //通常读取的是缓存文件 ?> <? print“<img src=’yourfile.jpg?”.time().“‘>”; //增加了唯一的编号,使浏览器重新请求
w//print“<img src=’yourfile.jpg?”.rand(100,999).“‘>”; ?>
2,自定义php函数,将图片传送给浏览器显示。
复制代码 代码示例:
<?php
function PE_img_by_path($PE_imgpath = “”)
{
if (file_exists($PE_imgpath)) {
$PE_imgarray = pathinfo($PE_imgpath);
$iconcontent = file_get_contents($PE_imgpath);
header(“Content-type: image/” . $PE_imgarray["extension"]);
header(‘Content-length: ‘ . strlen($iconcontent));
echo $iconcontent;
die(0);
}
return false;
}
?>
更多实例:
复制代码 代码示例:
<?php
// ok
header(‘HTTP/1.1 200 OK’);
//设置一个404头:
header(‘HTTP/1.1 404 Not Found’);
//设置地址被永久的重定向
header(‘HTTP/1.1 301 Moved Permanently’);
//转到一个新地址
header(‘Location: http://www.jbxue.com/’);
//文件延迟转向:
header(‘Refresh: 10; url=http://www.jbxue.com/’);
print ‘You will be redirected in 10 seconds’;
//当然,也可以使用html语法实现
// <meta http-equiv=”refresh” content=”10;http://www.jbxue.com/ />
// override X-Powered-By: PHP:
header(‘X-Powered-By: PHP/4.4.0′);
header(‘X-Powered-By: Brain/0.6b’);
//文档语言
header(‘Content-language: en’);
//告诉浏览器最后一次修改时间
$time = time() – 60; // or filemtime($fn), etc
header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’, $time).’ GMT’);
//告诉浏览器文档内容没有发生改变
header(‘HTTP/1.1 304 Not Modified’);
//设置内容长度
header(‘Content-Length: 1234′);
//设置为一个下载类型
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=”example.zip”‘);
header(‘Content-Transfer-Encoding: binary’);
// load the file to send:
readfile(‘example.zip’);
// 对当前文档禁用缓存
header(‘Cache-Control: no-cache, no-store, max-age=0, must-ridate’);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’); // Date in the past
header(‘Pragma: no-cache’);
//设置内容类型:
header(‘Content-Type: text/html; charset=iso-8859-1′);
header(‘Content-Type: text/html; charset=utf-8′);
header(‘Content-Type: text/plain’); //纯文本格式
header(‘Content-Type: image/jpeg’); //JPG图片
header(‘Content-Type: application/zip’); // ZIP文件
header(‘Content-Type: application/pdf’); // PDF文件
header(‘Content-Type: audio/mpeg’); // 音频文件
header(‘Content-Type: application/x-shockwave-flash’); //Flash动画
//显示登陆对话框
header(‘HTTP/1.1 401 Unauthorized’);
header(‘WWW-Authenticate: Basic realm=”Top Secret”‘);
print ‘Text that will be displayed if the user hits cancel or ‘;
print ‘enters wrong login data’;
?>
Header(“Location: http://bbs.it-home.org”;);
exit; //在每个重定向之后都必须加上“exit”,避免发生错误后,继续执行。
?>
header(“refresh:3;url=http://bbs.it-home.org”);
print(‘正在加载,请稍等… 三秒后自动跳转~~~’);
header重定向 就等价于替用户在地址栏输入url
?>
复制代码
例2,禁止页面在IE中缓存
header(''Expires: Mon, 26 Jul 1997 05:00:00 GMT'');
header(''Last-Modified: ''.gmdate(''D, d M Y H:i:s'') .'' GMT'');
header(''Cache-Control: no-store, no-cache, must-ridate'');
header(''Cache-Control: post-check=0, pre-check=0'',false);
header(''Pragma: no-cache'');//兼容http1.0和https
?>
CacheControl = no-cache
Pragma=no-cache
Expires = -1
复制代码
说明:
如果服务器上的网页经常变化,就把Expires设置为-1,表示立即过期。
如果一个网页每天凌晨1点更新,可以把Expires设置为第二天的凌晨1点。
当HTTP1.1服务器指定CacheControl = no-cache时,浏览器就不会缓存该网页。
旧式 HTTP 1.0 服务器不能使用 Cache-Control 标题。所以为了向后兼容 HTTP 1.0 服务器,IE使用Pragma:no-cache 标题对 HTTP 提供特殊支持。
如果客户端通过安全连接 (https://) 与服务器通讯,且服务器在响应中返回 Pragma:no-cache 标题,则 Internet Explorer 不会缓存此响应。
注意:
Pragma:no-cache 仅当在安全连接中使用时才防止缓存,如果在非安全页中使用,处理方式与 Expires:-1 相同,该页将被缓存,但被标记为立即过期。
http-equiv meta标记:
在html页面中可以用http-equiv meta来标记指定的http消息头部。
老版本的IE可能不支持html meta标记,所以最好使用http消息头部来禁用缓存。
例3,让使用者的浏览器出现找不到档案的信息。
网上资料显示:php的函数header()可以向浏览器发送Status标头,
例如:
header(”Status: 404 Not Found”)
复制代码
。
实际上浏览器返回的响应却是:
header(”http/1.1 404 Not Found”);
复制代码
第一部分为HTTP协议的版本(HTTP-Version);
第二部分为状态代码(Status);
第三部分为原因短语(Reason-Phrase)。
例4,让使用者下载档案( 隐藏文件的位置 )
html标签 就可以实现普通文件下载。
如果为了保密文件,就不能把文件链接告诉别人,可以用header函数实现文件下载。
header(“Content-type: application/x-gzip”);
header(“Content-Disposition: attachment; filename=文件名”);
header(“Content-Description: PHP3 Generated Data”);
?>
复制代码
例5 ,header函数前输入内容
一般来说在header函数前不能输出html内容,类似的还有setcookie() 和 session 函数,这些函数需要在输出流中增加消息头部信息。
如果在header()执行之前有echo等语句,当后面遇到header()时,就会报出 “Warning: Cannot modify header information – headers already sent by ….”错误。
在这些函数的前面不能有任何文字、空行、回车等,而且最好在header()函数后加上exit()函数。
例如,以下的错误写法,在两个 php代码段之间有一个空行:
//some code here
?>
//这里应该是一个空行
header(”http/1.1 403 Forbidden”);
exit();
?>
复制代码
原因分析:
PHP脚本开始执行 时,它可以同时发送http消息头部(标题)信息和主体信息。
http消息头部(来自 header() 或 SetCookie() 函数)并不会立即发送,相反,它被保存到一个列表中。
如此,即可允许修改标题信息,包括缺省的标题(例如 Content-Type 标题)。
但是,一旦脚本发送了任何非标题的输出(例如,使用 HTML 或 print() 调用),那么PHP就必须先发送完所有的Header,然后终止 HTTP header。
而后继续发送主体数据,从这时开始,任何添加或修改Header信息的试图都是不允许的,并会发送上述的错误消息之一。
解决办法:
修改php.ini打开缓存(output_buffering),或者在程序中使用缓存函数ob_start(),ob_end_flush() 等。
原理分析:
output_buffering被启用时,在脚本发送输出时,PHP并不发送HTTP header。
相反,它将此输出通过管道(pipe)输入到动态增加的缓存中(只能在PHP 4.0中使用,它具有中央化的输出机制)。
可以修改/添加header,或者设置cookie,因为header实际上并没有发送。
当全部脚本终止时,PHP将自动发送HTTP header到浏览器,然后再发送输出缓冲中的内容。
附,其它一些有关php header函数的例子。
// ok
header(‘HTTP/1.1 200 OK’);
//设置一个404头:
header(‘HTTP/1.1 404 Not Found’);
//设置地址被永久的重定向
header(‘HTTP/1.1 301 Moved Permanently’);
//转到一个新地址
header(‘Location: http://bbs.it-home.org/’);
//文件延迟转向:
header(‘Refresh: 10; url=http://bbs.it-home.org/’);
print ‘You will be redirected in 10 seconds’;
//当然,也可以使用html语法实现
//
// override X-Powered-By: PHP:
header(‘X-Powered-By: PHP/4.4.0′);
header(‘X-Powered-By: Brain/0.6b’);
//文档语言
header(‘Content-language: en’);
//告诉浏览器最后一次修改时间
$time = time() – 60; // or filemtime($fn), etc
header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’, $time).’ GMT’);
//告诉浏览器文档内容没有发生改变
header(‘HTTP/1.1 304 Not Modified’);
//设置内容长度
header(‘Content-Length: 1234′);
//设置为一个下载类型
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=”example.zip”‘);
header(‘Content-Transfer-Encoding: binary’);
// load the file to send:
readfile(‘example.zip’);
// 对当前文档禁用缓存
header(‘Cache-Control: no-cache, no-store, max-age=0, must-ridate’);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’); // Date in the past
header(‘Pragma: no-cache’);
//设置内容类型:
header(‘Content-Type: text/html; charset=iso-8859-1′);
header(‘Content-Type: text/html; charset=utf-8′);
header(‘Content-Type: text/plain’); //纯文本格式
header(‘Content-Type: image/jpeg’); //JPG图片
header(‘Content-Type: application/zip’); // ZIP文件
header(‘Content-Type: application/pdf’); // PDF文件
header(‘Content-Type: audio/mpeg’); // 音频文件
header(‘Content-Type: application/x-shockwave-flash’); //Flash动画
//显示登陆对话框
header(‘HTTP/1.1 401 Unauthorized’);
header(‘WWW-Authenticate: Basic realm=”Top Secret”‘);
print ‘Text that will be displayed if the user hits cancel or ‘;
print ‘enters wrong login data’;
?>
复制代码
我们今天的关于php之readdir函数用法实例 和php readdir函数 的分享就到这里,谢谢您的阅读,如果想了解更多关于4个php遍历函数opendir()、readdir()、closedir()、rewinddir()用法实例汇总、C/C++的readdir和readdir_r函数(遍历目录)、php header函数用法、PHP header函数用法举例 的相关信息,可以在本站进行搜索。