简体   繁体   中英

Delete file from a directory with php NO DATABASE

I am stuck on my codes from 2 days now. I have already tried more then 100 tutorials/guide but none of them solve my problem. Mostly guide is for database.

I am using ready made gallery plugin to display images on my website. This gallery does not use database. For that I made admin panel with upload function. Now i am looking for function to delete uploaded photos from admin panel. one pic at a time or multiple option will be more then good.

Right now with this code i am displaying images in Admin Page at main.php which i uploaded before:

<?php
$folder_path = 'gallery-images/'; //image's folder path

$num_files = glob($folder_path . "*.{jpeg,jpg,gif,png,bmp}", GLOB_BRACE);

$folder = opendir($folder_path);

if($num_files > 0)
{
 while(false !== ($file = readdir($folder))) 
 {
  $file_path = $folder_path.$file;
  $extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
  if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp') 
  {
   ?>
            <a href="<?php echo $file_path; ?>" id="fname"><img src="<?php echo $file_path; ?>"  height="250" /></a>
            <?php
  }
 }
}
else
{
 echo "the folder was empty !";
}
closedir($folder);
?>

And i am trying this delete code in delete.php

<?php
$filename = $_POST['fname'];
$path = $_POST['directory'];
if(file_exists($path."/".$filename)) { 
 unlink($path."/".$filename); //delete file
}
?>

So i need a function to delete file from server with confirmation and with delete button. Right now file just open with a click. This function will be only for admin, So i think i am safe with delete function as i read in similar topics.

Thanks in Advance.

EDIT 1:

So far this code successfully delete a file from server (Answer from @Jocelyn):

<h3><a href="?delete=1">Delete Now!</a></h3>

<?php
    if(isset($_GET['delete']))
    {
        unlink(__FILE__);
    }
?>

Change this unlink(__FILE__); to unlink("$file_path");

EDIT 2:

Sorry, it does delete file from server but its deleting all the files in that directory.

Is there anyway to delete only one file which i click.

Right now all photos appearing from one link of code, i think thats the problem.

The link is this from which photos are appearing:

<a href="?delete=1" id="delete" name="delete"><img src="<?php echo $file_path; ?>"  height="250" /></a>

A very quickly cobbled together example of how you might achieve your goal using ajax to send the filename to the delete.php script. No doubt that because it's not tested there may well be issues - but it's a starting point.

<?php
    /* delete.php */
    $img=!empty( $_GET['name'] ) ? $_GET['name'] : false;
    $result=false;


    if( $img ){
        /*

            here you would typically check that the path sent via ajax exists
            and then use unlink to delete the file before sending a response
            to the ajax callback function - the callback would then inform the
            user that the file has been deleted ( or not! )

            For testing though a simple message will suffice so that files are not deleted unnecessarily!!!

            -- uncomment the line below to actually attempt deletion of file.
        */


        if( file_exists( $img ) ){
            #$result = @unlink( $img );
            clearstatcache();
        }


        echo $result ? 'The file '.$img.' was deleted' : 'The file '.$img.' could not be deleted';
    }
?>




<?php
    $root='c:/wwwroot';
?>
<!-- /* admin page that lists images */ -->
<html>
    <head>
        <title>Delete images - no database</title>
        <script>
            function ajax(imagename,callback){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.status==200 && xhr.readyState==4 ){
                        callback.call( this, xhr.response );
                    }
                };
                xhr.open( 'GET', 'delete.php?name='+imagename, true );
                xhr.send();
            }
            function deleteimage(e){
                e.preventDefault();
                ajax.call( this, e.target.dataset.path+'/'+e.target.dataset.name, cbdeleteimage );
            }
            function cbdeleteimage(r){
                alert( r );
            }
            function bindEvents(){
                var col=document.querySelectorAll('img.delete');
                for( var n in col )if( col[ n ].nodeType==1 ) col[n].addEventListener( 'click', deleteimage, false );
            }

            document.addEventListener( 'DOMContentLoaded', bindEvents, false );
        </script>
    </head>
    <body>
        <?php

            $dir = 'gallery-images/';       /* YOUR path */
            $dir = $root . '/images/misc/'; /* MY test path */

            $files=preg_grep( '@(\.jpg|\.jpeg|\.png|\.bmp|\.gif)@i', glob( $dir . '*.*' ) );
            $html=array();


            foreach( $files as $file ){
                if( $blocal ) $file=str_replace( $root, '', $file );    /* remove MY site root from file names */
                $name = pathinfo( $file, PATHINFO_BASENAME );
                $path = pathinfo( $file, PATHINFO_DIRNAME );

                $html[]="<img class='delete' src='{$file}' data-name='{$name}' data-path='{$path}' />";
            }


            echo implode( PHP_EOL, $html );
        ?>
    </body>
</html>

So this is the final code which is perfectly fine for noobs like me who stuck with their work:

this is Delete.php to delete only a requested file

<?php
$file = $_GET['delete'];
if(isset($_GET['delete']))
    {
        unlink("./gallery-images/$file");
        header("Location:home.php");
    }
?>

This is upload.php to upload file with rename to auto increment value:

<?php

// Upload and Rename File

if (isset($_POST['submit']))
{
    $filename = $_FILES["file"]["name"];
    $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
    $file_ext = substr($filename, strripos($filename, '.')); // get file name
    $filesize = $_FILES["file"]["size"];
    $allowed_file_types = array('.png','.jpg','.jpeg');  
    $count = count (glob ('gallery-images/*'));

    if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000000))
    {   
        // Rename file
        $newfilename = ($count + 1) . $file_ext;
        if(file_exists("gallery-images/" . $newfilename))

        {
            // file already exists error
            echo "You have already uploaded this file.";
        }
        else
        {       
            move_uploaded_file($_FILES["file"]["tmp_name"], "gallery-images/" . $newfilename);
            header("Location: home.php");   
            exit;
        }
    }
    elseif (empty($file_basename))
    {   
        // file selection error
        echo "Please select a file to upload.";
    } 
    elseif ($filesize > 10000000)
    {   
        // file size error
        echo "The file you are trying to upload is too large.";
    }
    else
    {
        // file type error
        echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
        unlink($_FILES["file"]["tmp_name"]);
    }
}

?>

This is home.php to display image with delete feature:

Upload Form:

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload: <br />
    <input type="file" name="file" id="file"><br /><br />
    <input type="submit" value="Upload Image" name="submit">
</form>

Display photos from directory:

<?php
$folder_path = 'gallery-images/'; //image's folder path 
$num_files = glob($folder_path . "*.{jpeg,jpg,png}", GLOB_BRACE);
$folder = opendir($folder_path);
$file = '$file_path';

if($num_files > 0)
{
 while(false !== ($file = readdir($folder))) 
 {
  $file_path = $folder_path.$file;
  $extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
  if($extension=='jpg' || $extension =='png' || $extension == 'jpeg' || $extension == 'bmp') 
  {
   ?>
     <a href="delete.php?delete=<?php echo $file; ?>" onclick="return deleletconfig()" id="delete" name="delete"><img src="<?php echo $file_path; ?>"  height="175" /></a> 
<?php
  }
 }
}
else
{
 echo "the folder was empty !";
}
closedir($folder);
?>

Delete confirmation popup script:

<script>
function deleletconfig(){

var del=confirm("Are you sure you want to delete this record?");
if (del==true){
}
return del;
}
</script>

Hope this will be helpful for learners. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM