I am trying to a delete file selected using a dropdown. I am getting an error 'undefined index "file"' and permission denied warning on unlink.
<?php
$dirname = $_SERVER['DOCUMENT_ROOT']."myphp/project/userdir/neeraj/";
$dir = opendir($dirname);
echo '<form action="delete.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="Delete" class="submit" />';
echo '</form>';?>
<?php
$dirpath = $_SERVER['DOCUMENT_ROOT']."myphp/project/userdir/neeraj/";
$file_to_delete = $_GET['file2'];
if ( unlink ($dirpath.'/'.$file_to_delete) ) {
echo $file_to_delete . " deleted.";
} else {
echo "Error.";
}
?>
Note that your $dirpath ends with / and later you are trying to unlink:
unlink ($dirpath.'/'.$file_to_delete)
so it actualy gets something like this (note double slash):
[...] myphp/project/userdir/neeraj//$file_to_delete [...]
You should check file permissions to be sure that script has a right to unlink your files:
https://en.wikipedia.org/wiki/File_system_permissions
I guess you get the first error because you do not wrap your code to be executed only on form submit. Change the second section of your code to this:
<?php
if(isset($_GET['file2'])){ //i have posted my form
$dirpath = $_SERVER['DOCUMENT_ROOT']."myphp/project/userdir/neeraj/";
$file_to_delete = $_GET['file2'];
if ( unlink ($dirpath.'/'.$file_to_delete) ) {
echo $file_to_delete . " deleted.";
} else {
echo "Error.";
}
}
?>
The other error is related to the apache user to be able or not to access and delete in the directory where you store the files.
Related
I want to return the contents of a folder as a radio button. I would like to be able to return the selected option in a variable so that I can then show the user what they have selected.
How do I solve this problem?
Attempt
$dir = '/beta/import/';
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo ("<form action=\"#\" method=\"post\">");
foreach ($files as $file) {
echo '<input type="radio" name="files[]" value="' . $file . '" /> ' . $file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' . '</form>';
echo "<br>";
if (isset($_POST['submit'])) {
$selected_val = $_POST['$file'];
echo "You have selected :" . $selected_val;
}
} else {
exit('No files found.');
}
Since you use name="files[]", $_POST['files'] will be an array, not a single value. There's little point in doing this for radio buttons, since you can only select one of them, and the array will always have one entry. So you should change that to name="file".
If you make that change, your code to print the selection should work.
You also need to remove action="#" from the form. That prevents the form from submitting, so you'll never get any $_POST variables (unless you submit the form using AJAX).
I have a drop down list that generates all files in a folder, which is working. But i would like to only see .jpg files and also i would like to exclude one file from the list as it is a place holder image lets call it "0001_Place_Holder.jpg".
The second part to this is that i want to pick a file from the dropdown list and copy it to a New folder then delete the original image.
this is "move_files_general.php" // which generates my dropdown list
<?php
$dirname = "general_2";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality" class="submit" />';
echo '</form>';
?>
This is "move_general.php" // which should copy the file then delete the original
<?php
$dirpath = "general_2";
$dirpath_2 = "quality_2";
$file_to_move = $_GET['file2'];
copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move") or die("Unable to copy");
if (copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move")) {
unlink("$dirpath.'/'.$file_to_move");
if ( unlink ($dirpath.'/'.$file_to_move) ) {
echo $file_to_move . " deleted.";
echo '<script>parent.window.location.reload(true);</script>';
} else {
echo "Error.";
}
}
?>
You would test the filename if its extension is jpg and if it is not equal to your placeholder name.
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
For the second issue: try to set the folder permissions to 777 for testing purpose. Also echo the strings that you pass to copy(string1,string2) in order to check if something is wrong in there.
First off, Thanks for your answers, and help. Alex Odenthal, that worked for the 1st part. i tried everything to get the 2nd part to work. I finally rewrote it a different way and it's working now, I must have had something wrong , somewhere.
Here is my fixed "move_files_general.php"
<?php
$dirname = "general";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder_DO_NOT_DELETE.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality1" class="submit" />';
echo '</form>';
?>
Here is my fixed "move_general.php"
<?php
$file_to_move = $_GET['file2'];
$source = "general/$file_to_move";
$dest = "quality/$file_to_move";
copy($source, $dest);
if (copy($source, $dest)) {
unlink($source);
if(file_exists($source)) {
unlink($source); }
else {
echo "Deleted.";
}
}
?>
I have code like this however it doesn't delete. I check console if there is an error, no; there is no error appearing either. Can you help that can delete properly files in the pointing directory.
<?php
$dir = 'C:\xampp\htdocs\phpex\uploads';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST['filenames'] ) ) {
foreach( $_POST['filenames'] as $key => $file ) {
unlink( $dir . '\\' . $file );
}
echo 'Files deleted';
}
else {
echo 'No files selected';
}
}
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input name='filenames[]' value='".($files1[$n])."' type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo "<input type='submit' value='Delete'>";
echo "</form>";
echo "</div>";
?>
Your code of deleting is alright. It must work.
Obviously, the problem is in input: something wrong in $_POST['filenames'].
Insert log right before unlink and examine it.
I would like PHP to check the directory of selection i input in variable and out put the Folder, Files, Permission (writable or not writable) at same time.
Here is my PHP Code:
<?php
$directorySelection = '../app/';
if (file_exists($directorySelection)) {
if ($existence = opendir('../app')) {
while (false !== ($files = readdir($existence))) {
if ($files != "." && $files != ".." && $files != ".DS_Store") {
echo '<table>';
echo '<tr>';
echo '<td style="width: 90%; padding: 10px;">'. $files .'</td>';
if (is_writable($files)) {
echo '<td><span class="label label-success">Writable</span></td>';
} else {
echo '<td><span class="label label-danger">Not writable</span></td>';
}
echo '<td>'. substr(sprintf('%o', fileperms($files)), -4) . '</td>';
echo '</tr>';
echo '</table>';
}
}
closedir($existence);
}
} else {
echo '<div class="alert alert-warning" role="alert">Application Directory doesn\'t exist <a role ="button" data-toggle="alertInfo" placement="left" title="Application Directory" data-content="Please set your Application Directory, so that the installer can check for folder, files and there Permissions "> <span class="glyphicon glyphicon-info-sign floatRight"></span></a></div>';
}
?>
Result i get:
the problem is with your $files variable, as it doesn't contain the full path, only the name, and it is checking from CWD.
Your code is testing for the file perms based on the CWD, but your files are not located in the CWD. so prefix the $files with the name of the directory such as
if ($files != "." && $files != ".." && $files != ".DS_Store") {
$filepath = $directorySelection . $files;
....
if (is_writable($filepath)) {
.....
substr(sprintf('%o', fileperms($filepath)), -4)
And it should read the file correctly. Then use $files if you want the name, and $filepath for function that take a filename.
(interior code not shown as to not clutter it up)
I'm currently making a droplist but in the droplist let's say I only want to include only .txt extension files so any other extensions like .php .jpg or any other extensions will not be in in the droplist. How can I do that as simple as possible?
Another question is I want to make a warning IF the folder does not have any .txt extension files an error message will show. So even if there are other .jpg .php or any other files inside as long as there's no .txt file in the folder a warning will show.
Anyone able to give me a hand?
This is what I have done but it only shows a drop-list with no .txt at the end but it will still show other random files in the drop-list though.
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if(($list == ".") || ($list == ".."))
{
continue;
}
echo "<option value=\"";
echo basename($list,".txt");
echo "\">";
echo basename($list,".txt");
echo "</option>";
}
echo "</select>";
echo "</form>";
editted added the substr with $hasTxt
<?php
if(!(is_dir("./aaa")))
{
die("Must create a <strong>aaa</strong> folder first, sorry");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select name=\"aaa\">";
$aaa_files = scandir("./aaa");
$hastxt = false;
foreach($aaa_files as $file_list)
{
if(($file_list == ".") || ($file_list == ".."))
{
continue;
}
if(strlen($file_list)>4 && strtolower(substr($file_list, -4))!='.txt')
{
continue;
}
else
{
$hastxt = true;
echo "<option value=\"";
echo basename($file_list,".txt");
echo "\">";
echo basename($file_list,".txt");
echo "</option>";
}
}
echo "</select>";
echo "<br/><input type=\"submit\">";
echo "</form>";
if($hastxt == false)
{
echo "Must create text files first, sorry";
die();
}
?>
This is what happens for the script that I have now if the folder does not have any txt files.
This is what I actually want if there's no txt file but of course without the arrow
For the first part, just like you continue on directories . and .., you can continue on non-text files:
if(strlen($list)>4 && strtolower(substr($list, -4))!='.txt') continue;
For the warning part, put a flag before the foreach
$hasTxt = false;
And set it to true whenever you get input you don't ignore (ie. after the if(unwanted) continue;)
$hasTxt = true;
Finally, after the foreach check the value of $hasTxt and use it as you prefer.
You could use PHP's substr() function to test the filenames:
if(substr($filename, -3) == 'txt') {
// show file
}
See here: http://php.net/manual/en/function.substr.php
Try this , Hope it will work you
<?php
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
$i =0;
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
$i++;
}
}
if($i == 0){
die("the folder does not have any .txt extension files");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
echo "<option value=\"".substr($list,0, -4)."\">".substr($list, 0,-4)." </option>";
}
}
echo "</select>";
echo "</form>";
?>