Images Not Displaying - php

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; ?> />

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>

File not being created in PHP?

I've made this code in PHP because I want to practice file handling.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form action = "index.php" method = "get">
Do you want to make a new file (NF), edit a file (EF), or delete a file (DF)?
<input type = "text" name = "FileHandling">
<input type = "submit">
<br/>
</form>
<?php
$FileCommand = $_GET['FileHandling'];
if($FileCommand == 'NF') {
echo "<form action = 'index.php' method = 'get'><br/>";
echo "What is the new file's name?<br/>";
echo "<input type = 'text' name = 'CreateFile' method = 'get'><br/>";
echo "<input type = 'submit'><br/>";
$FileName = $_GET['CreateFile'];
echo $FileName;
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
}
?>
</body>
</html>
However, there is a problem after you choose 'NF' and type in the file name. The file does not get created:
echo $FileName;
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
}
You have a bug in the way you're handling inputs and forms. Currently, you're checking $FileCommand == 'NF', which is true on the first form submission. But then the page reloads and you get a second form with a new input. So when you fill in the second form and resubmit it, now <input name='FileHandling' /> wasn't submitted because it wasn't part of this form (it's part of the first form).
So if you change your PHP to the following, the file will be attempted to be created if $FileName !== null (regardless of the value of $FileCommand) rather than your previous logic which also required $FileCommand == 'NF'. This moves the logic for creating the file outside of the first if.
<?php
$FileCommand = $_GET['FileHandling'];
if ($FileCommand == 'NF') {
echo "<form action='index.php' method='get'><br/>";
echo "What is the new file's name?<br/>";
echo "<input type='text' name = 'CreateFile'><br/>";
echo "<input type='submit'><br/>";
echo "</form>";
}
$FileName = $_GET['CreateFile'];
if (null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
?>
Another way to handle this would be to create only a separate field instead of a completely separate form.
<html>
<body>
<form action="index.php" method="get">
Do you want to make a new file (NF), edit a file (EF), or delete a file (DF)?
<br>
<input type="text" name="FileHandling" />
<br>
<?php
$FileCommand = #$_GET['FileHandling'];
if($FileCommand == 'NF') {
echo "What is the new file's name?<br/>";
echo "<input type='text' name = 'CreateFile' /><br/>";
}
?>
<input type="submit">
</form>
<?php
$FileName = $_GET['CreateFile'];
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
?>
</body>
</html>
When you create new form get request blocked because of page reload.
This is working code to solve your problem.
<form method="get" action="index.php">
<input type="text" name="filehandling">
<input type="submit" name="createfile">
</form>
<?php
if ( isset($_GET['createfile']) ) {
$fh = $_GET['filehandling'];
if ($fh == 'NF') {
echo '
<form method="get">
<input type="text" name="filename">
<input type="submit" name="createnewfile">
</form>
';
}
}
if ( isset($_GET['createnewfile']) ) {
$filename = $_GET['filename'];
$f = fopen($filename, "w");
fclose($f);
}
?>
Try to use is_null() PHP function to get the desired result
Change your code to
if(!is_null($FileName)) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
}

Replace all the spaces in a file’s name with an underscore during the upload process

I have a file named upload_file.php which uploads an image file to my web server. The problem I am having is that I want to replace all the spaces in the file’s name with an underscore during the upload process. I know this could be done using str_replace(), but I have no idea where I should use str_replace() within my code. Any help will be greatly appreciated.
Here is the full code contained within my upload_file.php file:
<?php
require_once '../../config.php';
include '../secure.php';
if ($login_status != 1) exit();
if (isset($_GET['done'])) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if ($_POST['type'] == 'wallpaper') {
$directory = "../../files/";
}
else {
$directory = "../../files/images/";
}
$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (file_exists($directory . $_FILES["file"]["name"])) {
echo htmlspecialchars($_FILES["file"]["name"]) . " already exists. ";
}
elseif (((strpos($ext, "php") !== false) || $ext == 'aspx' || $ext == 'py' || $ext == 'htaccess') && !isset($allow_php_uploads)) {
echo 'Uploading PHP files disabled (<a target="_blank" href=""></a>)';
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $directory . $_FILES["file"]["name"]);
header("Location: upload-complete.php?type=".htmlspecialchars($_POST['type'])."&newfile=". htmlspecialchars($_FILES["file"]["name"])."&id=".intval($_POST['id'])."");
}
}
} else { ?>
<head>
<style type="text/css">
body {
margin:0px;
padding:0px;
}
</style>
</head>
<form action="upload_file.php?done=1" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" style="max-width:230px;" />
<input name="id" type="hidden" value="<?php echo intval($_GET['id']);?>" />
<input name="type" type="hidden" value="<?php echo htmlspecialchars($_GET['type']);?>" />
<input type="submit" name="submit" value="Upload" />
</form>
<?php } ?>
You could create a variable that holds the name of the file and replace all spaces there. Then in the rest of the code, replace $_FILES["file"]["name"] by that variable.
<?php
require_once '../../config.php';
include '../secure.php';
if ($login_status != 1) exit();
if (isset($_GET['done'])) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if ($_POST['type'] == 'wallpaper') {
$directory = "../../files/";
}
else {
$directory = "../../files/images/";
}
$filename = basename($_FILES['file']['name']);
$file = preg_replace('/\s+/', '_', $_FILES['file']['name']); // <-- Replace spaces
$ext = substr($filename, strrpos($filename, '.') + 1);
if (file_exists($directory . $file)) {
echo htmlspecialchars($file) . " already exists. ";
}
elseif (((strpos($ext, "php") !== false) || $ext == 'aspx' || $ext == 'py' || $ext == 'htaccess') && !isset($allow_php_uploads)) {
echo 'Uploading PHP files disabled (<a target="_blank" href=""></a>)';
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $directory . $file);
header("Location: upload-complete.php?type=".htmlspecialchars($_POST['type'])."&newfile=". htmlspecialchars($file)."&id=".intval($_POST['id'])."");
}
}
} else { ?>
<head>
<style type="text/css">
body {
margin:0px;
padding:0px;
}
</style>
</head>
<form action="upload_file.php?done=1" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" style="max-width:230px;" />
<input name="id" type="hidden" value="<?php echo intval($_GET['id']);?>" />
<input name="type" type="hidden" value="<?php echo htmlspecialchars($_GET['type']);?>" />
<input type="submit" name="submit" value="Upload" />
</form>
<?php } ?>
You have to try replace the spaces with underscores by having a whitelist and the replace function. So you can do something like:
$file = preg_replace("/[^-_a-z0-9]+/i", "_", $file);
I can't test it right now but something like that should work fine. Basically, it replaces the characters that they are not in the whitelist of the "[^-_a-z0-9]+/i".

uploading files in php using xampp

I have a problem in uploading files using php in XAMPP
my code is:
include 'header.html';
include 'header.php';
include 'debugging.php';
echo '<br />';
echo '<h1> Upload files</h>';
echo <<<_END
<br/>
<form method='post' action='FileUpload.php' enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='100' />
<input type='submit' value='Upload' />
<input type='hidden' name='submitted' value='1' />
</form>
<br/>
_END;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (isset($_POST['submitted'])) {
if ($_FILES && $_FILES['filename']['name']) {
$file_info = pathinfo($_FILES['filename']['name']);
$extension = $file_info['extension'];
include 'DO_Files.php';
$valid = DO_File::validExtension($extension);
echo '1';
if ($valid) {
echo '2';
$tmpName = $_FILES['filename']['tmp_name'];
$name = "Files//" . $_FILES['filename']['name'];
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $name)) {
echo '3';
echo "<p>there was an error..</p>";
echo error_get_last();
} else {
echo '4';
$file = new DO_File();
$file->FileName = $name;
$file->FileSize = $_FILES['filename']['size'];
if ($file->save()) {
echo '5';
echo $file->FileName;
} else {
echo '6';
mysqli_error($file->dbc);
}
}
} else {
echo '7';
echo '<p>the file is not prompted</p>';}
} else {
echo '8';
echo 'no filee';
}
}
include 'footer.html';
I don't know why it doesn't upload. it works in remote server but with local server like XAMPP it shows an error on
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $name)) {
any help? because I didn't figure put how to upload files to loacl server
I made a directory and the permissions are fine.
if (is_array($_FILES['filename']) && $_FILES['filename']['error'] == 0) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$sourcePath = $_FILES['filename']['tmp_name'];
$targetPath = "Files//" . $_FILES['filename']['name'];
if (!is_dir('Files//')) {
mkdir('Files/', 0777, true);
}
if (move_uploaded_file($sourcePath, $targetPath)) {
echo $targetPath;
}
}
}

How to display images to delete using PHP Unlink

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.

Categories