php中的DirectoryIterator跟RecursiveDirectoryIterator
php中的DirectoryIterator和RecursiveDirectoryIterator
php中,可以用用DirectoryIterator获取指定目录的文件或者目录.
$path = "/tmp"; $oDir = new DirectoryIterator($path); foreach($oDir as $file) { if($file->isfile()) { $tmpFile['link'] = $file->getPath(); $tmpFile['name'] = $file->getFileName(); $tmpFile['type'] = 'file'; $tmpFile['size'] = _cal_size($file->getSize()); $tmpFile['mtime'] = $file->getMTime(); $arrFile[] = $tmpFile; } } print_r($arrFile); /* output Array ( [0] => Array ( [link] => /tmp [name] => scim-panel-socket-:0-root [type] => dir [size] => 0b [mtime] => 1222049895 ) [1] => Array ( [link] => /tmp [name] => .font-unix [type] => dir [size] => 4k [mtime] => 1241417372 ) ) */
RecursiveDirectoryIterator 获取目录下所有的文件,包括子目录 ,其中搭配:
RecursiveIteratorIterator使用.
(RecursiveIteratorIterator是个递归迭代器,其后可选带四个参数(只能任一)
RecursiveIteratorIterator::LEAVES_ONLY
默认,已在__construct中设定使用
作用是去枝留叶,跳过空节点,只递归取实值
举例就是
1.递归文件夹取文件时跳过文件夹本身,只取文件夹下面的文件,输出的项全部是file(文件和各级子文件夹的文件)
2.多维数组就跳过前几维的key,而取value,输出的每一项都不是array
3.XML只取值(text),不输出节点名,当然还要视乎你设定获取xml什么内容
RecursiveIteratorIterator::SELF_FIRST
各项都包含,例如递归文件夹就会连同子文件夹名称也作为其中项输出,顺序是先父后子
RecursiveIteratorIterator::CHILD_FIRST
同上,但顺序是先子后父,./test/test.php会在./test(文件夹)前面)
$path = "/tmp/";
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $object)
{
$tmpFile['link'] = $object->getPath();
$tmpFile['name'] = $object->getFileName();
$tmpFile['type'] = $object->isFile() ? 'file' : 'dir';
$tmpFile['size'] = _cal_size($object->getSize());
$tmpFile['mtime'] = $object->getMTime();
$arrFile[] = $tmpFile;
}
print_r($arrFile);
/*
output:
Array
(
[0] => Array
(
[link] => /tmp
[name] => scim-panel-socket-:0-root
[type] => dir
[size] => 0b
[mtime] => 1222049895
)
[1] => Array
(
[link] => /tmp/.font-unix
[name] => fs7100
[type] => dir
[size] => 0b
[mtime] => 1241417372
)
)
*/
再来看个例子:
/*** the target directory, no trailling slash ***/
$directory = './';
try
{
/*** check if we have a valid directory ***/
if( !is_dir($directory) )
{
throw new Exception('Directory does not exist!'."\n");
}
/*** check if we have permission to rename the files ***/
if( !is_writable( $directory ))
{
throw new Exception('You do not have renaming permissions!'."\n");
}
/**
*
* @collapse white space
*
* @param string $string
*
* @return string
*
*/
function collapseWhiteSpace($string)
{
return preg_replace('/\s+/', ' ', $string);
}
/**
* @convert file names to nice names
*
* @param string $filename
*
* @return string
*
*/
function safe_names($filename)
{
$filename = collapseWhiteSpace($filename);
$filename = str_replace(' ', '-', $filename);
$filename = preg_replace('/[^a-z0-9-.]/i','',$filename);
return strtolower($filename);
}
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, 0));
/*** loop directly over the object ***/
while($it->valid())
{
/*** check if value is a directory ***/
if(!$it->isDot())
{
if(!is_writable($directory.'/'.$it->getSubPathName()))
{
echo 'Permission Denied: '.$directory.'/'.$it->getSubPathName()."\n";
}
else
{
/*** the old file name ***/
$old_file = $directory.'/'.$it->getSubPathName();
/*** the new file name ***/
$new_file = $directory.'/'.$it->getSubPath().'/'.safe_names($it->current());
/*** rename the file ***/
rename ($old_file, $new_file);
/*** a little message to say file is converted ***/
echo 'Renamed '. $directory.'/'.$it->getSubPathName() ."\n";
}
}
/*** move to the next iteration ***/
$it->next();
}
/*** when we are all done let the user know ***/
echo 'Renaming of files complete'."\n";
}
catch(Exception $e)
{
echo $e->getMessage()."\n";
}
?>

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
