How to delete a file from a directory folder with php? - php

I'm echoing out users images from a folder, i don't have the names of the images stored. so i'm trying to take the src of the image file on .image_delete_btn click and pass that to delete_image.php where it can delete the file. I can't see why this isn't working. any suggestions are much appreciated.
PS: no errors, the delete_image.php script simply returns NULL, but the ajax request is being called. But I don't think the data is being passed.
HTML/PHP: (displays images from folder)
for ($i=0; $i<count($files); $i++){
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo '<div class="card company_photo_card">';
echo '<div class="image_delete_btn flaticon-error"></div>';
echo '<div class="img_hover_effect">';
echo '<img src="'.$image .'" alt="Random image" class="company_photos" />';
echo '</div>';
echo '</div>';
} else {
continue;
}
}
AJAX:
$('.image_delete_btn').click(function() {
var filename = $(this).next("div").first("img").attr("src");
$('.loading_gif').show();
m = confirm("Are you sure you want to delete this image?");
if (m == true) {
$.ajax({
type: 'POST',
url: 'confirm/delete_image.php',
data: {
filename: filename
},
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(response) {
$('.loading_gif').hide();
$(filename).fadeOut();
},
error: function(data) {
switch (data.info) {
case 'delete_error':
delete_error();
break;
case 'delete_success':
delete_success();
break;
}
}
});
} else {
$('.loading_gif').hide();
}
});
delete_image.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$filename = $_POST['filename'];
$file = basename($ImageData);
if (file_exists($filename)) {
unlink($filename);
$response["message"] = 'delete_success';
$errors++;
}
var_dump($filename);
echo json_encode($response);
exit();
}else{
echo"acces denied";
}
?>

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

jQuery submit form and php

I'm making a upload form and have chosen to do this with jQuery. The file gets uploaded but not into the desired folder, so im not parsing the data correct from the upload form to the process.
upload.php
<script>
$(document).ready(function()
{
var settings = {
url: "upload_process.php",
method: "POST",
allowedTypes:"jpg,jpeg,png",
fileName: "myfile",
galleryName: "<?php echo $gallery->folder; ?>",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
upload_process.php
$galleryName = $_POST["galleryName"];
$output_dir = "media/images/".$galleryName."/";
if(isset($_FILES["myfile"])) {
$ret = array();
$error = $_FILES["myfile"]["error"];
{
/* Single File */
if(!is_array($_FILES["myfile"]['name'])) {
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $_FILES["myfile"]["name"]);
$ret[$fileName] = $output_dir.$fileName;
/* Multiple files */
} else {
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++) {
$fileName = $_FILES["myfile"]["name"][$i];
$ret[$fileName] = $output_dir.$fileName;
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName );
}
}
}
echo json_encode($ret);
}
The file is uploaded to media/images/ and can't see why the $galleryName is not set?
The parameter passing to the script does not seem to be right. You did not specify the exact jQuery plugin that is being used, so the below example might not work, but if so, it should at least give You a good hint about what to look for in the plugin documentation
Please remove the line
galleryName: "<?php echo $gallery->folder; ?>",
And replace with lines
enctype: "multipart/form-data", // Upload Form enctype.
formData: { galleryName: "<?php echo $gallery->folder; ?>" },

if isset post with jquery (upload file)

When i remove "if(isset($_POST['_upload_profile_image'])){}" from users.php. Code is working and uploading.
How can i do this with 'isset($_POST'.
MY JQUERY
$("#upload_profile_image").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "/particley/global/post/users.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (html) {
if (html == 'true') {
//
} else {
//
}
}
});
}));
MY PHP
if(isset($_POST['_upload_profile_image'])){
$upload = ($_FILES['image']['tmp_name']);
if ($users->upload($upload) === TRUE) {
echo 'true';
} else {
echo 'false';
}
}
Is there any element in your form having name _upload_profile_image, If not then remove this line
if(isset($_POST['_upload_profile_image'])){
or replace with
if(isset($_FILE['image']) && !empty($_FILE['image'])){
Please replace this with your ph code
if(!empty($_FILES['image'])){
$upload = ($_FILES['image']['tmp_name']);
if ($users->upload($upload) === TRUE) {
echo 'true';
} else {
echo 'false';
}
}
For File upload There are various methods available to check files exist or not you can use any of them.
if (!empty($_FILES['image']['name'])) {
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
In your case you can use any of them :
if(!empty($_FILES['image'])){
$upload = ($_FILES['image']['tmp_name']);
if ($users->upload($upload) === TRUE) {
echo 'true';
} else {
echo 'false';
}
}

getting error while uploading image via Ajax

im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);

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..

Categories