Basically what i am trying to do is- create a page to upload file. Below is the code and its working fine:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function wow_default_alert() {alert("Successfully saved!"); }
</script>
</head>
<body>
<form action="index.php" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if (!file_exists('.\\tigerimg\\'))
{
mkdir('.\\tigerimg\\', 0777, true);
}
$target_dir = '.\\tigerimg\\';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
"File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
"File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
echo '<script type="text/javascript">
wow_default_alert();
</script>';
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
But the problem is that if i refresh the page again -after uploading one file successfully, it works with the same post values.
Previously i used the below code to unset post data-which worked for other pages.
clear Code-1
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>
But i cant use it in this one. It shows error:
Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 41
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 47
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\up\index.php on line 47
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 62
So, i tried to also clear the FILES array too by adding 3 lines with the above code.
clear Code-2
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
$_SESSION['filedata'] = $_FILES; //new code
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
$_FILES = $_SESSION['filedata']; //new
unset($_SESSION['postdata']);
unset($_SESSION['filedata']); //new
}
?>
But now its showing only one error:
Warning: getimagesize(C:\xampp\tmp\php1A2F.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\up\index.php on line 51.
>>> So, here is one question- why is this happening?
Ok, now i tried another way put the above [clear Code-1] inside a php function function remove_post() and call it just after the code of successful uploading- where i called the alert.
This time its working fine. But now the problem is that the alert doesn't appear. So, is it possible to call the function remove_post() when user clicks the ok in alert.
It looks like you are trying to copy from W3Schools web site, which is not the greatest of places. At any rate, in this instance, I think you may want to do all your processing at the top of your page like so:
<?php
// Not sure if you are storing anything in sessions...
session_start();
// Create a root
define("ROOT_DIR",__DIR__);
// Create a function so you can customize it if you want to
function SaveFileToDisk($dir = '/tigeimg/',$allow = array("image/png","image/jpeg","image/gif"))
{
// Make directory if not exists
if(!is_dir($mkdir = ROOT_DIR.$dir)) {
if(!mkdir($mkdir,0755,true))
return 'mkdir';
}
// Filter filename
$name = preg_replace("/[^0-9a-zA-Z\.\_\-]/","",$_FILES["fileToUpload"]["name"]);
// Assign name
$filename = (!empty($name))? $name : false;
// If empty, record error
if(!$filename)
$error[] = 'nofile';
// Get mime type
$mime = (!empty($_FILES["fileToUpload"]["tmp_name"]))? getimagesize($_FILES["fileToUpload"]["tmp_name"]) : false;
// Record if invalid
if(!$mime)
$error[] = 'invalid';
// Filter out double forward slashes (if user decides to change $dir)
// and adds too many forward slashes
$final = str_replace("//","/",ROOT_DIR."/".$dir."/".$filename);
// If file exists, record error
if(is_file($final))
$error[] = 'exists';
// If too big record error
if($filename > 500000)
$error[] = 'size';
// If not in the allowed file types, record error
if(!in_array($_FILES["fileToUpload"]["type"],$allow))
$error[] = 'type';
// Return array of errors
if(!empty($error))
return $error;
// True or false if no errors are recorded previously
return (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$final));
}
// Just create a simple error returning function
// This is expandable by adding error descriptions stored in database if desired
function ErrorReporting($value = false)
{
$msg['invalid'] = "INVALID File!";
$msg['type'] = "The file you are trying to upload is not a valid image type.";
$msg['exists'] = "The file you are trying to upload is already uploaded.";
$msg['size'] = "The file you are trying to upload is too large.";
$msg['nofile'] = "The file you are trying to upload has no name.";
if($value === true)
return "Successfully uploaded!";
elseif(is_array($value)) {
foreach($value as $error) {
$err[] = (!empty($msg[$error]))? $msg[$error]:"";
}
if(!empty($err))
return implode("",$err);
}
else
return "File failed to upload.";
}
// If post is submitted
if(isset($_POST["submit"]))
// Run the uploader function
$success = SaveFileToDisk();
?><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
<?php
// if there is an upload, run the js alert
if(isset($success)) {
?>
function error_alert(errmsg)
{
alert(errmsg);
}
error_alert("<?php echo ErrorReporting($success); ?>");
<?php }
?>
</script>
</head>
<body>
<form action="" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
After user clicks OK for alert you can call the php function as
alert('Your alert');
document.write(' <?php remove_post(); ?> ');
Your remove_post() function will get called after user click OK on alert
Related
I got totally lost.
Ive tried to make some Image Upload function in PHP and everything works fine. Because i dont want the whole Page to reload, when uploading a File i wanted to use AJAX with Jquery, to send the Form Content (Image) via POST to a file like upload.php with an hidden ajax request.
No matter what i try its impossible to send anything with formData(). I copied & pasted several Sample Codes, tried changing the Code, nothing happens when i use formData().
A normal request with Jquery / Ajax, using POST works fine.
Here ist the Sample of my last used Code..
Could my XamPP has been misconfigured, or what could cause that really not one of the Scripts from google, tutorial pages etc works?
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
<button id="Knopf">Knopf</button>
<div id="Disp">fghfgh</div>
</body>
<script>
$(document).ready(function(){
$("#Knopf").click(function(){
var formData = new FormData(Test);
$.ajax({
url : "uploadtest2.php",
type : "POST",
data : formData,
cache : false,
contentType : false,
processType : false,
success : function() {
$("#Disp").html(result);
}
});
});
});
</script>
</html>
<?php
$target_dir = "Media/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The problem is this:
if(isset($_POST["submit"])) {
There's no element named submit in the form, so this check fails. Even if you had a submit button in the form, it wouldn't be included in formData, because buttons are only automatically included in POST data when they trigger normal form submission.
You can add that to formData.
var formData = new FormData(Test);
formData.set("submit", "1");
Or you could change your test to
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
Please see: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
You must use a Form Element:
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
Consider the following example.
$(function() {
$("#Test").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "uploadtest2.php",
type: "POST",
data: formData,
cache: false,
contentType: false,
processType: false,
success: function(result) {
$("#Disp").html(result);
}
});
});
$("#Knopf").click(function() {
$("#Test").submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" />
</form>
<button id="Knopf" type="submit">Knopf</button>
<div id="Disp">fghfgh</div>
It is better to bind to the submit callback. This way, if the User submits the form or clicks Submit, the callback is triggered. We need to .preventDefault() on the Event to ensure the Form doesn't post or submit the data. Now we can then perform the AJAX call without the page being refreshed.
In your success callback, you must pass in a variable to be used for the returned data. Otherwise result will be undefined.
With the proper FormData, there should be no issue uploading. this in the callback refers to the Form Element itself.
Consider updating your PHP as well:
if(isset($_POST["submit"])) {
Change this to:
if(isset($_POST["fileToUpload"])) {
I am trying to create a form where when the user chooses a file, the file chosen will automatically upload to the database by going to the action in form. I used the onchange function and it just sends me to my php file in which that file contains my uploading system. What i think my problem is about my $_POST['asdasd'], but i cant really think of any other solutions to this.
Here is my form:
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
</form>
The PHP File:
if (isset($_POST['submit'])) {
$target_dir = "../users/".$_SESSION['u_id']."/image/";
$str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$rand = substr(str_shuffle($str), 0, 10);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($temp);
$target_file = $target_dir . $newfilename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ". <br/>";
$uploadOk = 1;
} else {
echo "File is not an image. <br/>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. <br/>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
echo "Sorry, your file is too large. <br/>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. <br/>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. <br/>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
require 'database_inc.php';
$sql = "UPDATE `users` SET `user_profile` = '$newfilename' WHERE 1";
if (mysqli_query($conn,$sql)) {
$_SESSION['profile_picture'] = $newfilename;
header("Location: ../profile.php");
} else {
echo "The query has not been updated. <br/>";
}
} else {
echo "Sorry, there was an error uploading your file. <br/>";
}
}
}
It is not saving because in the php file you have the line
if (isset($_POST['submit'])) {
add in the form a hidden field
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
<input type="hidden" name="submited" value="1" />
</form>
And in php change the line
if (isset($_POST['submit'])) {
to
if (isset($_POST['submited'])) {
That should do it
Instead of doing the $_POST['submit'] validation, try to check if the request is a $_POST.
To do that you can use something like
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }
or
if ($_SERVER['REQUEST_METHOD'] === 'POST') {…}
i recommend you to use the first one.
PHP doc: http://php.net/manual/pt_BR/function.filter-input.php
I am stuck on my codes from 2 days now. I have already tried more then 100 tutorials/guide but none of them solve my problem. Mostly guide is for database.
I am using ready made gallery plugin to display images on my website. This gallery does not use database. For that I made admin panel with upload function. Now i am looking for function to delete uploaded photos from admin panel. one pic at a time or multiple option will be more then good.
Right now with this code i am displaying images in Admin Page at main.php which i uploaded before:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,gif,png,bmp}", GLOB_BRACE);
$folder = opendir($folder_path);
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="250" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
And i am trying this delete code in delete.php
<?php
$filename = $_POST['fname'];
$path = $_POST['directory'];
if(file_exists($path."/".$filename)) {
unlink($path."/".$filename); //delete file
}
?>
So i need a function to delete file from server with confirmation and with delete button. Right now file just open with a click. This function will be only for admin, So i think i am safe with delete function as i read in similar topics.
Thanks in Advance.
EDIT 1:
So far this code successfully delete a file from server (Answer from #Jocelyn):
<h3>Delete Now!</h3>
<?php
if(isset($_GET['delete']))
{
unlink(__FILE__);
}
?>
Change this unlink(__FILE__); to unlink("$file_path");
EDIT 2:
Sorry, it does delete file from server but its deleting all the files in that directory.
Is there anyway to delete only one file which i click.
Right now all photos appearing from one link of code, i think thats the problem.
The link is this from which photos are appearing:
<img src="<?php echo $file_path; ?>" height="250" />
A very quickly cobbled together example of how you might achieve your goal using ajax to send the filename to the delete.php script. No doubt that because it's not tested there may well be issues - but it's a starting point.
<?php
/* delete.php */
$img=!empty( $_GET['name'] ) ? $_GET['name'] : false;
$result=false;
if( $img ){
/*
here you would typically check that the path sent via ajax exists
and then use unlink to delete the file before sending a response
to the ajax callback function - the callback would then inform the
user that the file has been deleted ( or not! )
For testing though a simple message will suffice so that files are not deleted unnecessarily!!!
-- uncomment the line below to actually attempt deletion of file.
*/
if( file_exists( $img ) ){
#$result = #unlink( $img );
clearstatcache();
}
echo $result ? 'The file '.$img.' was deleted' : 'The file '.$img.' could not be deleted';
}
?>
<?php
$root='c:/wwwroot';
?>
<!-- /* admin page that lists images */ -->
<html>
<head>
<title>Delete images - no database</title>
<script>
function ajax(imagename,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.status==200 && xhr.readyState==4 ){
callback.call( this, xhr.response );
}
};
xhr.open( 'GET', 'delete.php?name='+imagename, true );
xhr.send();
}
function deleteimage(e){
e.preventDefault();
ajax.call( this, e.target.dataset.path+'/'+e.target.dataset.name, cbdeleteimage );
}
function cbdeleteimage(r){
alert( r );
}
function bindEvents(){
var col=document.querySelectorAll('img.delete');
for( var n in col )if( col[ n ].nodeType==1 ) col[n].addEventListener( 'click', deleteimage, false );
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<?php
$dir = 'gallery-images/'; /* YOUR path */
$dir = $root . '/images/misc/'; /* MY test path */
$files=preg_grep( '#(\.jpg|\.jpeg|\.png|\.bmp|\.gif)#i', glob( $dir . '*.*' ) );
$html=array();
foreach( $files as $file ){
if( $blocal ) $file=str_replace( $root, '', $file ); /* remove MY site root from file names */
$name = pathinfo( $file, PATHINFO_BASENAME );
$path = pathinfo( $file, PATHINFO_DIRNAME );
$html[]="<img class='delete' src='{$file}' data-name='{$name}' data-path='{$path}' />";
}
echo implode( PHP_EOL, $html );
?>
</body>
</html>
So this is the final code which is perfectly fine for noobs like me who stuck with their work:
this is Delete.php to delete only a requested file
<?php
$file = $_GET['delete'];
if(isset($_GET['delete']))
{
unlink("./gallery-images/$file");
header("Location:home.php");
}
?>
This is upload.php to upload file with rename to auto increment value:
<?php
// Upload and Rename File
if (isset($_POST['submit']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg');
$count = count (glob ('gallery-images/*'));
if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000000))
{
// Rename file
$newfilename = ($count + 1) . $file_ext;
if(file_exists("gallery-images/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "gallery-images/" . $newfilename);
header("Location: home.php");
exit;
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 10000000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
?>
This is home.php to display image with delete feature:
Upload Form:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload: <br />
<input type="file" name="file" id="file"><br /><br />
<input type="submit" value="Upload Image" name="submit">
</form>
Display photos from directory:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,png}", GLOB_BRACE);
$folder = opendir($folder_path);
$file = '$file_path';
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'jpeg' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="175" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
Delete confirmation popup script:
<script>
function deleletconfig(){
var del=confirm("Are you sure you want to delete this record?");
if (del==true){
}
return del;
}
</script>
Hope this will be helpful for learners.
Thanks.
I would like to return an error on a case from my php code that handles the upload.
Currently if the php upload fails the JS still thinks it successes which I presume is to do with the fact it returned fine.
I have tried returning false instead of a string but that still runs the this.on('success') function.
PHP
public function imageUpload(){
//Сheck that we have a file
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
($_FILES["file"]["size"] < 3500000)) {
//Determine the path to which we want to save this file
$newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
}
JS
$(document).ready(function(){
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone('div#imagesdropzone', { url: '/admin/imageUpload',
parallelUploads: 100,
maxFiles: 100,});
});
Dropzone.options.imagesdropzone = {
init: function() {
this.on('success', function( file, resp ){
console.log( file );
console.log( resp );
});
this.on('error', function( e ){
console.log('erors and stuff');
console.log( e );
});
}
};
Yes, its right. You have to set an HTTP Header.
Have a look at:
https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-an-error-returned-by-the-server
If you have an HTTP Error and want to show it in the hover error message of DropzoneJS you can:
myDropzone.on("error", function(file, message, xhr) {
var header = xhr.status+": "+xhr.statusText;
$(file.previewElement).find('.dz-error-message').text(header);
});
(You need jQuery for that code [$().find();])
The other way would be to return a JSON error message via PHP:
//define text for error message
$output['error'] = 'No Token';
//return right HTTP code
if( $error ){
http_response_code (401);
}
else{
http_response_code (200);
}
//set Content-Type to JSON
header( 'Content-Type: application/json; charset=utf-8' );
//echo error message as JSON
echo json_encode( $output );
Where does this.on('success') take the information about the success/failure of the (internal) PHP upload process?
I guess from the HTTP header's status code, which is 200 (OK) even if the upload failed (it just prints some error text).
I recommend you to set a 500 header if the upload fails.
Use below php code snippet
public function imageUpload(){
//Сheck that we have a file
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") &&
($_FILES["file"]["size"] < 3500000)) {
//Determine the path to which we want to save this file
$newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
header('Error: A problem occurred during file upload!', true, 500);
//echo "Error: A problem occurred during file upload!";
}
} else {
header("Error: File ".$_FILES["file"]["name"]." already exists", true, 500);
//echo "Error: File ".$_FILES["file"]["name"]." already exists";
}
} else {
header("Error: Only .jpg images under 350Kb are accepted for upload", true, 500);
//echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
header("Error: No file uploaded", true, 500);
//echo "Error: No file uploaded";
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How do I upload an image and store it into a cookie? I want to be able to upload an image with limitations on e.g. file size restrictions.
Here is my PHP code:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
In this code is the function to upload a file with restrictions on.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<link href="bitnami.css" media="all" rel="Stylesheet" type="text/css" />
<link href="test.php"/>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
You have multiple faults in your logic.
1) You never check if an upload was actually performed. You just start working on the ['tmp_name'] without ever checking if it actually exists. Your FIRST action on processing an upload must be to check for errors:
if ($_FILES["fileToUpload"]['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileToUpload']['error']);
}
2) You're checking file types based on filename extensions. Nothing says a user can't do ren nastyvirus.exe cutekittens.jpg and get through your filename check. You're already using getimagesize() later on, so the extension check is pointless:
$info = getimagesize($_FILES['fileToUpload']['tmp_name']);
if ($info === false) {
die("Not an image at all");
}
if (($info[2] != IMGTYPE_GIF) && ($info[2] != IMGTYPE_JPG) && ($info[2] != IMGTYPE_PNG)) {
die("Not a gif/jpg/png");
}
if (($info[0] > $maximum_width) || ($info[1] > $maximum_height)) {
die("Too tall/wide");
}
And then, after all that - why store it in a cookie? Cookies are naturally limited in the maximum amount of data that can be stored. You shouldn't exect to be able to store more than a couple kilobytes at most. Since you've set your upload size limit at 500k, you WILL end up with corrupted/truncated images if you do store a 500k into that 1-2k cookie.