How to display images to delete using PHP Unlink - php

I have a script that deletes images from a folder using PHP.
The problem is the images arenot being displayed on the page.
My code is as below
<?php
// directory separator
defined("DS")
|| define("DS", DIRECTORY_SEPARATOR);
// root path
defined("ROOT_PATH")
|| define("ROOT_PATH", realpath(dirname(__FILE__)));
// upload folder directory
defined("UPLOAD_DIR")
|| define("UPLOAD_DIR", "uploads");
// path to the upload folder
defined("UPLOAD_PATH")
|| define("UPLOAD_PATH", ROOT_PATH.DS.UPLOAD_DIR);
function getAllFiles($folder = null) {
if(!empty($folder) && is_dir($folder)) {
if($handle = opendir($folder)) {
$out = array();
while($file = readdir($handle)) {
if(is_file($folder.DS.$file)) {
$out[] = $file;
}
}
closedir($handle);
return $out;
}
return false;
}
return false;
}
$files = getAllFiles(UPLOAD_PATH);
if (!empty($_POST['file'])) {
foreach($_POST['file'] as $file) {
unlink(UPLOAD_PATH.DS.$file) or die("Failed to <strong class='highlight'>delete</strong> file");
}
header("location: " . $_SERVER['REQUEST_URI']);
}
?>
<?php if (!empty($files)) { ?>
<form name="form1" method="post">
<?php foreach($files as $key => $file) { ?>
<label for="file_<?php echo $key; ?>">
<input type="checkbox" name="file[]" id="file_<?php echo $key; ?>" value="<?php echo $file; ?>" />
<?php echo $file; ?>
</label>
<?php } ?>
<input type="submit" name="delete" value="Delete" />
</form>
The code works fine to delete the images but does not display the images on the page.
Your help is much apprecited.
Thank You

I think the images are still in the browser cache, so deleting the cache will result in not seeing any deleted images.

Related

How can i show the images in order in website with PHP and HTML?

I added the images with image upload page and show the image and thumbnail images in another web page. I used the resize name with time() function. And I want this: I want each image I add to appear on the html page in order, according to the names I have just given. However, as I add the photos with the code I wrote, the order in my html page is distorted, but I always want it to continue in the order I added. How can I show the pictures I renamed with the Time() function in order on my html page?
home.php
<div class ="gallery-items">
<?php
$image_extensions = array("png","jpg","jpeg","gif");
$dir = 'image/';
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
$thumbnail_path = "image/thumbnailkamu/".$file;
$image_path = "image/".$file;
$thumbnail_ext = pathinfo($thumbnail_path, PATHINFO_EXTENSION);
$image_ext = pathinfo($image_path, PATHINFO_EXTENSION);
if (array_key_exists('delete_file', $_POST)) {
$filen = $_POST['delete_file'];
if (file_exists("image/".$filen)){
unlink("image/".$filen);
unlink("image/thumbnailkamu/".$filen);
}
}
if(!is_dir($image_path) &&
in_array($thumbnail_ext,$image_extensions) &&
in_array($image_ext,$image_extensions)){
?>
<div class ="item">
<a href="<?= $image_path; ?>" data-lightbox="mygallery">
<img src="<?= $thumbnail_path; ?>">
</a>
<a class="btn btn-primary" href="<?= $image_path; ?>" download>Download</a>
<form action = "" method="post">
<input type="hidden" value="<?= $file; ?>" name="delete_file" />
<input class = "button" type="submit" value="Delete" />
</form>
</div>
<?php
}
}
}
}
closedir($dh);
}
?>
</div>
Since you're having trouble following the other S.O. answer, try this. First stick the files in an array with the filemtime as the key, then use ksort to sort it before you start iterating
<div class="gallery-items">
<?php
$image_extensions = array("png", "jpg", "jpeg", "gif");
$dir = 'image/';
if (is_dir($dir)) {
$thefiles = [];
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file != "" && $file != "." && $file != "..") {
$thefiles[filemtime('image/' . $file)] = $file;
}
}
closedir($dh);
}
// sort the by most recent at the top
ksort($thefiles);
// now loop through
foreach ($thefiles as $file) {
$thumbnail_path = "image/thumbnailkamu/" . $file;
$image_path = "image/" . $file;
$thumbnail_ext = pathinfo($thumbnail_path, PATHINFO_EXTENSION);
$image_ext = pathinfo($image_path, PATHINFO_EXTENSION);
if (array_key_exists('delete_file', $_POST)) {
$filen = $_POST['delete_file'];
if (file_exists("image/" . $filen)) {
unlink("image/" . $filen);
unlink("image/thumbnailkamu/" . $filen);
}
}
if (!is_dir($image_path) &&
in_array($thumbnail_ext, $image_extensions) &&
in_array($image_ext, $image_extensions)) {
?>
<div class="item">
<a href="<?=$image_path;?>" data-lightbox="mygallery">
<img src="<?=$thumbnail_path;?>">
</a>
<a class="btn btn-primary" href="<?=$image_path;?>" download>Download</a>
<form action="" method="post">
<input type="hidden" value="<?=$file;?>" name="delete_file" />
<input class="button" type="submit" value="Delete" />
</form>
</div>
<?php
}
}
}
?>
</div>

How can I add a delete function to this script to delete file on server

i have a script which loads all files within a specific directory folder into a viewable table. I have also been able to successfully get the date uploaded element integrated and am using the $iterator function as seen in the code below
UPDATE
edited value to checkbox input but still not working
Removed unnecessary code snippets from past attempts
Updated code to most recent and added full script for better understanding including CD001's suggestions
// Begin Adding Uploader Page Content
function pdfupload_admin_page(){
?>
<style>
<?php include '../wp-content/plugins/PDF-Uploader/support-files/stylesheet.css'; ?>
</style>
<div class="wrap">
<div id="contact">
<div style="text-align:center;">
<h1>Secure PDF File Upload</h1>
<p>Adding a watermark to your PDF files is as easy as uploading the file using the form below.<br>
Upon successful submission of your PDF file you will receive the uploaded PDF files URL which you can then use when linking to the PDF within any page or post you desire.</p>
<p>The PDF file when linked to using the URL provided will automatically acquire a watermark when loaded within the browser of the specific logged in user as well as the current date and time.</p>
<form action="" method="post" enctype="multipart/form-data">
<h3>Select PDF File To Upload:</h3><br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload PDF File" name="submitUpload">
</form>
<?php
$target_dir = "../wp-content/plugins/PDF-Uploader/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submitUpload"])) {
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["fileToUpload"]["size"] > 10000000) {
// echo "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($FileType != "pdf") {
echo "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "File uploaded successfully use the following URL when linking to your PDF <br> https://website.com/wp-content/plugins/PDF-Uploader/watermarked.php?filename=" . basename( $_FILES["fileToUpload"]["name"]). "";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
// Check if file already exists
/**
* FILE DELETION HANDLER
*/
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
function delete_file($iterator, $file) {
if(!unlink($iterator->getPath() . '/' . $file)) {
echo "Sorry! your file cannot be deleted. Please try again later";
}
else {
echo "File deleted successfully!";
}
}
if(isset($_POST['submit'])){
if(!empty($_POST['file'])) { // check if the checkbox was checked.
foreach($_POST['file'] as $file) {
// call delete function here.
delete_file($iterator, $file);
}
}
else{
echo "No file selected. You must select at least one PDF file to be deleted.";
}
}
?>
</div>
<?php
// if ($handle = opendir('../wp-content/plugins/PDF-Uploader/')) {
// while (false !== ($file = readdir($handle)))
// {
// if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
// {
// $thelist .= '<td><input type="checkbox" name="file[]" value="https://website.com/wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
// }
// }
// closedir($handle);
//}
?>
<form id="deletionForm" method="post" action="">
<table>
<thead>
<tr style="width:100%;">
<th style="width:25px;"></th>
<th style="text-align:left;width:625px;">Filename</th>
<th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
</tr>
</thead>
<?php
// $iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/pdf-watermarker/');
foreach($iterator as $file){
//if($file->isFile()){
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
//echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
?>
<tr>
<td style="width:25px;"><input type="checkbox" name="file[]" value="wp-content/plugins/PDF-Uploader/<?php echo $file->getFileName(); ?>"></td>
<td style="text-align:left;width:625px;"><?php echo $file->getFileName(); ?></td>
<td style="text-align:right;width:100px;padding-right:20px;"><?php echo $cTime->format('Y-m-d h:i:s'); ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>
</div>
<?php
}
// End Adding Secure PDF Upload Page Content
So all in a nutshell, I need to figure out why the delete functionis not working and add a sort order to the script to product the results in alphabetical order.
Any code samples would be greatly appreciated.
File handling require a valid enctype in <form>, being enctype="multipart/form-data" as per the manual:
https://secure.php.net/manual/en/features.file-upload.post-method.php
An example from the manual:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
You need to change all references of $_POST['file'] to $_FILES['file']['name'] / $_FILES['file']['tmp_name'] respectively.
Handling multiple files is also included in the manual, and here is an example pulled from it:
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Use PHP's error reporting to help you debug:
https://php.net/manual/en/function.error-reporting.php
However, when dealing with checkboxes, don't use empty(), use isset():
if(isset($_POST['file'])) { // check if the checkbox was checked.
It's a bit unclear if you want to upload files. If so, then you need to change the <input type="checkbox" to an file input type <input type="file"
Edit:
This part of your code should error out, since there needs to be an empty variable declaration using $thelist = "";
I.e.:
<?php
if ($handle = opendir('../wp-content/plugins/PDF-Uploader/.')) {
$thelist = "";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$thelist .= '<td><input type="checkbox" name="file[]" value="../wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
}
}
closedir($handle);
}
?>
Solution (explanation follows)
<?php
// global iterator
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
function delete_file($iterator, $file) {
if(!unlink($iterator->getPath() . '/' . $file)) {
echo "Sorry! your file cannot be deleted. Please try again later";
}
else {
echo "File deleted successfully!";
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['file'])) { // check if the checkbox was checked.
foreach($_POST['file'] as $file) {
// call delete function here.
delete_file($iterator, $file);
}
}
else{
echo "No file selected. You must select at least one PDF file to be deleted.";
}
}
?>
<form method="post" action="">
<table>
<thead>
<tr style="width:100%;">
<th style="width:25px;"></th>
<th style="text-align:left;width:625px;">Filename</th>
<th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
</tr>
</thead>
<?php
foreach($iterator as $file) {
//if($file->isFile()){
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
//echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
?>
<tr>
<td style="width:25px;"><input type="checkbox" name="file[]" value="<?= $file->getFileName(); ?>"></td>
<td style="text-align:left;width:625px;"><?= $file->getFileName(); ?></td>
<td style="text-align:right;width:100px;padding-right:20px;"><input type="text" name="date[]" value="<?= $cTime->format('Y-m-d h:i:s'); ?>"></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>
</body>
</html>
Explanation
Since the FilesystemIterator holds the path to the directory for your PDF repository I've defined that as a global variable at the top of the script. It's then referenced wherever required so should you ever need to change the filepath, you just change it in the $iterator.
For instance, it's used in the loop and passed to the delete_file function. The form itself is only posting the filenames rather than the full paths.
Otherwise you weren't really a long way off.
Couple of thoughts
The FilesystemIterator class has methods for detecting the extension and whether the file is . or .. so you can replace:
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
With:
if(!$file->isDot() && $file->getExtension() == 'pdf')
Which is a little neater.
There is also a security concern with having a directory that's both web server readable and writeable - if there's a vulnerability in your application an unauthorised user could upload and execute anything (open it in the browser); a malicious PHP script for instance.
You can mitigate this through your Apache configuration - one common thing to do is to disable PHP via an .htaccess file:
php_flag engine off

Upload an image and newsTitle related to image PHP

I need to upload an image and add it to my slideshow and give it related newsTitle in front of my uploaded picture. I'm a new in PHP and trying to learn how to send data from my admin.php file to my index.php file and add more image with a <form> in html.
My problem is that I can upload images but can't get my newsTitle printed to my home page which is index.php.
This is my PHP code in index.php:
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
$newsImage = $_POST['newsImage'];
echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
echo'<h2'.'>'.htmlspecialchars($newsImage["newsImage"]).'</h2>';
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
This is my html code in admin.php:
<form action="index.php" method="post" enctype="multipart/form-data">
<br><br>
<tr>
<td> NewsTitle: </td>
<td> <input type="text" name="newsTitle" placeholder="newsTitle"> </td>
</tr>
<br><br>
Select image to upload:
<input type="file" name="image">
<br><br>
<br><br>
NewsText: <textarea name="newsImage" placeholder="newsImage" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" value="Send" name="send_object">
</form>
I'm trying to do this without connection to the database, just to my apache server. I have tried with another global variable $_REQUEST but it didn't work. What I know it can use for $_POST , $_GET and $_COOKIES
Firstly, if you are trying to make each news with a text you collect it separately with the $_POST , but note once you refresh the page the parameters are gone cause the form processes everything so there is no space for output in text but if you use the get the parameters remain because you are not storing both the post method and get method in the database. Try this
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
<?php
$newsImage = $_POST['newsImage'];
//this would give a parse error echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
try
echo <?php echo $newsimage; ?>
?>

re-sizing image in php error in server

i have a code for re-sizing image in php... it works well in local machine and splitting correctly...images are visible in all 4 sizes... but,when am using this in server...image size is re-sized...original image is visible...resized image is not visible...comes with black color...what is the solution for it...here is the code i used...
main.php
<?php
if(isset($_POST['submit']))
{
$uploaddir = 'uploads/';
$file = basename($_FILES['uploadedfile']['name']);
$uploadfile = $uploaddir . $file;
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile);
include ("thumb.php");
$target=$_FILES['uploadedfile']['name'];
$new='uploads/'."thumb_".$target;
$type=$_FILES['uploadedfile']['type'];
$w=90;
$h=90;
resize($target,$new,$w,$h,$type);
include ("medium.php");
$new1='uploads/'."middle_".$target;
$type1=$_FILES['uploadedfile']['type'];
$w1=400;
$h1=400;
resizee($target,$new1,$w1,$h1,$type1);
include ("big.php");
$new2='uploads/'."big_".$target;
$type2=$_FILES['uploadedfile']['type'];
$w2=900;
$h2=900;
resizeee($target,$new2,$w2,$h2,$type2);
echo "thumb_".$target."<br>";
echo "middle_".$target."<br>";
echo "big_".$target."<br>";
}
?>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile">
<input type="submit" name="submit">
</form>
</body>
</html>
thumb.php
<?php
function resize($target,$new,$w,$h,$type)
{
echo $target;
list($wo,$ho)=getimagesize('uploads/'.$target);
if($type=="image/jpeg")
{
$m=imagecreatefromjpeg('uploads/'.$target);
}
elseif($type=="image/gif")
{
$m=imagecreatefromgif('uploads/'.$target);
}
elseif($type=="image/png")
{
$m=imagecreatefrompng('uploads/'.$target);
}
$change=imagecreatetruecolor($w,$h);
imagecopyresampled($change,$m,0,0,0,0,$w,$h,$wo,$ho);
imagejpeg($change,$new,90);
}
?>
medium.php
<?php
function resizee($target,$new1,$w1,$h1,$type)
{
list($wo1,$ho1)=getimagesize('uploads/'.$target);
if($type=="image/jpeg")
{
$m1=imagecreatefromjpeg('uploads/'.$target);
}
elseif($type=="image/gif")
{
$m1=imagecreatefromgif('uploads/'.$target);
}
elseif($type=="image/png")
{
$m1=imagecreatefrompng('uploads/'.$target);
}
$change1=imagecreatetruecolor($w1,$h1);
imagecopyresampled($change1,$m1,0,0,0,0,$w1,$h1,$wo1,$ho1);
imagejpeg($change1,$new1,500);
}
?>
big.php
<?php
function resizeee($target,$new2,$w2,$h2,$type)
{
list($wo2,$ho2)=getimagesize('uploads/'.$target);
if($type=="image/jpeg")
{
$m2=imagecreatefromjpeg('uploads/'.$target);
}
elseif($type=="image/gif")
{
$m2=imagecreatefromgif('uploads/'.$target);
}
elseif($type=="image/png")
{
$m2=imagecreatefrompng('uploads/'.$target);
}
$change2=imagecreatetruecolor($w2,$h2);
imagecopyresampled($change2,$m2,0,0,0,0,$w2,$h2,$wo2,$ho2);
imagejpeg($change2,$new2,900);
}
?>
You may want to check the permissions on the file / directory to make sure that they are readable and writable by your PHP script.

Images Not Displaying

All I want is that the images are displayed nothing else please.
I have been working on a different script but have the same problem.
I images are deleted but not displayed.
My code is:
<?php
// directory separator
defined("DS")
|| define("DS", DIRECTORY_SEPARATOR);
// root path
defined("ROOT_PATH")
|| define("ROOT_PATH", realpath(dirname(__FILE__)));
// upload folder directory
defined("UPLOAD_DIR")
|| define("UPLOAD_DIR", "../imagefolder");
// path to the upload folder
defined("UPLOAD_PATH")
|| define("UPLOAD_PATH", ROOT_PATH.DS.UPLOAD_DIR);
function getAllFiles($folder = null) {
if(!empty($folder) && is_dir($folder)) {
if($handle = opendir($folder)) {
$out = array();
while($file = readdir($handle)) {
if(is_file($folder.DS.$file)) {
$out[] = $file;
}
}
closedir($handle);
return $out;
}
return false;
}
return false;
}
$files = getAllFiles(UPLOAD_PATH);
if (!empty($_POST['file'])) {
foreach($_POST['file'] as $file) {
unlink(UPLOAD_PATH.DS.$file) or die("Failed to <strong class='highlight'>delete</strong> file");
}
header("location: " . $_SERVER['REQUEST_URI']);
}
?>
<?php if (!empty($files)) { ?>
<form name="form1" method="post">
<?php foreach($files as $key => $file) { ?>
<label for="file_<?php echo $key; ?>">
<input type="checkbox" name="file[]" id="file_<?php echo $key; ?>" value="<?php echo $file; ?>" />
<?php echo UPLOAD_DIR.DS.$file; ?>
</label>
<?php } ?>
<input type="submit" name="delete" value="Delete" />
</form>
<?php } ?>
The question is not clear to me but it appears you want to display the images in the form (beside each "delete" checkbox) so the user can see what they are deleting?
If so, can you try changing
<?php echo UPLOAD_DIR.DS.$file; ?>
to
<img src=<?php echo UPLOAD_DIR.DS.$file; ?> />

Categories