I want to check existence of a folder called $subdomaine in the directory \cms\sites\ on the keyup.
Here is my script:
<script>
$(document).ready(function(){
$('#subdomain').keyup(subdomain_check);
});
function subdomain_check(){
var subdomain = $('#subdomain').val();
if(subdomain == "" || subdomain.length < 4){
$('#subdomain').css('border', '3px #CCC solid');
$('#tick').hide();
}else{
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain='+ subdomain,
cache: false,
success: function(response){
if(response == 1){
$('#subdomain').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('#subdomain').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
</script>
ajax.php :
<?php
$dirname = $_SESSION["subdomain"];
$filename = DOCUMENT_ROOT."sites/".$dirname;
if (!file_exists($filename)) {
echo "The directory $dirname exists.";
exit;
}
How do I check the existence of the folder at the input ?
Thanks
Try this, you need to use is_dir() function to check given file name is directory.
if (is_dir($filename)) {
echo "The directory $dirname exists.";
exit;
}
For your ajax response,
if (is_dir($filename)) {
echo 1;
}else{
echo 0;
}
better way---
NB: change $_SESSION to $_POST too.
<?php
$dirname = $_POST["subdomain"]; //look this
$dir = DOCUMENT_ROOT."sites/".$dirname;
if(file_exists($dir) && is_dir($dir)){
echo "The directory $dirname exists.";
exit;
}
?>
Related
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
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; ?>" },
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';
}
}
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";
}
?>
I am trying to upload a file using ExtJS and PHP.
My file is not uploading to the server.
JS:
function slidersave(){
var form = sliderform.getForm();
if (form.isValid()) {
var slider_name=Ext.getCmp('txtslidername').getValue();
var slider_image=Ext.getCmp('txtsliderimage').getValue();
var slider_link=Ext.getCmp('txtsliderurl').getValue();
form.submit({
url: 'slider/file',
waitMsg: 'Uploading your slider image...',
success: function(form, o) {
var obj = Ext.util.JSON.decode(o.response.responseText);
alert(obj);
if (obj.failed == '0' && obj.uploaded != '0') {
Ext.Msg.alert('Success', 'All files uploaded');
} else if (obj.uploaded == '0') {
Ext.Msg.alert('Success', 'Nothing Uploaded');
} else {
Ext.Msg.alert('Success',
obj.uploaded + ' files uploaded <br/>' +
obj.failed + ' files failed to upload');
}
}
});
}
}
PHP:
public function file()
{
if(isset($_FILES)){
$uploaddir = '/siteimages/slider/';
$uploadfile = $uploaddir . basename($_FILES['txtsliderimage']['name']);
if (move_uploaded_file($_FILES['txtsliderimage']['tmp_name'], $uploadfile)) {
echo '{success: true}';
} else {
echo '{success: false}';
}
}
}
I am not getting anything in the response the loader just disappears after sometime.
I don't know what's happening.