I want to delete files from my local server that's running on my beaglebone.
I have created a page that displays all the files and lets you select the files to delete. (As you can see below)
The webpage returns the names of the files to delete in the form of an array to the php script unlink.php
The code for Unlink.php is:
<?php
$files = $_POST['file'];
print_r($files);
if (empty($files)) {
echo "No files were selected. Go back to 192.168.7.2 and refresh the page." ;
} else {
$N = count($files);
for ($i = 0; $i < $N; $i++) {
$path = '/Logs/';
print_r($path);
#chown($path, 666);
if (unlink($path . $_GET['$files[$i]'])) {
echo ": Deleted";
} else {
echo "fail";
}
}
}
?>
However, whenever I try to delete a file: It fails.
The unlink() php function isn't being implemented properly and I'm not sure why.
How do I do this the right way?
The index.html page is located in /var/www/html and the logs are located in /var/www/html/Logs/. The address of the local server is 192.168.7.2
Form code:
<?php
$url = $_SERVER['DOCUMENT_ROOT'];
$path = "/var/www/html/Logs";
$dh = opendir($path);
$k = 0;
$foo = True;
while (($file = readdir($dh)) !== false) {
if ($file != "." && $file != "..") {
if ($k == 0 || $k % 6 == 0) {
$col .= "<tr><td><input type='checkbox' name='file[]' value='$file'> <a href='Logs/$file'>$file</a><br /></td>";
} else if ($k % 6 == 5) {
$col .= "<td><input type='checkbox' name='file[]' value='$file'> <a href='Logs/$file'>$file</a><br /></td></tr>";
} else {
$col .= "<td><input type='checkbox' name='file[]' value='$file'> <a href='Logs/$file'>$file</a><br /></td>";
}
$k++;
}
}
echo "<form action='unlink.php' method='post'><table>$col</table><br/><center><input type='submit' name='formSubmit' value='Delete' /></center></form>";
closedir($dh);
?>
EDIT: PHP display-errors
Warning: chmod(): Operation not permitted in /var/www/html/unlink.php on line 17
chmod($path . $files[$i], 0755);
Warning: unlink(/var/www/html/Logs/2017.01.24--13.43.43--0.log): Permission denied in /var/www/html/unlink.php on line 18 fail
if (unlink($path . $files[$i]))
but when I check ls -la for /Logs -> it shows up as it belongs to www-data. How do I change the permissions beyond this?
Permissions:
<?php
$files = $_POST['file'];
$path = "/var/www/html/Logs/";
print_r($files);
if (empty($files)) {
echo "No files were selected. Go back to 192.168.7.2 and refresh the page." ;
} else {
foreach ($files as $file) {
if (unlink($path . $file)) {
echo $path. $file ." : Deleted";
} else {
echo $path. $file . " : fail";
}
}
}
?>
That should do it, $path was wrong, and even if you had used the same as in the other code, it was missing a slash.
Nonetheless this code is not going to prevent malicious user actions.
How to avoid UNLINK security risks in PHP?
From your updated question I can see that the Logs folder is a symlink to /media/card/Logs.
What is the output of ls -la /media/card?
Some further reads:
https://en.wikipedia.org/wiki/Symbolic_link
http://php.net/manual/en/control-structures.foreach.php
Make sure the file that you are trying to pass to unlink() / delete is not being opened. If the file is .exe or etc please also check in Windows Task Manager -> Process and then kill it.
Change permission status of file. Maybe you can't have access to delete the file (execute permission).
After you sure the file is not being opened 1, then lets try this code :
// Check existence of file
if (file_exists($cekFile1)) {
// make sure you have permission to delete file
if(chmod($fileDir, 0777)){
if(!unlink($cekFile1)){
echo "unlink is fail !";
}
}else{
echo "chmod is fail";
}
// owner have read, write, execute rights.
// owner's user group only have read rights.
// everybody else only have read rights.
chmod($fileDir, 0744);
}
For more information about chmod(), please check this reference:
php.net.
php-cmod-function.
Related
I have a folder of 1000 images and I need to randomly rename them from 1.jpg to 1000.jpg , it must be completely random each time I run the script.
I just need that 1.jpg is different each time I run the script.
all I have to work with so far is the following code.
Please help. Thanks
<?php
if (file_exists('Image00001.jpg'))
{
$renamed= rename('Image00001.jpg', '1.jpg');
if ($renamed)
{
echo "The file has been renamed successfully";
}
else
{
echo "The file has not been successfully renamed";
}
}
else
{
echo "The original file that you want to rename does not exist";
}
?>
Check this out, if this helps. I tried it out and it works. Create a php file and copy the code, and in the same directory create a folder name files and fill it with images with extension .jpg and then run the php file. This is the refined code. Let me know if this works for you.
<?php
$dir = 'files/'; //directory
$files1 = scandir($dir);
shuffle($files1); //shuffle file names
$i = 1; //initialize counter
//store existing numbered files in array
$exist_array = array();
while (in_array($i . ".jpg", $files1)) {
array_push($exist_array, $i . ".jpg");
$i++;
}
foreach ($files1 as $ff) {
if ($ff != '.' && $ff != '..') // check for current or parent directory, else it will replace the directory name
{
// check whether the file is already numbered
if (in_array($ff, $exist_array)) {
continue;
}
//next 3 lines is proof of random rename
echo $ff . " ---> ";
rename($dir . $ff, $dir . $i . ".jpg");
echo $i . ".jpg<br/>";
$i++;
}
}
?>
My folder structure has 4 layers with my form in the top layer, currently it displays the files in the top layer only, I want to be able to select a subfolder and display the files in it so they can be deleted if necessary.
Produce
Produce/Meat
Produce/Meat/Beef
Produce/Meat/Beef/Portions
Produce/Meat/Beef/Packaged
Produce/Vegtables
Produce/Vegetables/Fresh
Produce/Vegetables/Fresh/Local etc,.
My form displays the contents of the folder it is in with checkboxes, I can then tick boxes and delete files, but I have added a select and want to be able to display the contents of the selected subfolder and delete files. I made two submit buttons and both work, but the delete feature only works if it's in the top folder.
if ($_POST['delete'] == 'Submit')
{
foreach ((array) $_POST['select'] as $file) {
if(file_exists($file)) {
unlink($file);
}
elseif(is_dir($file)) {
rmdir($file);
}
}
}
$files = array();
$dir = opendir('.');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..")and ($file != "error_log")) {
$files[] = $file;
}
}
if ($_POST['action'] == 'Change') {
if($_POST['folder'] == 'AAA'){
$files = array();
$dir = opendir('/home/mysite/public_html/Produce/Vegetables/');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..")) {
$files[] = $file;
}
}
}
if($_POST['folder'] == 'BBB'){
$files = array();
$dir = opendir('/home/mysite/public_html/Produce/Meat');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..")) {
$files[] = $file;
}
}
}
}
natcasesort($files);
?>
<form id="delete" action="" method="POST">
<?php
echo '<table><tr>';
for($i=0; $i<count($files); $i++) {
if ($i%5 == 0) {
echo '</tr>';
echo '<tr>';
}
echo '<td style="width:180px">
<div class="select-all-col"><input name="select[]" type="checkbox" class="select" value="'.$files[$i].'"/>
'.$files[$i].'</div>
<br />
</td>';
}
echo '</table>';
?>
</table>
<br>
Choose a folder:
<select name="folder"><option value="this" selected>This folder</option><option value="BBB">Meat</option><option value="CCC">Meat/Beef</option><option value="DDD">Meat/Beef/Portions</option><option value="EEE">Meat/Beef/Packaged</option><option value="FFF">Vegetables</option><option value="GGG">Vegetables/Fresh</option><option value="HHH">Vegetables/Fresh/Local</option><option value="III">Vegetables/Fresh/Packaged</option></select>
<br>
<input class="button" type="submit" form="delete" name="action" value="Change"><br>
<button type="submit" form="delete" value="Submit">Delete File/s</button>
</form><br>
How can I utilise the selected value to accomplish this?
First, I'd like to address why you are unable to delete files outside of the top folder. You never change the "current working directory" so calling the deleting functions on deep files will never work as intended and could delete the files in the top folder. To correct this, you will either need to include the path with each file/directory to be deleted or call chdir() once so that unlink() and rmdir() are looking in the right place.
I believe your project still has some natural maturing to do including security and UX. I'll provide a generalized/simple snippet for you to consider/compare against your project to hopefully give you a bit more traction in your development.
Your users will be able to make one of two choices on submission: Change Directory & Remove Files/Directories
For the directory change, your program will need to submit two necessary pieces of information:
The action (action="change")
The new folder (newfolder={variable})
For the file/directory deletion, there will be three necessary pieces of information:
The action (action="delete")
The files/directory (files[]={variable})
The directory to access (folder={variable}) * the value in the <select> cannot be trusted, because a user could change the selected value before selecting files in the current directory for deletion. This value must be statically preserved.*Note, you could just add the paths to the filenames in the checkbox values and eliminate the hidden input -- this will be a matter of programming preference.
Purely for demonstration purposes, I'll reference this static array of folders in my code:
$valid_folders=[
'Produce',
'Produce/Meat',
'Produce/Meat/Beef',
'Produce/Meat/Beef/Portions',
'Produce/Meat/Beef/Packaged',
'Produce/Vegetables',
'Produce/Vegetables/Fresh',
'Produce/Vegetables/Fresh/Local',
'Produce/Vegetables/Fresh/Packaged'
];
In reality, you'll probably want to generate an array of valid/permitted/existing folders. I might recommend that you have a look at this link: List all the files and folders in a Directory with PHP recursive function
if(isset($_POST['action'])){ // if there is a submission
if($_POST['action']=="Delete"){ // if delete clicked
if(in_array($_POST['folder'],$valid_folders)){
$folder=$_POST['folder']; // use valid directory
}else{
$folder=$valid_folders[0]; // set a default directory
}
chdir($folder); // set current working directory
//echo "<div>",getcwd(),"</div>"; // confirm directory is correct
foreach($_POST['files'] as $file){ // loop through all files submitted
if(is_dir($file)){ // check if a directory
rmdir($file); // delete it
}else{ // or a file
unlink($file); // delete it
}
}
}elseif($_POST['action']=="Change"){ // if change clicked
if(in_array($_POST['newfolder'],$valid_folders)){ // use valid new directory
$folder=$_POST['newfolder'];
}else{
//echo "Sorry, invalid folder submitted";
$folder=$valid_folders[0]; // set a default directory
}
}
}else{
$folder=$valid_folders[0]; // no submission, set a default directory
}
$dir = opendir("/{$folder}"); // set this to whatever you need it to be -- considering parent directories
//echo "Accessing: /$folder<br>";
while(false!=($file=readdir($dir))){
if(!in_array($file,['.','..','error_log'])){ // deny dots and error_log; you should also consider preventing the deletion of THIS file as well! Alternatively, you could skip this iterated condition and filter the $files array after the loop is finished.
$files[] = $file;
}
}
natcasesort($files);
echo "<form action=\"\" method=\"POST\">";
echo "<select name=\"newfolder\">";
//echo "<option value=\"\">Select a folder</option>"; // this isn't necessary if the neighboring button is descriptive
foreach($valid_folders as $f){
echo "<option",($folder==$f?" selected":""),">{$f}</option>"; // if a previously submitted directory, show it as selected
}
echo "</select> ";
echo "<button name=\"action\" value=\"Change\">Change To Selected Folder</button>";
echo "<br><br>";
echo "Delete one or more files:";
echo "<table><tr>";
for($i=0,$count=sizeof($files); $i<$count; ++$i){
if($i!=0 && $i%5==0){ // see the reason for this change # https://stackoverflow.com/questions/43565075/new-containing-div-after-every-3-records/43566227#43566227
echo "</tr><tr>";
}
echo "<td style=\"width:180px;\">";
echo "<div><input name=\"files[]\" type=\"checkbox\" value=\"{$files[$i]}\">{$files[$i]}</div>";
echo "</td>";
}
echo "</tr></table>";
echo "<input type=\"hidden\" name=\"folder\" value=\"{$folder}\">"; // retain current directory
echo "<button name=\"action\" value=\"Delete\">Delete Checked File(s)</button>";
echo "</form>";
As for form structure, you could implement <input type="submit"> or <button> to submit the form. I won't discuss the caveats for this question.
You see, in the form, $folder is a value that invisibly passed with the submission. This stops the user from moving to an unintended directory when deleting files.
When action=Delete then $folder and $files are used for processing.When action=Change only newfolder is used for processing.
When there is no action a default folder is declared and files will be listed.
I accidentally created a file with no name http://website.com/myFolder/.html,
now, in the control panel of my webhost, this file is not listed, I cannot see or delete it...
but I can see it using this "myList.php" file: (http://website.com/myFolder/myList.php):
<?php
echo "<ol>";
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<li>'.$entry.'</li>';
}
}
closedir($handle);
}
echo "</ol>";
?>
This "myList.php" file outputs all the files present in the directory: http://website.com/folder/
also the file with no name http://website.com/myFolder/.html
How can I delete this file?
I tried to create another .php file called http://website.com/myFolder/myDelete.php,
and use the php function unlink():
<?php
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
echo ("Error deleting".$path);
}else{
echo ("Deleted".$path);
}
}
}
?>
But it doesn't work.
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
^^^^^----undefined variable
Why all of that when you could just have
unlink('.html');
? Your unwanted file is in the same directory as your myDelete.php script, so the rest of all that is pointless.
Files and directories that begin with . are considered "hidden" on *nix systems. You can see them with ls -la but not with just ls.
Try changing the $file variable to just be the name of the file ".html". Make sure to use the $file variable for the delete - this is not defined in your example.
$file = ".html";
if ( file_exists( $file ) ){
if ( ! unlink( $file ) ){
echo "Error deleting '$file'" );
} else{
echo "Deleted '$file'";
}
} else {
echo "File '$file' does not exist!";
}
The one comment suggested you use FTP, you should have FTP access to your server then you can simply delete through FTP.
I'm trying to read all folder names and create buttons out of it via .php. It somehow doesn't work how I want it to work.
Foldernames to read are in /www/templates/
.php file is in /www/php/
tried to:
put read.php in /www/templates/, telling it to opendir() and readdir() of "./" and include it to /www/php/ -> shown me results (folders) of /www/php/ (where it works perfectly and shows the folders of "./" if it's placed in there aswell).
Tried using the complete path ( /opt/xyz/www/templates/ ) -> no result at all
CHMOD of the folders are 766 - owner is the same as the PHP script.
Script placed in /www/php/:
<?php
$d = opendir('../templates/');
while(false !== ($f = readdir($d))) {
if (is_dir($f) && $f != "." && $f != "..") {
echo "<form action=\"./change.php\" method=\"get\">
<input type=\"submit\" name=\"template\" value=\"" . $f . "\"><br>";
}
}
?>
Script tried in /www/templates/:
<?php
$d = opendir('./');
while(false !== ($f = readdir($d))) {
[insert-code-from-above-here] }
?>
included the script in /www/templates/ to the "index.php" with:
<?php include('../templates/read.php'); ?>
Webserver: lighttpd
im trying to make a php script that if a .php extention exists in a folder it says check mail, if no .php files exist no mail either one or the other results show up not both.
<?php
$directory = "http://server1.bioprotege-inc.net/roleplay_realm_online/contact_us_files/";
if (glob($directory . "*.php") != true) {
echo 'Check Mail:';
}
else {
echo 'No mail Today';
}
?>
that what I got but it aint working it only shows the same result if there is a .php file in the folder or not
The glob() function returns the array of files name with extension so you can not check them with true and false.
Check the reference site: glob function in php
That's why you should use following code to check it:
<?php
$directory = "http://server1.bioprotege-inc.net/roleplay_realm_online/contact_us_files/";
// Open a known directory, and proceed to read its contents
if (is_dir($directory)) {
$arr = array();
if ($dh = opendir($directory)) {
while (($file = readdir($dh)) !== false) {
$arr[] = $file;
}
$name = implode($arr);
if(strstr($name,".php")){
echo "Check Mail:";
} else {
echo "No mail Today";
}
closedir($dh);
}
}
?>
This will be helpful to you. I hope so.
Understanding the risk, this is how it can be done
$dir="core/view/";
if(glob($dir . "*.php")!=null)
echo " New Mail";
else
echo "No Mail";
You can use glob if you have less than a 100k files, else you may get a Allowed memory size of XYZ bytes exhausted ..." error.
In that case you can change the setting in php.ini or you can use
readdir()
You can use readdir() in this manner
if ($handle = opendir('core/view')) {
$flg=0;
while (false !== ($entry = readdir($handle))) {
if(strcasecmp(pathinfo($entry, PATHINFO_EXTENSION),"php")==0){
$flg=1;
break;
}
}
echo $flg;
closedir($handle);
}