Image delete button not functioning correctly? - php

I'm trying to make a button that deletes an image which is uploaded on to my server. However, when I've uploaded an image then click delete nothing works it removes the image from the page but when I check the site directory it's still there. Plus there is no echo message appearing for DELETION COMPLETE either just DELETION FAILED, so it makes me wonder if it works at all and is just refreshing the page. No sure why this is, also is there a way to make it only show the loading image gif when the image is being rendered? Here's what I've got:
<?php
ob_clean();session_start();
if (isset($_GET['logout'])){
session_destroy();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
header("Location: index.php");
}
$loadingimage = false;
if(isset($_FILES['UploadFileField'])){
$allowed = array('jpg','png','jpeg');
$name = $_FILES["UploadFileField"]["name"];
$tmp = $_FILES['UploadFileField']['tmp_name'];
$type = $_FILES['UploadFileField']['type'];
$newName = "Image Attachment.jpg";
$types = array('jpg','png','jpeg');
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext,$types)){
move_uploaded_file($tmp, "UPLOADS/$newName");
echo '<font size="3"><p align="center"><b>UPLOAD SUCCESSFUL: </font><font color="#000000" size="3">Your document has now been uploaded and is ready to send.</b></p></font>';
$loadingimage = true;
}
else {
if(!$tmp){
echo '<font size="3"><p align="center"><b>UPLOAD FAILED: </font><font color="#000000" size="3">No document has been selected.</b></p></font>';
}
else {
echo '<font size="3"><p align="center"><b>UPLOAD FAILED: </font><font color="#000000" size="3">Uploaded document was an incorrect extension type, please use ".jpg", ".jpeg", or "png" only.</b></p></font>';
}
}
}
if (isset($_POST['submit'])){
header( 'Location: Review.php' );
}
if (isset($_POST['delete'])){
if ($loadingimage == true){
echo '<font size="3"><p align="center"><b>DETLEION COMPLETE: </font><font color="#000000" size="3">Image no longer available</b></p></font>';
unlink('UPLOADS/Image Attachment.jpg');
$loadingimage = false;
}
else{
echo '<font size="3"><p align="center"><b>DETLEION FAILED: </font><font color="#000000" size="3">No image available for deletion</b></p></font>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Attach Image</title>
<link href="CSS/boilerplate.css" rel="stylesheet" type="text/css">
<link href="CSS/master.css" rel="stylesheet" type="text/css">
<script src="JAVASCRIPT/respond.min.js"></script>
</head>
<body link="black">
<div class="gridContainer clearfix">
<div id="borderDiv">
<div id="navDiv">
<div id="backNavDiv">
<font color="white"><p align="left"><b> < Completed By</b></p></font>
</div>
<div id="logoutDiv">
<font color="white"><p align="right"><b>Log Out > </b></p></font>
</div>
</div>
<div id="headerDiv">
<p>Attach Image</p>
</div>
<?php
if($loadingimage == false){
echo '<div id="imageDiv"><img src="IMAGES/loading.gif"></div>';
}
else{
echo '<div id="imageDiv"><img src="UPLOADS/Image Attachment.jpg"></div>';
}
?>
<div id="loginBtnDiv">
<div id="uploadAreaDiv">
<form action="AttachImage.php" method="post" enctype="multipart/form-data" name="FileUploadForm" id="FileUploadForm">
<label for="UploadFileField"></label>
<input type="file" name="UploadFileField" id="UploadFileField"/>
<input type="submit" name="UploadButton" id="UploadButton" value="Upload"/>
</form>
</div>
<form action="AttachImage.php" method="post" enctype="multipart/form-data" name="delete" id="delete">
<input id="delete" name="delete" type="submit" value="Delete">
</form>
<form action="AttachImage.php" method="post" enctype="multipart/form-data" name="FileForm" id="FileForm">
<input id="submit" name="submit" type="submit" value="Next">
</form>
</div>
</div>
</div>
<div id="logoDiv">
<img src="IMAGES/Logo.png">
</div>
</body>
</html>

As I commented before, because you define $loadingimage = false;, you will only be able to delete the file if the file is being uploaded at the very same time - which seems rather pointless.
You should rather check if the file exists than using your $loadingimage variable for unlinking the file.
You could change
if ($loadingimage == true){
with
if (file_exists("UPLOADS/Image Attachment.jpg")) {
This will only delete the file if it exists, and prevent unlink from causing warnings.

Your $loadingimagevariable is always false. So you will never execute the unlink() function. If you think that it will be true because you set it to true in if(isset($_FILES['UploadFileField'])){}, it will not, because your page is reloaded and you passed the $_POST['delete'] to the page and $loadingimage variable will be set to false again. So remove the condition
if($loadingimage==true){} and your code should work. I don't see any reason why you're making this condition at all.

Related

Upload doesn't do anything when I hit the upload button

This is my first question here, I hope I can explain my problem. I have PHP code where I want to upload a PDF file and select a date, then upload it to a folder in my project called "pdfs". Then I want to download it but only until the date I chose at the upload is reached.
My upload doesn't work and I don't know why, here is my code:
<?php
include_once 'headeradmin.php';
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styleUpload.css">
<title>Umleitung hochladen</title>
</head>
<body>
<div class="container">
<div class="row">
<form action="umleitungen.php" method="post" enctype="multipart/form-data">
<h3>Umleitungen hochladen</h3>
<input type="file" name="fileToUpload" id="fileToUpload" accept="application/pdf"><br>
<p> Datum: <input type="date" name="ablaufdatum"></p> <br>
<button type="submit" name="save">Hochladen</button>
</form>
</div>
</div>
</body>
</html>
<?php
if (isset($_POST['submit'], $_POST['ablaufdatum']) && is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$date = strtotime($_POST['ablaufdatum']);
if (false === $date) {
return;
}
$mimeType = mime_content_type($_FILES['fileToUpload']['tmp_name']);
$allowedFileTypes = ['application/pdf'];
if (!in_array($mimeType, $allowedFileTypes, true)) {
return;
}
$destination = 'pdfs/' . date('Y-m-d', $date) . '_' . time() . '.pdf';
if (!file_exists($destination)) {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $destination)) {
echo 'Supi :)';
} else {
echo 'Upload fehlgeschlagen :/';
}
}
}
include_once 'footer.php';```
Check that the web server has permissions to write to the "pdfs/" directory.

Php Image Up load not working

I am trying to upload a image using PHP to a file, I am new to the langue so help is definitely appreciated. The image to be uploaded comes from a page with a from input, the code just doesn't seem to be executing! Thanks so much and here is my code (first html, second php):
I am trying to upload a image using PHP to a file, I am new to the langue so help is definitely appreciated. The image to be uploaded comes from a page with a from input, the code just doesn't seem to be executing! Thanks so much and here is my code (first html, second php):
<?php
include_once 'Includes/dbh.inc.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $_SESSION['user']; ?></title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Tajawal|Quicksand|Raleway:100" rel="stylesheet">
<link rel="stylesheet" tyle="text/css" href="main.css">
</head>
<body>
<!-- START Header -->
<section class="headuser">
<div class="pagetitle">
C A T C H Y .
</div>
<div class="username">
<?php echo $_SESSION['user']; ?>
</div>
</section>
<!-- END Header -->
<!-- START Bio -->
<section class="Bio">
<div class="friends">
<br>freinds<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div class="editbio">
<?php echo $_SESSION['user']; ?>
<form action="Includes/upload.php" id="bioimage" method="POST" enctype="multipart/form-data">
<input type="file" name="profileup">
<button type="submit" id = "submit" name="upload">Use!</button>
</form>
<form action="Includes/Post.inc.php" id="bioform" method="POST">
<textarea name="Text1" id= "content" placeholder="Tell everyone who you are" cols="50" rows="10"></textarea>
<br>
<button type="submit" id="submit" name="submit">Post!</button>
</form>
</div>
</section>
<!-- END Bio -->
</body>
</html>
if(isset($_POST['submit'])) {
$file = $_FILES['profileup'];
$fileName = $_FILES['profileup']['name'];
$fileTmpName = $_FILES['profileup']['tmp_name'];
$fileSize = $_FILES['profileup']['size'];
$fileError = $_FILES['profileup']['error'];
$fileType = $_FILES['profileup']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)){
if ($fileError === 0){
if ($fileSize < 1000000){
$filenamenew = uniqid('', true).".".$fileActualExt;
$filedest = 'profileimages/'.$filenamenew;
move_uploaded_file($fileTmpName, $filedest);
header("Location: ../UserProfile.php?suc");
}else{
echo "your file was to big";
}
}else{
echo "There was an error uploading your file";
}
}else{
echo "you cant upload files of this type";
}
}else{
header("Location: ../UserProfile.php?fail");
}
?>
I think you can use your button name "upload".
if(isset($_POST['submit']))
when you submit an image it must be working.
if(isset($_POST['upload']))
problem for not execution of php script in upload page is tthis line
if(isset($_POST['submit'])
because this check input submit is set in your html you have named submit button as upload
solution change name ofhttml buttton to submitt or change if condition to this
if(isset($_POST['upload']))

how can I upload a pdf and an image in php mysql

I am trying to upload a pdf file and an image in php mysql but it seems that the move_uploaded_file function can only work with one file. I have tried to make it work with both files but it doesn't seem to me working. It moves just the images to the target folder and adds both image name and pdf name to the database but it doesn't move the pdf to target folder. This is the code. pls help
<?php
session_start();
require_once("includedfunctions.php");
include 'dbh.php';
if (isset($_POST['submit'])){
$title=$_POST['title'];
$author=$_POST['author'];
$target = "img/pic_book/";
$target2 = "img/pdf/";
$imgname = basename($_FILES["cphoto"]["name"]);
$bookname = basename($_FILES["book"]["name"]);
$newname = $target.basename($_FILES["cphoto"]["name"]);
$newname2 = $target2.basename($_FILES["book"]["name"]);
$img_type = pathinfo($newname,PATHINFO_EXTENSION);
$book_type = pathinfo($newname2,PATHINFO_EXTENSION);
if($img_type!='jpg' && $img_type!='JPG' && $img_type!='png' && $img_type!='PNG'){
$message="Please ensure you are entering an image";
}else{
if($book_type != 'pdf'){
$message="books must be uploaded in pdf format";
}else{
if(!preg_match("/^[a-zA-Z'-]+$/",$author)){
$message = "<p style='color:red'>Please enter the real name of the author; not a nickname.</p>";
}else{
if (move_uploaded_file($_FILES["cphoto"]["tmp_name"], $newname)) {
if(move_uploaded_file($_FILES["book"]["tmp_name"], $newname2));{
$sql = "INSERT INTO books (Title, Author, pathtopdf, pathtoimage) VALUES ('$title', '$author', '$bookname', '$imgname')";
$result = mysqli_query($conn, $sql);
if($result){
$message = "upload successful";
}else{
$message = "upload failed1";
}
}
}else{
$message = "upload failed";
}
}
}
}
}
else{
$message="";
$title="";
}
?>
<html>
<head>
<title>Libraria</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/contactcss.css" rel="stylesheet">
<script src="js/respond.js"></script>
</head>
<body>
<br><br><br><br><br>
<!-- content -->
<div class="container">
<?php
echo '<p>Welcome ' . $_SESSION['name']. '</p><br>';
echo '<p>' . $message. ' </p>';
?>
<br><br>
<!--form-->
<div class="row">
<form action="admin2.php" method = "post" enctype="multipart/form-data">
<label for="Title">Title</label><br>
<input type="text" id="fname" value ="<?php echo $title; ?>" name="title" placeholder="Title of the book" required><br>
<label for="author">Author</label><br>
<input type="text" id="lname" name="author" placeholder="Author of the book" required><br>
<label for="Cover photo">Cover photo</label><br>
<input type="file" id="cphoto" name="cphoto" required><br>
<label for="book">Book</label>
<input type="file" id="book" name="book" required><br>
<button class="submit" type="submit" name="submit"><b>Upload</b></button>
</form>
</div>
</div>
</body>
</html>
Code is all correct. just check pdf size. if size is more than 4MB than it will not allowed to upload. you need to increase upload file size in php.ini file or apache config settting file.
Have a great day :)
application/pdf is the mime type for pdf not just pdf.

PHP create folder inside ($_POST)

I need to upload the image to a server and store to the directory created by PHP using current timestamp. Below is the relevant part of the code, but not working as expected, it's not creating a folder as well it's not printing to the console. What could be the issue?
Edit:
Modified php based on below comment
upload.php
<?php
//get unique id
$up_id = uniqid();
?>
<?php
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$user = "user";
//console.log("debug.......");
echo "debug.......";
if (!file_exists("/var/www/Scan")) {
mkdir("/var/www/Scan", 0777, true);
}
$folderName = date("Y-m-d") . "_" . date("h_i_sa") . "_" . $user;
if (!file_exists("/var/www/Scan/$folderName")) {
mkdir("/var/www/Scan/$folderName", 0777, true);
}
$folder = "/var/www/Scan/$folderName";
//specify redirect URL
$redirect = "upload.php?success";
//upload the file
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
//do whatever else needs to be done (insert information into database, etc...)
//redirect user
header('Location: '.$redirect); die;
}
//
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Upload your file</title>
<!--Progress Bar and iframe Styling-->
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<!--Get jQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<!--display bar only if file is chosen-->
<script>
$(document).ready(function() {
//
//show the progress bar only if a file field was clicked
var show_bar = 0;
$('input[type="file"]').click(function(){
show_bar = 1;
});
//show iframe on form submit
$("#form1").submit(function(){
if (show_bar === 1) {
$('#upload_frame').show();
function set () {
$('#upload_frame').attr('src','upload_frame.php?up_id=<?php echo $up_id; ?>');
}
setTimeout(set);
}
//document.getElementById("message").innerHTML = "";
});
//
});
</script>
</head>
<body>
<div id="outPopUp">
<h1 >Upload your file </h1>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<br />
<br />
<!--Choose a file to upload<br />-->
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $up_id; ?>"/>
<!---->
<!-- <input name="file" type="file" id="file" size="30"/>-->
<label class="custom-file-upload">
<input name="file" type="file" id="file" onclick="myFunction()" />
Choose Video
</label>
<!--Include the iframe-->
<br />
<br />
<iframe id="upload_frame" name="upload_frame" color= black frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<!---->
<br />
<input class="btn btn-blue" name="Submit" type="submit" id="submit" value="Submit" />
<br />
<br />
<?php if (isset($_GET['success'])) { ?>
<span style="color:#FFFFFF;" id="message" class="notice">Your file has been uploaded.</span>
<?php } ?>
</form>
</div>
<script>
function myFunction() {
document.getElementById("message").innerHTML = "";
}
/*document.getElementById('file').onchange = function () {
//alert('Selected file: ' + this.value);
var path = this.value;
var fileName = path.replace(/.*(\/|\\)/, '');
alert('Selected file: ' + fileName);
//myFunction(fileName);
};*/
</script>
</body>
</html>
try a simple example for understanding:
<?php
//php content
if ($_POST) { //here we are checking $_POST values that $_POST has some values.
//specify folder for file upload
$tempDir = __DIR__ . DIRECTORY_SEPARATOR . 'upload'; //it means make a directory uploads where this php file is kept.
if (!file_exists($tempDir)) { // if $tempDir is not there, so it will create that directory.
mkdir($tempDir);
}
if(!empty($_FILES))//now checking your uploaded file is not empty
{
$nm=$_FILES['file']['name']; //here $nm get the name of the file
$tmp=$_FILES['file']['tmp_name'];//$tmp get the temporary file stored path
$mDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR .time().$nm; //this your destination path with time+nameof file as a name of file.
if(move_uploaded_file($tmp,$mDir)) //uploading file to your destination path, if uploaded then it will go in the if scope and echo.
{
echo "file uploaded with timestamp in uploads folder";
//now redirect from here any where
}
else
{
echo "fail to upload a file";
}
}
}
?>

Click image , that will show on a new tab with 100% width

Hi every one i have make some php pages that is about web design presenter, and my problem is that, i receive image from user and save it into a folder and show all the saved images with href image link but , when i click on a image it will open only image in browser not in any page.
how to resolve this issue kindly help me.
my code is .
<html>
<head>
<link rel="stylesheet" type="css/text" href="style.css">
<title>Uploading Files via PHP</title>
</head>
<body>
<center><form action="file.php" method="post" enctype="multipart/form-data">
<table border="2">
<tr height="100"><td>Upload A file:</td>
<td><input type="file" name="file"></td></tr>
<tr height="100"><td>Click Upload File:</td><td><input type="submit" name="submit" value="Upload File"></td></tr>
</table>
</form></center>
<?php
if (isset($_POST['submit'])) {
$name=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$size=$_FILES['file']['size'];
$tmp=$_FILES['file']['tmp_name'];
if ($name==''){
echo "<script>alert('Please Select a file from computer!')</script>";
exit();
}
if (($type == "image/jpeg") || ($type == "image/gif") || ($type == "image/png")) {
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo "This file $name is already exist!<br> please try another one..";
exit();
}
if ($size <= 50000){
move_uploaded_file($tmp,"images/$name");
echo "<center><font color=red>File was uploaded successfully!</font><br>Uploaded Image is here<br><img src='images/$name'> </center>";
}
else {
echo "Size of the image $size is larger than 50kb and it's not allowed... <br> image size must be less than 50kb..";
}
}
else {
echo "$type this is not a valid type of file<br>only upload Jpeg, PNG and Gif images";
}
}
?>
<div class="container">
<div class="row">
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<div class="col-sm-4"><img src="'.$num.'" alt="random image" class="demo"/></div>';
}
?>
</div>
</div>
<script>
function fullwin(){
window.open("bigpage.php","bfs","fullscreen,scrollbars")
}
</script>
</body>
</html>

Categories