Delete Image Files From Server

◇◆丶佛笑我妖孽 提交于 2019-11-29 09:33:56

If you can pass the username, locationid, and imagename variables to your script, you can delete the files using unlink():

$path = 'UploadedFiles/' . $username . '/' . $locationid . '/';

unlink( $path . $imagename );
unlink( $path . 'Thumbnails/' . $imagename );

Because you are interacting with your file system, you'll want to be sure and sanitize the variables (prevent someone from using ../../../ to get to unwanted parts of your file system).

$username = str_replace( array( '..', '/', '\\', ':' ), '', $username );
$imagename = str_replace( array( '..', '/', '\\', ':' ), '', $imagename );
$locationid= str_replace( array( '..', '/', '\\', ':' ), '', $locationid );

Obviously your javascript (client-side) will have to call a URL (server-side) to delete the picture that the user selected. I propose that for now you do it statically (if later you wanna move to something more dynamic, the step to transform into ajax in rather small.

So as Set Sail Media said, you will have to pass the username and locationID to your server when clicking on the delete button. One way to do that is:

When rendering your gallery in HTML/javascript, for each picture, you had below it a which will contain the needed information and the submit button will simply call the delete script from your server. An example of form that you could do is:

    <form name="deleteImageX" method="GET" target="your.server.org/deleteImage.php">
        <input type="hidden" name="userName" value="theUserNameAssociatedWithThePicture" />
        <input type="hidden" name="locationId" value="locationOfThePicture" />
        <input type="submit" value="delete"/>
    </form>

This form will store the needed value in hidden fields which will not be displayed on the webpage but will still be sent to the server when pressing the submit button.

(for the little story, the method used here is GET because AFAIK HTML doesn't support the DELETE method (which would have been suitable in our case)).

The GET method will call the script "your.server.org/deleteImage.php". In this script you will have all the information you need (username/locationId) to delete the image by using the $_GET['username'] and $_GET['locationId'] variables. Then as you mentioned, you will need to use the unlink method to actually delete the file from the server.

Finally once this is done you need to redirect the php script so that after deleting the image you display the gallery again (for instance). This can be done by calling a script if you have some sort of template engine, or by calling the "header" function of php.

I hope this flow was what you expected and I hope I have been helpful.

regards,

Bear

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!