Blog スタッフブログ

PHP システム開発

[PHP]特定ディレクトリ内のファイルのランダム読み込み

システム開発担当のTFです。

やり方

  • glob関数で、特定ディレクトリ内のファイル名全てを配列に格納する
  • shuffle関数で、ランダムに並び変える
  • 配列の先頭を読み込む

サンプル

<?php
	// testディレクトリ内のファイル名一覧の取得
	$files = glob("test/*.*");
	
	// ランダムに並び変える
	shuffle($files);
	
	if( !isset($files[0]) ) exit;
	
	// ファイルの中身取得し返す
	ob_start();
	
	include( $files[0] );
	
	$content = ob_get_clean();
	print( $content );

?>

Warning: Undefined array key 0 in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3

Warning: Attempt to read property "cat_ID" on null in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3