PHP unlink (delele ) multiple files on server - php

Sometimes, I have to delete multiple files in different folders on the server. It's a tedious job to to this one by one via FTP. I wrote a little script that does the job. I can import the list of files in Excel and copy and paste them in the script. However, my approach is not elegant:
$file1 = "some-file.php";
$file12 = "some-file2.php";
...
if (!empty($file1)) {
if ( #unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file1 ) )
{
echo 'The file <strong><span style="color:green;">' . $file1 . '</span></strong> was deleted!<br />';
}
else
{
echo 'Couldn't delete the file <strong><span style="color:red;">' . $file1 . '</span></strong>!<br />';
}}
if (!empty($file2)) { ...
I would rather like to do this with a foreach and an array, but don't know how. Any help would be appreciated!

Just put your files into an array and loop it.
$files = array('some-file.php', 'some-file2.php');
foreach ($files as $file) {
if ( #unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file ) ) {
echo 'The file <strong><span style="color:green;">' . $file . '</span></strong> was deleted!<br />';
} else {
echo 'Couldn\'t delete the file <strong><span style="color:red;">' . $file . '</span></strong>!<br />';
}
}

also, i think its better if you use file_exists()
if (file_exists($file1))
{
unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file1 );
clearstatcache();
}

Related

looping in file_get_content php and output the content of each file with filename

I m using this code to output content of files in a directory but I have two problems
first is that this directory contains sub-dir and this code doesn't output
files content in these sub-dir
Second problem
I want this code to output like
Filename:"name of the file"
Content :"content of the file"
so that I can parse this
$dir = new DirectoryIterator('./Chemistry');
foreach($dir as $file)
{
if(!$file->isDot() && $file->isFile() && strpos($file->getFilename(), '.md') !== false)
{
$content = file_get_contents($file->getPathname());
echo $content
}
}
?>
If I understand correct you want to output:
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
If this is not your intention I will require a more thorough explanation.
* edit *
For dir iteration use http://php.net/manual/en/function.scandir.php
From the top of my head it goes a little something like this (hit it)...
function loopDir($path) {
$allFilesAndFoldersInCurrentFolder = scandir($path);
foreach($allFilesAndFoldersInCurrentFolder as item) {
if(is_dir($item)) {
loopDir($path.'/'.$item);
}
else {
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
}
}
}

Extract a folder and then search for specific file in PHP

I´m building a php programm which uploads a zip file, extracts it and generates a link for a specific file in the extracted folder. Uploading and extracting the folder works fine. Now I´m a bit stuck what to do next. I have to adress the just extracted folder and find the (only) html file that is in it. Then a link to that file has to be generated.
Here is the code I´m using currently:
$zip = new ZipArchive();
if ($zip->open($_FILES['zip_to_upload']['name']) === TRUE)
{
$folderName = trim($zip->getNameIndex(0), '/');
$zip->extractTo(getcwd());
$zip->close();
}
else
{
echo 'Es gab einen Fehler beim Extrahieren der Datei';
}
$dir = getcwd();
$scandir = scandir($dir);
foreach ($scandir as $key => $value)
{
if (!in_array($value,array(".",".."))) //filter . and .. directory on linux-systems
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value) && $value == $folderName)
{
foreach (glob($value . "/*.html") as $filename) {
$htmlFiles[] = $filename; //this is for later use
echo "<a href='". SK_PICS_SRV . DIRECTORY_SEPARATOR . $filename . "'>" . SK_PICS_SRV . DIRECTORY_SEPARATOR . $filename . "</a>";
}
}
}
}
So this code seems to be working. I just noticed a rather strange problem. The $zip->getNameIndex[0] function behaves differently depending on the program that created the zip file. When I make a zip file with 7zip all seems to work without a problem. $folderName contains the right name of the main folder which I just extracted. For example "folder 01". But when I zip it with the normal windows zip programm the excat same folder (same structure and same containing files) the $zip->getNameIndex[0] contains the wrong value. For example something like "folder 01/images/" or "folder 01/example.html". So it seems to read the zip file differently/ in a wrong way. Do you guys know where that error comes from or how I can avoid it? This really seems strange to me.
Because you specify the extract-path by yourself you can try finding your file with php's function "glob"
have a look at the manual:
Glob
This function will return the name of the file matching the search pattern.
With your extract-path you now have your link to the file.
$dir = "../../suedkurier/werbung/"
$scandir = scandir($dir);
foreach ($scandir as $key => $value)
{
if (!in_array($value,array(".",".."))) //filter . and .. directory on linux-systems
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
foreach (glob($dir . DIRECTORY_SEPARATOR . $value . "/*.html") as $filename) {
$files[] = $value . DIRECTORY_SEPARATOR $filename;
}
}
}
}
The matched files will now be saved in the array $files (with the subfolder)
So you get your path like
foreach($files as $file){
echo $dir . DIRECTORY_SEPARATOR . $file;
}
$dir = "the/Directory/You/Extracted/To";
$files1 = scandir($dir);
foreach($files1 as $str)
{
if(strcmp(pathinfo($str, PATHINFO_EXTENSION),"html")===0||strcmp(pathinfo($str, PATHINFO_EXTENSION),"htm")===0)
{
echo $str;
}
}
Get an array of each file in the directory, check the extension of each one for htm/html, then echo the name if true.

Reading all file contents from a directory - php

This is actually is an easy task
I want to display contents of all files located in specified folder.
I am passing directory name
echo "<a href='see.php?qname=". $_name ."'>" . $row["qname"] . "</a>";
on second page ,
I am iterating over the directory content
while($entryname = readdir($myDirectory))
{
if(is_dir($entryname))
{
continue;
}
if($entryname=="." || $entryname==".." )
{}
else
{
if(!is_dir($entryname))
{
$fileHandle=fopen($entryname, "r");
while (!feof($fileHandle) ) {
$line = fgets($fileHandle);
echo $line . "<br />";
}
.
.
.
but I am unable to read any file , I have changed their permissions as well.
I tried putting directory name statically which worked,
Can someone suggest what am I doing wrong?
$entryname will contain JUST the filename, with no path information. You have to manually rebuild the path yourself. e.g.
$dh = opendir('/path/you/want/to/read/');
while($file = readdir($dh)) {
$contents = file_get_contents('/path/you/want/to/read/' . $file);
^^^^^^^^^^^^^^^^^^^^^^^^^^---include path here
}
Without the explicit path in your "read the file code", you're trying to open and read a file in the script's current working directory, not the director you're reading the filenames from.
Much simpler:
foreach(glob("$myDirectory/*") as $file) {
foreach(file($file) as $line) {
echo $line . "<br />";
}
}
Even simpler:
foreach(glob("$myDirectory/*") as $file) {
echo nl2br(file_get_contents($file));
}

PHP auto refresh

I am having some trouble coding a PHP script to update only when the value in a .txt file changes. What happens is that a VB form can change the value in the .txt file and the PHP script displays an image based on the value in the .txt file. Currently the script will show the updated files if I manually hit refresh on the browser, but I would like to eliminate that. I have tried using the meta refresh tag but because I am rendering images the page is very "jolty" when it refreshes every 2 or so seconds and makes viewing the page unbearable. What I have tried to do is create a loop between the $string and $string2 variables so that when they are not equal it redirects the page to a page that redirects back to this page and does a "back-door" refresh. $string is what is the direct value in the .txt file and it defined in the loop whereas $string2 is defined outside of the loop. I would the loop to see the difference between them once a different value is inputted to the .txt file.
Thank you all in advance.
<?php
{
$file=fopen("counter.txt","r");
$string=fgetc($file);
fclose($file);
}
$string2 = $string;
if ($string == '1') {
$files = glob('tg.jpg');
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}}
elseif ($string == '2') {
$files = glob('tr.jpg');
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}}
elseif ($string == '3') {
$files = glob('wua.jpg');
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}}
elseif ($string == '4') {
$files = glob('wur.jpg');
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}}
elseif ($string == '5') {
$files = glob('stop.jpg');
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}}
elseif ($string == '6') {
$files = glob('base.jpg');
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}}
while ($string == $string2) {
$file=fopen("counter.txt","r");
$string=fgetc($file);
echo $string;
fclose($file);
}
header('Location: redirect.php');
exit;
?>
PHP only runs in runtime, so there is no chance you can do what you just described.
Your best bet is to create a very small PHP script that does the check and have an AJAX script on the frontend check every second and update the image if PHP returns that it has been updated.
You are trying to use a server-side script to perform something on the client side.
Have your client page include a small Javascript snippet which posts back to your server to a script which can perform the check. Then, if your script indicates that a change had occured, refresh the page using Javascript.
That way, the page will only refresh when needed, and you can easily separate your client and server code.

Display Images From A Folder (slideshow) from external folder / URL

I have the code below
<?php
$directory = 'images/slideshow';
try {
// Styling for images
echo '<div id="myslides">';
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . '/' . $item;
echo '<img src="' . $path . '"/>';
}
}
echo '</div>';
}
catch(Exception $e) {
echo 'No images found for this slideshow.<br />';
}
?>
copied from this topic:
Display Images From A Folder (slideshow)
I would like to know if its possible to load the images externally instead, or from a specific directory of a URL? Thanks in advance.
It is possible, but you would need to know the urls of each photo. Though that would be easy if you can make them follow a certain pattern I.e. www.example.com/dir/photo1, www.example.com/dir/photo2.
The external server you point must allow remote linking as well.
Then it's just a matter of making the links:
for ($i = 1; $i < NUMBER_OF_PHOTOS; ++$i) {
echo '<img src="http://www.example.com/dir/photo'.$i.'"/>';
}

Categories