-
PHP > les dossiers et fichiers
- Don’t use
$fileLineByLine[$key] = "";
instead of
unset($fileLineByLine[$key]);
because the first case doesn’t remove the line, it just clears the line (and an unwanted empty line will remain). In that case, implode() adds a new line also for $fileLineByLine[$key] which is empty; otherwise if you unset a variable, it will unavailable (and implode() can not find it).
DOSSIERS
Lister les fichiers d’un dossier
$dir = 'chemin/dossier'; $files = scandir($dir); natsort($files); arsort($files); foreach ( $files as $var ){ if ( is_dir ( $dir.'/'.$var ) ){ if ( $var != '.' ){ if ( ( $dir == './uploads' ) && ( $var != '..' ) ){ $IDdir = str_replace( "/", "_", $var ) ; echo $dir.'/'.$var; } } }else{ echo $var; } }
Classer des fichiers par date de modification
while ($file = readdir($handler)) { if ($file != "." && $file != ".." && $file != '.svn') { $results[] = array('file' => $file, 'time' => filemtime($file)); } }
informations sur un fichier
stat( fichier )
devvolume
inoNuméro d’inode
modedroit d’accès à l’inode
nlinknombre de liens
uiduserid du propriétaire
gidgroupid du propriétaire
rdevtype du volume, si le volume est une inode
sizetaille en octets
atimedate de dernier accès (Unix timestamp)
mtimedate de dernière modification (Unix timestamp)
ctimedate de dernier changement d’inode (Unix timestamp)
blksizetaille de bloc
blocksnombre de blocs de 512 octets allouésNOTE : peut retourner des résultats étranges pour les fichiers de taille supérieure à 2 Go.
<?php $stat = stat('C:\php\php.exe'); echo 'Date et heure d\'accès : ' . $stat['atime']; echo 'Date et heure de modification : ' . $stat['mtime']; echo 'Numéro du Device : ' . $stat['dev']; ?>
<?php $stat = stat('C:\php\php.exe'); * Nous voulons que la date et heure d'accès soit d'une semaine après la date courante. $atime = $stat['atime'] + 604800; touch('some_file.txt', time(), $atime)) ?>
Connaitre la taille d’un dossier
<?php function dir_size($dir){ $handle = opendir($dir); while ($file = readdir($handle)) { if ($file != '..' && $file != '.' && !is_dir($dir.'/'.$file)) { $mas += filesize($dir.'/'.$file); } else if (is_dir($dir.'/'.$file) && $file != '..' && $file != '.') { $mas += dir_size($dir.'/'.$file); } } return $mas; } echo dir_size('DIRECTORIO').' Bytes'; ?>
FICHIERS
AJOUTER DU TEXTE A LA FIN DU FICHIER
$txt = "user id date"; $myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
SUPPRIMER UNE LIGNE D’UN FICHIER
$contents = file_get_contents($fichiere); $contents = str_replace('texte de la ligne à effacer', '\n', $contents); file_put_contents($fichier, $contents);
$DELETE = "texte de la ligne à effacer"; $data = file("./foo.txt"); $out = array(); foreach($data as $line){ if(trim($line) != $DELETE) { $out[] = $line; } } $fp = fopen("./foo.txt", "w+"); flock($fp, LOCK_EX); foreach($out as $line){ fwrite($fp, $line); } flock($fp, LOCK_UN); fclose($fp);
function remove_line($file, $remove){ $lines = file($file, FILE_IGNORE_NEW_LINES); foreach($lines as $key => $line){ if($line === $remove) unset($lines[$key]); } $data = implode(PHP_EOL, $lines); file_put_contents($file, $data); }
This is also good if you’re looking for a substring (ID) in a line and want to replace the old line with the a new line.
$contents = file_get_contents($dir); $new_contents= ""; if( strpos($contents, $id) !== false) { // if file contains ID $contents_array = preg_split("/\\r\\n|\\r|\\n/", $contents); foreach ($contents_array as &$record) { // for each line if (strpos($record, $id) !== false) { // if we have found the correct line pass; // we've found the line to delete - so don't add it to the new contents. }else{ $new_contents .= $record . "\r"; // not the correct line, so we keep it } } file_put_contents($dir, $new_contents); // save the records to the file echo json_encode("Successfully updated record!"); } else{ echo json_encode("failed - user ID ". $id ." doesn't exist!"); }
Like this:
file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename)));
First, get all lines of the file (the following codes can be compressed):
$file = @fopen($dir, 'r'); # As you said, $dir is your filename if ($file) { # Ending bracket is at the end if (filesize($dir)) { # Checks whether the file size is not zero (we know file exists) $fileContent = fread($file, filesize($dir)); # Reads all of the file fclose($file); } else { // File is empty exit; # Stops the execution (also you can throw an exception) } $fileLineByLine = explode(PHP_EOL, $fileContent); # Divides the file line by line
Here, you can perform your search:
$key = false; # By default, your string $line is not in the file (false) foreach ($fileLineByLine as $lineNumber => $thisLine) if ($thisLine === $line) $key = $lineNumber; # If $line found in file, set $key to this line number
Simply, you can remove line $key + 1:
if ($key !== false) # If string $line found in the file unset($fileLineByLine[$key]); # Remove line $key + 1 (e.g. $key = 2, line 3)
At last, you must save your changes to the file:
$newFileContent = implode(PHP_EOL, $fileLineByLine); # Joins the lines together $file = fopen($dir, "w"); # Clears the file if ($file) { fwrite($file, $newFileContent); # Saves new content fclose($file); } } # Ends 'if ($file) {' above
Also you can set above code as a function.
NOTE : $line must not have new line characters like \n. You must remove them:
$line = str_replace(PHP_EOL, '', $line);
—
Delete Line From File
Here we show how to take a file and a line number and delete that line from the file
<?php ### La fonction prend deux arguements, $fileName et $lineNum ### ### Exemple : supprimer la ligne 14 du fichier "fichier.txt" ### ### ### ### $fileName = "fichier.txt"; ### ### $lineNum = 14 ### ### delLineFromFile($fileName, $lineNum); ### ### Auteur Kevin Waterson kevin@phpro.org ### $fileName = "/chemin/fichier.txt"; $lineNum = 87; delLineFromFile($fileName, $lineNum);
function delLineFromFile($fileName, $lineNum){ // check the file exists if(!is_writable($fileName)){ print "Le fichier $fileName n'est pas writable"; exit; }else{ // read the file into an array $arr = file($fileName); } // the line to delete is the line number minus 1, because arrays begin at zero $lineToDelete = $lineNum-1; // check if the line to delete is greater than the length of the file if($lineToDelete > sizeof($arr)){ print "Vous avez choisi la ligne n°$lineNum, plus grand que le total de lignes."; exit; } //remove the line unset($arr["$lineToDelete"]); // open the file for reading if (!$fp = fopen($fileName, 'w+')){ print "Impossible d'ouvrir le fichier ($fileName)"; exit; } // if $fp is valid if($fp){ // write the array to the file foreach($arr as $line) { fwrite($fp,$line); } fclose($fp); } echo "terminé"; } ?>
—
- Don’t use