How to delete uploaded files PHP ajax - javascript

I want to delete a file uploaded after I click on a submit button or after the page is reloaded.
I did this drop zone to drag and drop file:
<div id="drop_file_zone" class="centered" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file" class="centered">
<p><strong>Drop file here</strong></p>
<p>or</p>
<p>
<input class="btn btn-danger btn-sm" id="selectfile3" type="button" value="Select File" onclick="file_explorer();" />
</p>
<input type="file" id="selectfile"/>
<div class="img-content" style="text-align: center;"></div>
</div>
</div>
On my drag_drop.js file:
var fileobj;
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function () {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function ajax_file_upload(file_obj) {
if (file_obj != undefined) {
var form_data = new FormData();
form_data.append('file', file_obj);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/app/helpers/upload_file.php", true);
xhttp.onload = function (event) {
oOutput = document.querySelector('.img-content');
if (xhttp.status == 200) {
if(this.responseText == 'false'){
console.log('no type');
} else {
oOutput.innerHTML = "<img src='/app/assets/img/pdf.png' alt='The Image' width='32' height='32'/><p>" + this.responseText + "</p>";
}
} else {
oOutput.innerHTML = "Error " + xhttp.status + " occurred when trying to upload your file.";
}
}
xhttp.send(form_data);
}
}
And on the upload_file.php this function:
<?php
$arr_file_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
echo "false";
return;
}
if (!file_exists('uploads')) {
mkdir('uploads', 0777);
}
$filename = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $filename);
echo $filename;
die;
but I don't really know how to delete these temps documents when I press the button (this button will save the document on a database) or when the page is reloaded.

Related

Try to open file using Click Counter with PHP

I want to prevent user from predicting the target script (test.php) AND do the whole "counter" logic on the server side.
I don't know how to achieve it with PHP.
I would like to open the file from the server side with PHP so the client will not have the possibility to see and know what file will open after 15 clicks. Because by typing the URL of the file it is possible to open it even before 15 clicks.
Thanks
HTML
<div id='overlay' class='overlay'></div>
<div class="view" id="view"></div>
<div class="canvas">
<div id="totalCounter" class="total-counter"></div>
<button id="clap" class="clap-container" tabindex="-1"></button>
<div id="clicker" class="click-counter">
<span class="counter"></span>
</div>
</div>
JAVASCRIPT
let accCounter = 0;
let totalCount = 0;
document.getElementById('totalCounter').innerText = totalCount;
document.getElementById('clap').onclick = function() {
const clap = document.getElementById('clap');
const clickCounter = document.getElementById("clicker");
upClickCounter();
loadDoc();
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter ++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("view").innerHTML = this.responseText;
}
};
xhttp.open("GET", "clickcheck.php", true);
xhttp.send();
document.getElementById("view").style.visibility="visible";
if (totalCount + accCounter%15) {
document.getElementById('view').style.visibility="hidden";
}
document.getElementById('overlay').style.display = 'block';
if (totalCount + accCounter%15) {
document.getElementById('overlay').style.display = 'none';
}
}
clickcheck.php:
<?php
session_start();
if (!array_key_exists('clickcount', $_SESSION)) {
$_SESSION['clickcount'] = 1;
}
if ($_SESSION['clickcount'] < 15) {
header('HTTP/1.1 404 Not found');
exit();
} else {
include("test.php");
}
?>

Uploading an image, then displaying it as a Canvas on the next page

I'm attempting to create a page that allows the manipulation of an uploaded image by using Canvas. So far, I've had no luck forwarding the image from one page (the submit form) to the other, which contains the canvas. I'm using PHP, Javascript and HTML in order to try and send the image from the submit form to the canvas space.
This is the submitting form.
<form action="designer.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label><?php
include('/tbp3/php/autoload.php');
header('Content-Type: application/json');
$fullpath = $_SESSION['activeImg'];
$size = getimagesize($fullpath);
echo json_encode(array('x' => $size[0], 'y' => $size[1], 'path' => $fullpath, 'lastPosJson' => isset($_SESSION['lastPos']) ? $_SESSION['lastPos'] : '[]'));
$db->close();
?>
<p>2-32 characters</p>
<input class="form-control" type="text" name="name" id="name">
</div>
<div class="form-group">
<p>JPEG/PNG under 2MB only</p>
<label class="btn btn-default" for="image">Choose Image</label>
<span></span>
<input class="inputfile" type="file" name="image" id="canvas">
</div>
<div class="form-group">
</div>
<input class="btn btn-primary" type="submit" value="Next">
</form>
This is the JavaScript I use in order to confirm the uploaded file is a PNG or JPEG. Note: I'm a novice at Javascript.
var validTypes = ['png', 'jpg', 'jpeg'];
$(document).ready(function(){
$('form').submit(function(e){//on submission..
var file = $('#upload').val();
var isValid = true;
var error = '';
if(file == ''){
error = 'Select a file before proceeding!';
$('#upload').addClass('validation-error');
isValid = false;
} else{
var type = /[^\.]*$/.exec(file).toString().toLowerCase();
if($.inArray(type, validTypes) == -1){
error = type + ' is an invalid type for the image! Please use ' + validTypes.join(', ').replace(/,([^,]*)$/, " or$1.");
$('#upload').addClass('validation-error');
isValid = false;
}
}
});
And this is on the page 'Designer.php'. I want the image to be displayed on the tag.
<div class="row canvasarea">
<div class="col-xs-6 header">Canvas</div>
<div class="col-xs-6 header">Live View</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6 help">TEXT</div>
<div class="col-xs-6 help">TEXT</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6">
<canvas id='canvas'></canvas></div>
<div class="col-xs-6">
<img id='liveupdate'/><br></div>
The PHP script I'm using to save it to the server.
<?php
require('/var/www/html/tpb3/php/autoload.php');
session_start();
$megabyte = 8000000;
$db = "new Database();";
function getImage(){
$id = $this->getTemplateId();
$type = $this->getFiletype();
return "img/template/$id.$type";
}
function addTemplate($templateId, $filetype){
if(!$this->isLoggedIn()){
echo "You're not logged in";
return '';
}
function isValidFileType($type){
$type = strtolower($type);
$types = array('jpeg', 'jpg', 'png');
for($i = 0; $i < count($types); $i++){
if($type === $types[$i]){
return true;
}
}
return false;
}
function isPng($filepath){
$img = #imagecreatefrompng($filepath);
if($img === false){
return false;
} else{
echo "Not a PNG";
imagedestroy($img);
return true;
}
}
function isJpeg($filepath){
$img = #imagecreatefromjpeg($filepath);
if($img === false){
return false;
} else{
echo "Not a JPEG";
imagedestroy($img);
return true;
}
}
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
if(!empty($_POST['selectedType']) ){
$selectedType = $_POST['type'];
}
if(isset($_POST["type"]))
$selectedType = $_POST["type"];
$dir = $selectedType == 'template' ? 'temp' : 'sourceimages';
if(isset($_POST["submit"])) {
$valid = true;
$id = uniqid();
$type = strtolower(pathinfo(basename($_FILES['upload']['name']), PATHINFO_EXTENSION));
$uploadFileDest = 'img/template/$id.$type';
$size = #getimagesize($_FILES["upload"]["tmp_name"]);
$error = '';
if($size === false) {
$error .= "Main image not a valid image, ";
$valid = false;
} elseif($size[0] > 2000 || $size[1] > 2000){
$error .= "Image larger than 2000px, ";
$valid = false;
} elseif(!isValidFileType($type)){
$error .= "Not a valid filetype, ";
$valid = false;
} elseif(!isJpeg($_FILES["upload"]["tmp_name"]) && !isPng($_FILES["upload"]["tmp_name"])){
$error .= "Image is not a valid jpg/png. ";
$valid = false;
} elseif ($_FILES["upload"]["size"] > 2 * $megabyte) {
$error .= "File larger than 2 MB, ";
$valid = false;
}
}
if($valid = true){
if($selectedType == 'template'){
$_SESSION['activeId'] = $id;
$_SESSION['activeImg'] = $uploadFileDest;
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
header('Location: designer.php');
} else{
$response = $db->addSourceImage($id, $type);
if($response == ';success'){
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
$_SESSION['lastId'] = $id;
header('Location: success.php');
} else{
header('Location: submit.php?e='.urlencode("Database failed with message: $response"));
}
}
} else{
header('Location: submit.php?e='.urlencode(substr($error, 0, strlen($error) - 2)));
}
}
?>
Any push into the right direction would be appreciated.

How to upload multiple files after removing some files from preview PHP JS

an example I've uploaded the 3 Image (files), In the preview, I did not like 1 file that has been deleted, rest of the files 2 and
it should upload 2 but when I press submit button 3 files inserting into the database
please help me not working
html code
<form action="" method="post" enctype="multipart/form-data">
<div id="filediv">
<input name="upload[]" type="file" id="upload" multiple="multiple" />
</div>
<input type="submit" value="Upload Image" name="submit"/>
</form>
Jquery code
function deletePreview(ele, i) {
"use strict";
try {
$(ele).parent().remove();
filesToUpload.splice(i, 1);
} catch (e) {
console.log(e.message);
}
}
$("#upload").on('change', function() {
"use strict";
var filesToUpload = [];
if (this.files.length >= 1) {
$("[id^=previewImg]").remove();
$.each(this.files, function(i, img) {
var reader = new FileReader(),
newElement = $("<div id='previewImg" + i + "' class='abcd'><img /></div>"),
deleteBtn = $("<span class='delete' onClick='deletePreview(this, " + i + ")'>delete</span>").appendTo(newElement),
preview = newElement.find("img");
reader.onloadend = function() {
preview.attr("src", reader.result);
preview.attr("alt", img.name);
};
var f = document.getElementById("upload").files[i];
filesToUpload.push(f);
if (img) {
reader.readAsDataURL(img);
} else {
preview.src = "";
}
newElement.appendTo("#filediv");
});
}
});
php code
$total = count($_FILES['upload']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "./upload_files/" . $_FILES['upload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
}
}
}
Thanks in advance

Uploaded file is not passing through JavaScript to PHP

Here i'm trying to pass uploaded file and a text input from HTML->JavaScript->PHP. But it is only passing the text input and failed to pass the file , i'm not getting that file in PHP. As a result it is showing undefined index error for "$u_file" in the PHP file. I don't understand where is the problem.
Here goes the HTML file
<body>
<div class="container">
<form class="form-horizontal" action="">
<h2><b>Post your job</b></h2><br><br>
<div class="form-group">
<label class="control-label col-sm-2">Job Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="jName" placeholder="Enter job name" name="jName" required>
<p id="jErr"></p>
</div>
</div>
<div class="form-group">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
<label class="control-label col-sm-2">Add some detailed description:</label>
<div class="col-sm-10">
<input id="u_file" value="u_file" type="file" name="u_file" size="5000000" multiple onchange="showname()"><br><br>
</div>
</form>
</div>
<div class="container-fluid text-center">
<br><button name="submitJob" id="submitJob" type="submit" class="btn btn-default" onclick="job_checker()">Submit</button>
<p id="submitJobErr"></p></div>
</form>
</div>
</body>
Here goes the JavaScript file
signFlagj = 0;
function job_checker() {
checkJobName();
databasejobEntry();
}
function checkJobName() {
var jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname)){
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else {
jobnameError.innerHTML = "";
}
}
function showname() {
jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
function databasejobEntry() {
if(signFlagj==1) {
console.log("fill up correctly!");
alert("Sign up correctly!");
}
else
{
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success") {
alert("Successfully submitted :)");
window.location.href = "uploadJob.html";
}
}
}
xhttp.open("GET", "uploadJob.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
Here goes the PHP file
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$val="";
$jobName = $_GET["jobname"];
echo "$jobName";
$u_file = $_FILES['jobFilename'];
$file_type = $_FILES['jobFilename']['type'];
$file_size = $_FILES['jobFilename']['size'];
$file_name = $_FILES['jobFilename']['name'];
print_r($u_file);
//echo "****************";
$currentdir = getcwd();
$targetfolder = $currentdir . "/testupload/";
// echo "****************";
print_r($targetfolder);
$targetfile = $targetfolder . basename( $_FILES['jobFilename']['name']) ;
//print_r($targetfolder);
print_r($currentdir);
//echo "****************";
$uploadOk=1;
print_r($file_type);
if ($file_type != "application/pdf" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/jpg") {
echo "Sorry, only JPG, JPEG, PNG & PDF files are allowed.";
$uploadOk = 0;
}
if (file_exists($targetfile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($uploadOk==0){
echo "Problem in uploading file";
}
else {
if(move_uploaded_file($_FILES['jobFilename']['tmp_name'], $targetfile)) {
$fileUpQueryjob = "INSERT INTO jobs (job_name,job_filename) VALUES ('$jobName','$file_name')";
$upJob = $db->query($fileUpQueryjob);
if ($upJob == true) {
$val = "Success";
echo "The file ". basename( $_FILES['jobFilename']['name']). " is uploaded";
}
else
echo "Error: " . $fileUpQueryjob . "<br>" . mysqli_error($db);
}
}
//echo "$val";
$db->close();
Use POST request instead of GET request. If necessary warp it in new FormData and post it.

File not Uploading in File Reader

I am using File Reader for selecting and uploading images.
My images are selected previewing but not uploaded when i hit submit button.
In upload.php the output of $_FILES is an empty array.
Where is problem?
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input id="fileUpload" multiple="multiple" type="file"/>
<input type="submit" value="Upload Image" name="upload">
<div id="image-holder">
</div>
</div>
</form>
Javascript
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
</script>
upload.php
<?php
require_once './include/db_connection.php';
if(isset($_POST['upload']))
{
print_r($_FILES);
die();
if(!empty($_FILES)){
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
//insert file information into db table
$sql = mysqli_query($link,"INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
echo 'file inserted';
}
else
{
echo 'Query not working';
}
}
else
{
echo 'No file selected';
}
}
Your file input doesn't have a name.
The name of a form control is used to determine what key it will have in the submitted data. Controls without them will not be successful (i.e. will not appear in the submitted data at all).

Categories