Error deleting image with AJAX and PHP using unlink - php

I am trying to delete a selected image from a folder with AJAX and PHP. I have not seen any error, could you please tell me your opinion about the code I have?
Thanks in advance
AJAX code:
function createAjax()
{
var objAjax = false;
if (window.XMLHttpRequest)
{
objAjax = new XMLHttpRequest ();
}
else
{
if (window.ActiveXObject)
{
try
{
objAjax = new ActiveXObject ("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
objAjax = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
else
{
objAjax = false;
}
}
return objAjax;
}
function eliminar(id_foto)
{
var ajax = createAjax();
ajax.open("POST", "delete_img.php",true);
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
//AQUI DEBES DE PONER EL CODIGO RESPECTIVO PARA ELIMINAR DEL NAVEGADOR
// EL DIV EN CUESTION o simplemente hacer su contenido vacio, que es lo que hare
document.getElementById("delete"+id_foto).innerHTML = "";
document.getElementById("div_mensajes").innerHTML
}
else
{
document.getElementById("div_mensajes").innerHTML = "<br><center>Eliminando<img src = 'images/ajax-loader.gif' /></center>";
}
}
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("id_foto="+id_foto);
}
HTML and PHP code to display it first:
$handle = opendir(dirname(realpath(__FILE__)).'/uploads/');
while($file = readdir($handle)) {
if($file !== '.' && $file !== '..') {
if(file_exists('uploads/Thumbs.db')){
unlink('uploads/Thumbs.db');
}
echo'<div class="gallery-item" id="delete'.$file.'">
<p class="gallery-clean">
<a class="image" rel="'.$file.'" rev="'.$file.'" href="uploads/'.$file.'" title="">
<img src="uploads/'.$file.'" alt="'.$file.'"></a></p>
<div>
<a class="ico ico-delete" rel="9" rev="2" href="#" onclick = "eliminar_ajax('.$file.');"><span></span></a>
<a class="ico ico-edit" rel="9" href="#"><span></span></a>
<a class="ico ico-resize" rel="9" href="#"><span></span></a>
<a class="ico ico-full" rel="group" href="#"><span></span></a>
</div></div>';
}
}
PHP code to delete the file:
$dir = "uploads/";
$file = $_POST['id_foto'];
$img = $dir.$file;
unlink($img);
Ok! I have solved using this:
script type="text/javascript">
function deleteFile(fname,directory)
{
$.ajax({ url: "delete_img.php",
data: {"file":fname,"directory":directory},
type: 'post',
success: function(output) {
alert(output);
$("#delete"+file).remove();
}
});
}
</script>
How can I remove the div if I call it
#delete.'<?php echo $file?>

And what is the extension of your image? Add it to $file like so $file .= ".whateverextensionithas";
To be more clear
$dir = "uploads/";
$file = $_POST['id_foto'];
$file .= ".whateverextensionithas";
$img = $dir.$file;
unlink($img);
Or to be real clear
$dir = "uploads/";
$ext = ".whateverextensionithas";
$file = $dir.$_POST['id_foto'].$ext;
if(file_exists($file))
unlink($file);
else
echo "file does not exist";

Try this piece of code:
if(isset($_POST['id_foto'])){
$dir = "uploads/";
$file = $_POST['id_foto'];
$img = $dir.$file;
$f = fopen($dir."post.txt", 'w+');
fwrite($f, $img);
fclose($f);
}
and inspect post.txt to see what sort of output you get.

Related

How to create php multiple file zone upload?

I have on my website upload.php file please I want to use this script on my server which controls the upload of files to the server and can only upload one file.
Now I would like to do a multiple file upload with a drop zone just like here:
Multiple file Upload
As far as I know, I can set up a javascript and html form, but I don't know how to modify my upload.php file, which controls the upload of files to the server. Please see below is my upload.php file that controls the upload of one file how to modify it so that multiple files can be uploaded at once with the script whose link I left above:
<?php
$error_message = "";
$success_message = "";
if (IS_POST()) {
if ($_FILES['upload']) {
$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$type = getFileTypeText($_FILES['upload']['type']);
$ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
$user = getUserFromSession();
$userId = $user->id;
if (!file_exists(ABSPATH . '/content/uploads/'.$userId.'/'.$name)) {
$acceptedExt = ['srt', 'ass', 'sub', 'sbv', 'vtt', 'stl'];
if (in_array($ext, $acceptedExt)) {
$db_name = GET_GUID() . "." . $ext;
$file_name_db = ABSPATH . '/content/uploads/' . $userId . '/' . $name;
$description = isset($_POST["description"]) && $_POST["description"] != '' ? $_POST["description"] : $name;
if ($size > 0) {
move_uploaded_file($_FILES['upload']['tmp_name'], $file_name_db);
chmod($file_name_db, 0666);
$id = db_insertUploadDetails($name, $description, $size, $userId, $ext, $name);
if ($id > 0) {
$success_message = "Uploaded successfully.";
echo "<script>location.href='list.php';</script>";
}
} else {
$error_message = "Not a valid file.";
}
} else {
$error_message = "Please upload only srt, ass, sub, sbv, vtt, stl";
}
}else{
$error_message="File Already Exists";
}
}
}
So your point is like ,you want to upload multiple files in series right.Use ajax to send it one after another and this will work.No need of any edits.
<!DOCTYPE html>
<html>
<head>
<title>Drag and drop Multiple files</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3>Drag and drop multiple file upload </h3><br />
<div id="drop_file_area">
Drag and Drop Files Here
</div>
<div id="uploaded_file"></div>
</div>
</body>
</html>
Use some css to tidy up the things.
ajax will be like this
<script>
$(document).ready(function () {
$("html").on("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
});
$("html").on("drop", function (e) {
e.preventDefault();
e.stopPropagation();
});
$('#drop_file_area').on('dragover', function () {
$(this).addClass('drag_over');
return false;
});
$('#drop_file_area').on('dragleave', function () {
$(this).removeClass('drag_over');
return false;
});
$('#drop_file_area').on('drop', function (e) {
e.preventDefault();
$(this).removeClass('drag_over');
var formData = new FormData();
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
formData.append('file[]', files[i]);
}
uploadFormData(formData);
});
function uploadFormData(form_data) {
$.ajax({
url: "upload.php",
method: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$('#uploaded_file').append(data);
}
});
}
});
</script>
this will be the upload.php .db_config will be your db connect file
<?php
// Include the database connection file
include('db_config.php');
$fileData = '';
if(isset($_FILES['file']['name'][0]))
{
foreach($_FILES['file']['name'] as $keys => $values)
{
$fileName = $_FILES['file']['name'][$keys];
if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'uploads/' . $values))
{
$fileData .= '<img src="uploads/'.$values.'" class="thumbnail" />';
$query = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
mysqli_query($con, $query);
}
}
}
echo $fileData;
?>
sanitizing the data is upto you.This is just an example

AJAX not receiving PHP response

My ajax request puts files into the directory.
However I receive no response from the PHP file.
I'm using alerts to determine if a response has been received.
Any help would be greatly appreciated.
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
exit('unable to upload'); // Prints success and exit the script
} else {
exit($file); // Prints success and exit the script
}
?>
UPDATE:
I success and error to ajax and it comes up as an error.:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
}
Use json_encode to send data back with AJAX.
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
echo json_encode(['filename' => false]);
exit(); // Prints success and exit the script
} else {
echo json_encode(['filename' => $file]);
exit();
}
?>
In your AJAX do this
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
}else {
alert('unable to upload');
}
},
error: function(){
alert('failure');
}
});
}
You can also use $.post() which is a shorthand for $.ajax() for POST request.
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.post('test.php', {data: canvasData}, function (response) {
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
} else {
alert('unable to upload');
}
})
}
You need to replace all spaces with plus sign (+).
Your code with a fix:
<?php
/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$img = str_replace(' ', '+', $img); // Here is a fix
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {
exit('unable to upload'); // Prints success and exit the script
} else {
exit($file); // Prints success and exit the script
}
?>

AJAX data displays different variable than PHP return

I have the PHP function:
public function add() {
$image = $this->input->post('image');
$headers = $this->travel_model->getFunction('headers');
//Add new uploaded image
if (!empty($_FILES['img']['name'])) :
//Check uploaded file extension
$file_parts = pathinfo($_FILES['img']['name']);
$ext = $file_parts['extension'];
if($ext == "jpg" || $ext == "jpeg" || $ext == "png") {
$image = md5($_FILES['img']['name']) . "." . $ext;
$img = ROOT.'resources/img/headers/'.$image;
move_uploaded_file($_FILES['img']['tmp_name'], $img);
$result = "passed";
} else {
$result = "error-img-format";
}
else :
$result = "passed";
endif;
//Check if is new added slideshow or editable slideshow
if($result != "error-img-format") {
if($this->input->post('id')) {
$this->headers_model->updateHeaders($image);
} else {
//Check if more than three slides and Delete the last slide
foreach($headers as $key => $hdr) {
if($key >= 2) {
$this->travel_model->deleteFunction($hdr->id, 'slideshows') ;
}
}
$this->headers_model->insertHeaders($image);
}
}
echo $result;
}
Uploaded an img with extensions different than .jpg, .jpeg or .png, PHP displays: error-img-format as it should do
JQuery:
$(document).ready(function () {
$('#add_headers').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/backend/headers/add',
data: $(this).serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
});
Alert displays passed, different than PHP does. Can't understand what's the problem..

responseText is working but responseXML is null

I am trying to open an XML file with Ajax. Its responseText is working fine but responseXML is returning null. I checked the syntax, there is nothing wrong with the syntax. I don't know what the problem is. Here is my code...
My HTML code
<div id='albumBox'>
<input type='file' multiple name='newsfeedAlbum[]' id='newsfeedAlbum' onchange='uploadNewsfeedImages()' />
</div>
<div id='uploadingImages'>
<progress id='newsfeedImageProgressBar'></progress>
</div>
<div>
<input type='button' id='albumButton' value='post' />
</div>
my JavaScript codeā€¦
function uploadNewsfeedImages()
{
//alert("loaded");
var files = document.getElementById("newsfeedAlbum").files;
var formData = new FormData();
var unixTimeStamp = Math.floor(((new Date).getTime())/1000);
formData.append("action","post");
formData.append("thing","album");
formData.append("unixTimeStamp",unixTimeStamp);
formData.append("album_to","news_feed");
for(var i = 0;i < files.length;i++)
{
var file = files[i];
//alert("file name is "+files.item(i).name);
formData.append("albumImages[]",file);
}
var xhr = new XMLHttpRequest();
xhr.open("POST","add_newsfeed.php",true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
//alert(xhr.responseText);
alert(xhr.responseXML);
}
}
xhr.upload.onprogress = function(event)
{
showProgress(xhr,event);
}
xhr.send(formData);
}
function showProgress(xhr,event)
{
var uploaded = event.loaded/event.total;
uploaded = Math.floor(uploaded*100);
//alert(uploaded);
document.getElementById("newsfeedImageProgressBar").value = uploaded;
}
Here is my php code...
session_start();
echo '<?xml version="1.0" encoding="UTF-8"?>';
header("Content-type: text/xml");
if(isset($_POST))
{
echo "<newsfeed>";
$action = $_REQUEST["action"];
if($action == "post")
{
$thing = $_REQUEST["thing"];
if($thing == "text")
{
}
elseif($thing == "album")
{
$succeded = array();
$failed = array();
$targetFolder = "images/";
$extensions = array("jpeg","jpg","bmp","png","gif");
foreach($_FILES["albumImages"]["name"] as $key=>$value)
{
//echo $key."=>".$value."<br />";
if($_FILES["albumImages"]["error"][$key] === 0)
{
$extension = strtolower(pathinfo($value,PATHINFO_EXTENSION));
if(in_array($extension,$extensions))
{
$source = $_FILES["albumImages"]["tmp_name"][$key];
$destination = $targetFolder.basename($value);
if(move_uploaded_file($source,$destination))
{
$succeded[] = $value;
}
else
{
$failed[] = $value;
}
}
else
{
$failed[] = $value;
}
}
else
{
$failed[] = $value;
}
}
if(count($succeded)>0)
{
echo "<succeded>";
for($i=0;$i<count($succeded);$i++)
{
echo "<succeded_file>".$succeded[$i]."</succeded_file>";
}
echo "</succeded>";
}
if(count($failed)>0)
{
echo "<failed>";
for($i=0;$i<count($failed);$i++)
{
echo "<failed_file>".$failed[$i]."</failed_file>";
}
echo "</failed>";
}
}
}
echo "</newsfeed>";
}
?>
It's probably because the content type of the file coming back from the sever is not xml.
Try using header('Content-Type: text/xml'); in your PHP code.

unable to create thumb nail in php

Am using PHP to create thumbnail from following code but when i run code i get following ERROR
Notice: Undefined variable: phpThumb in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
Fatal error: Call to a member function setSourceFilename() on a non-object in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
since am uploading multiple file how do i create thumb for all formate images
PHP processing code for uploading multiple image and creating thumb
<?php
$newname = uniqid() . '_' . time();
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
//thumb creation
$files = array("$file1", "$file1", "$file1", "$file1", "$file1");
foreach ($files as $file) { // here's part 1 of your answer
$phpThumb->setSourceFilename($file);
$phpThumb->setParameter('w', 100);
$outputFilename = "thumbs/" . $file;
if ($phpThumb->GenerateThumbnail()) {
if ($phpThumb->RenderToFile($outputFilename)) { // here's part 2 of your answer
// do something on success
} else {
//failed
}
} else {
// failed
}
}
}
}
?>
Edited again to reflect the posters new wishes of how the user experience should be. Now has a drag-drop with preview OR manual selection of 5 files. The drag-drop is submitted by a ajax post, so watch the console for the result. Display and flow needs to be streamlined, but shows a technical working example. The same PHP code handles both results.
<html>
<body>
<pre><?
print_r($_FILES); //SHOW THE ARRAY
foreach ($_FILES as $file) {
if (!$file['error']) {
//PROCESS THE FILE HERE
echo $file['name'];
}
}
?></pre>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var fd = new FormData();
$(document).ready(function() {
//submit dragdropped by ajax
$("#dropsubmit").on("click", function(e) {
$.ajax({
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
//FILES POSTED OK! REDIRECT
console.log(data);
}
});
})
var dropzone = $("#dropzone");
dropzone.on('dragenter', function (e) {
$(this).css('background', 'lightgreen');
});
//dropped files, store as formdata
dropzone.on('dragover', stopPropagate);
dropzone.on('drop', function (e) {
stopPropagate(e)
$(this).css('background', 'white');
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
preview(files[i])
fd.append('file' + (i + 1), files[i]);
if (i >= 5) continue
}
});
function stopPropagate(e) {
e.stopPropagation();
e.preventDefault();
}
if (window.File && window.FileList && window.FileReader) {
$("input[type=file]").on("change", function(e) {
preview(e.target.files[0])
});
} else {
alert("Your browser doesn't support to File API")
}
function preview(item) {
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
src: file.result,
title: file.name,
}).appendTo("#images");
});
fileReader.readAsDataURL(item);
}
});
</script>
<div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div>
<input type="button" id="dropsubmit" value="Submit dropped files" />
<hr>
<form method="post" enctype="multipart/form-data">
<input id="file1" name="file1" type="file"/><br>
<input id="file2" name="file2" type="file"/><br>
<input id="file3" name="file3" type="file"/><br>
<input id="file4" name="file3" type="file"/><br>
<input id="file5" name="file3" type="file"/><br>
<input name="submit" type="submit" value="Upload files" />
</form><div id="images"></div>
</body>
</html>

Categories