【PHP】ファイル・ディレクトリの扱い方

ファイル

存在有無

file_exists($fileName)

コピー

copy(【ファイル元】, 【ファイル先】);

サンプル

<?php
	$sourceFilePath = "./dataFile.txt";
	$depatureFilePath = "./backUp/dataFile.txt";
	
	if (file_exists($sourceFilePath )) {
		copy($sourceFilePath, $depatureFilePath);
	}
	header("LOCATION:main.php");
?>

ファイル削除

unlink(【削除するファイル】);

サンプル

* 指定したディレクトリ内のファイルを一括削除する
<?php
$id = $_GET["id"];

$rootPath = "./images/" . $id;
DeleteFiles($rootPath);

echo "Finished...<br />";

function DeleteFiles($rootPath)
{
	echo "Path : " . $rootPath . "<br />";
	
	if (!file_exists($rootPath))
	{
		echo "!!<br />";
		return;
	}
	
	if ($handle = opendir($rootPath))
	{
		while (false !== ($file = readdir($handle)))
		{
			echo "File : " . $file . "<br />";
			$deletedFilePath = $rootPath . '/' . $file;
			if (is_file($deletedFilePath))
			{
				echo "Delete File : " . $deletedFilePath . "<br />";
				unlink($deletedFilePath);
			}
		}
		
		closedir($handle);
	}
}
?>

参考資料

http://www.phppro.jp/phpmanual/php/function.readdir.html