戻る

その他のファイル操作

ディレクトリ(フォルダ)の作成

mkdir()関数の構文

		TRUE/FALSE = mkdir(ディレクトリ名[,パーミッション(デフォルト:0777)]);

		bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )

例:

<?php
header("Content-type: text/html; charset=utf-8");

$folder = "test";

if(!file_exists($folder)){
	mkdir($folder,0755);
}

if(file_exists($folder)){
	echo "フォルダ作成";
}
else{
	echo "フォルダ作成失敗";
}

$filename = $folder . "/" . date("H") . ".txt";
?>

パーミッションとは

UNIXでは、ファイルやディレクトリには、下記に挙げるユーザがあります。各ユーザがファイルやディレクトリに対して、「読む」「書く」「実行する」のいずれを行えるかのアクセス権を「パーミッション」と呼びます。パーミッションを指定するには、「rw-r--r--」や「755」などと英字や数字で指定することができます。PHPスクリプトでパーミッションを記述する場合、数字のパーミッションを指定し、また必ず先頭にゼロ(0)を追加し、「777」の場合は「0777」と記述します。

ユーザの種類名称
ファイル/ディレクトリの所有者Owner
そのPCを利用できるユーザGroup
その他のすべてのユーザOther

英字数値内容
r4「読む」の許可
w2「書く」の許可
x1「実行」の許可
-0許可しない

rwx r-x r-x (755)数値ユーザ
rwx (最初の3文字)4+2+1=7Owner
r-x (真ん中の3文字)4+0+1=5Group
r-x (末尾の3文字)4+0+1=5Other

パーミッション例 数値 内容
rwx r-x r-x 755 所有者は「読む」「書く」「実行」ができる、それ以外のユーザは「読む」「実行」のみ
rwx rwx rwx 777 すべてのユーザが「読む」「書く」「実行」ができる

ディレクトリ(フォルダ)の削除

rmdir()関数の構文

		TRUE/FALSE = rmdir("ディレクトリ名");

		bool rmdir ( string $dirname [, resource $context ] )

ファイルサイズの取得

filesize()関数の構文

		ファイルのサイズ(バイト) = filesize(ファイル名);

		int filesize ( string $filename )

例:

<?php
header("Content-type: text/html; charset=utf-8");

$filename = "11.txt";

echo "このファイルのファイルサイズは" . filesize($filename) . "バイトです";
?>

ファイルの更新時刻

filemtime()関数の構文

		ファイルの更新時刻 = filemtime(ファイル名);

		int filemtime ( string $filename )

例:

<?php
header("Content-type: text/html; charset=utf-8");

$filename = "11.txt";

echo "このファイルの更新時刻は" . date("Y/m/d H:i:s",filemtime($filename)) . "バイトです";
?>

ファイルのコピー

copy()関数の構文

		copy(コピー元ファイル,コピー先ファイル);

		bool copy ( string $source , string $dest [, resource $context ] )

例;

<?php
header("Content-type: text/html; charset=utf-8");

$filename = "11.txt";

copy($filename,"abcde.txt");

if(file_exists("abcde.txt")){
	echo "COPY成功";
}
else{
	echo "COPY失敗";
}
?>

ファイルの削除

unlink()関数の構文

		unlink(ファイル名);

		bool unlink ( string $filename [, resource $context ] )

例;

<?php
header("Content-type: text/html; charset=utf-8");

$filename = "abcde.txt";

if(file_exists($filename)){
	unlink($filename);
}

if(!file_exists($filename)){
	echo "unlink成功";
}
else{
	echo "unlink失敗";
}
?>

ファイル名の変更

rename()関数の構文

		rename(元ファイル名,変更後のファイル名);

		bool rename ( string $oldname , string $newname [, resource $context ] )

例;

<?php
header("Content-type: text/html; charset=utf-8");

$filename = "11.txt";

rename($filename,"abcde.txt");

if(file_exists("abcde.txt")){
	echo "rename成功";
}
else{
	echo "rename失敗";
}
?>

inserted by FC2 system