我知道windows和unix路径之间的函数realpath
的结果存在差异
我有这个功能用于创建一个zip,我不知道如何将它转换为在windows和unix上工作(现在只适用于unix)
function ZIP($source, $destination){
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true){
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file){
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..')))
continue;
$file = realpath($file);
if (is_dir($file) === true){
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file) === true){
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}else if (is_file($source) === true){
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
我认为DIRECTORY_SEPARATOR常量可以帮助转换
更新
这适用于windows和unix
function Zip($source, $destination){
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file));
}
else if (is_file($file) === true)
{
$str1 = str_replace($source . '/', '', '/'.$file);
$zip->addFromString($str1, file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}