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"])) {
Related
I want to upload an image and save it in the uploads folder without refreshing the page. Furthermore, I also want to display the uploaded image on the screen in a div. However, when I run the code, when I try to upload an image, the text continues to say "Image Uploading..." and never finishes to actually upload. Therefore, the image never gets displayed on the page. Additionally, I am having trouble saving my image in the uploads folder, so can someone point me in the right direction? Thank you!
UPDATE: The Ajax POST gets an error each time I try to to upload an image. In fact, the POST request might not even reach my upload.php file. I trie d to alert myself when the request actually reaches upload.php but nothing ever prints out. What may be the potential causes of this?
UPDATE #2: I have included a picture of my file layout. I have the HTML and Javascript in privatecreate.blade.php and the Javascript in upload.php. I want to save the images in uploads folder.
Update #3: I printed out the ajax error and it is "No Input File Specified"
Please bear with my everyone. This is my absolute first time working with php and sql and I am trying my hardest to learn.
HTML:
<div class="container" style="width:700px;">
<br />
<label>Select Image</label>
<input type="file" name="file" id="file" />
<br />
<span id="uploaded_image"></span>
</div>
Javascript:
$(document).ready(function(){
$(document).on('change', '#file', function(){
var name = document.getElementById("file").files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
else{
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("file").files[0]);
var f = document.getElementById("file").files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById('file').files[0]);
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
,error: function(ts)
{
alert("error:" + ts.responseText);
}
});
}
}
});
});
PHP (upload.php):
<?php
//upload.php
$message = "Running Upload.php";
echo "<script type='text/javascript'>alert('$message');</script>";
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'uploads/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>
<?php
//Change your location path
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = 'upload/' . $name; // change here & enjoy
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>
After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?
My javascript
function uploadFile() {
var input = document.getElementById("picture");
file = input.files[0];
newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
console.log(newFileName);
if (file != undefined) {
formData = new FormData();
if (!!file.type.match(/image.*/)) {
formData.append("newFileName1", newFileName);
$.ajax({
url: "upload_file.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {}
});
} else {
alert('Not a valid image!');
}
} else {
alert('Input something!');
}
}
My php
<?php
$dir = "im_ges/";
$file_name = $dir. $_REQUEST["newFileName1"].".jpg";
echo $file_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>
Try this sample code
form.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function (responce) {
alert(responce);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<input name="name" value="First Name"><br>
<input name="file" type ="file" ><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
create post.php
echo "Name Value : ".$_POST["name"]."\n\n";
echo "\n File Details\n";
print_r($_FILES);
This will alert the values from form
If you get the file name in your custom php controller the you can use
$target_dir = "uploads/";
$filename = "phonenumber.png";//Set here the new file name which you passed through ajax
$target_file = $target_dir .$filename;
// test here the file is moved or not,
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
then update db with the $filename
}
or i changed the some code in above mentioed and add a text filed to enter a phone number and the selected file moved to the taget with the value enterd in the
text field with name phone can you check is it usefull for you .
form.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function (responce) {
alert(responce);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<input name="name" value="First Name"><br>
<input name="phone" value=""><br> <!-- new field -->
<input name="file" type ="file" ><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
post.php
<?php
echo "Name Value : ".$_POST["name"]."\n\n";
echo "\n File Details\n";
print_r($_FILES);
$target_dir = "uploads/";
$uploadOk = 1;
$filename = $_FILES['image']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$target_file = $target_dir . $_POST["phone"].$ext; // here we change the file name before uploads
// test here the file is moved or not,
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
}
?>
create a folder in the root with name "uploads" and give full permison
I just start to learn javascirpt, php about 2 days. The problem I face is I already have a x.dcm file under server root, and I already known that path(e.g. http://localhost:8888/....)
My question is how can I simply grab that file from server to use, maybe something like:
var file= 'http://localhost:8888/....'; ////file is not an object
I ask this question because I already known how to use input method:
<input type="file" name="file" id="file">
<script>
$('#file').on('change',function(e){
var file = e.target.file; ///file is an object
});
</script>
but that is not what I want, what I want is to use an existed file rather than input.
So the whole thing is that:
<form id="input" method="post" enctype="multipart/form-data">
<input type="file" id="fileToUpload" name="fileToUpload">
</form>
I firstly make a input to upload some file,then in script
<script>
$("form#input").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'segmentation.php',
type: 'POST',
data: formData,
async: false,
success: function (html) {
$('#segbound').html(html);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
I sent this file(e.g image.dcm) to do something( run a exec) on the server side, then it generates another image(imgproc.dcm) in an expected path(http://localhost:8888/....), and then the next thing is that I what that processed image display on the screen. To do that I need to use a js called cornerstone, and the function in it imageLoader.fileManager.get(file)
which file is that one I what to display.
When I select from input using var file = e.target.file; as I mentioned above, it works perfect, then I check the file type it is a [file object].
But when I want to simply display that 'imgproc.dcm' by using var file= 'http://localhost:8888/....'; the file type is not an object which comes out my question, how can I simply grab that known path image to use as an object.
Or, to improve that, it is possible to get the return (generated imgproc.dcm) directly after it process on server side, and then to use that return(maybe give it an id...do not know) to display (call cornerstone function imageLoader.fileManager.get(file))
On server side, it looks like:
<?php
$target_dir = "/Applications/MAMP/htdocs/dicomread/temp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "file has already been uploaded.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} 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.";
}
}
$cmd = "/Applications/MAMP/htdocs/dicomread/abc 2>&1";
$Output_fileName = "imgproc.dcm";//$_FILES['fileToUpload']['name'];
exec("$cmd $target_file $Output_fileName);
echo "<br/>done";
?>
Any help would be appreciated.
Use fopen with URL to the file:
$file = fopen("http://localhost:8888/x.dcm", "r");
Refer to this for fopen: http://php.net/manual/en/function.fopen.php
First of all this might be a silly question as there are many topics available on this but seriously I am not being able to get it straight and understand how to make it work.
WHAT I AM TRYING TO DO
I am trying to upload multiple files using AJAX and PHP.
PROBLEM
I cant figure out how to pass the data to the PHP script using AJAX.
I don't want to use a form and a submit button for uploading.
Tried using a form and submitting it using jQuery still couldn't make
it.
HTML
<div id="content">
<div id="heading">Upload your files seamlessly</div>
<a href="#"><div id="upload" class="button" title="Upload your files"><i class="fa fa-cloud-upload fa-align-center" aria-hidden="true"></i>
</div></a>
<a href="view.php"><div id="view" class="button" title="View all files on my cloud"><i class="fa fa-eye fa-align-center" aria-hidden="true"></i>
</div></a>
</div>
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
</form>
JS
<script type="text/javascript">
$(document).ready(function(){
$('#upload').click(function(){
$('input[type=file]').click();
return false;
});
$("#uploadfile").change(function(){
//submit the form here
$('#fileupload').submit();
});
});
</script>
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
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/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
Any help would be appreciated.
This is a very simple example of what you want to do.
HTML
Wrap your inputs within a form. Why? Because it is the easiest way to do it.
<form action="process.php" method="post">
<input type="file" multiple name="uploadfile[]">
<input type="submit" value="Upload">
</form>
JavaScript
Attach an onsubmit event handler to your form. Use $.ajax() to send a POST request.
Pass your form element i.e. this into the constructor of a FormData object and use it as your data when you send the request as shown below. You need to make sure that you set processData and contentType as false also for this to work.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
// send request
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this), // important
processData: false, // important
contentType: false, // important
success: function (res) {
alert(res);
}
});
});
});
PHP (process.php)
Let's clean up your PHP.
<?php
// always a good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dir = './storage';
$errors = [];
if (isset($_FILES['uploadfile'])) {
$files = $_FILES['uploadfile'];
// create directory if it does not exist
!is_dir($dir) && mkdir($dir, 0700);
// validate & upload files
foreach (array_keys($files['tmp_name']) as $key) {
$file = [
'name' => $files['name'][$key],
'size' => $files['size'][$key],
'tmp_name' => $files['tmp_name'][$key],
'type' => $files['type'][$key],
'error' => $files['error'][$key]
];
// skip if no file was given
if ($file['error'] === UPLOAD_ERR_NO_FILE) {
continue;
}
// get file extension
$file['ext'] = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
// generate a unique name (!)
$file['name'] = uniqid() . '.' . $file['ext'];
// validate
if (!file_exists($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name']) ||
$file['error'] !== UPLOAD_ERR_OK) {
$errors[$key] = 'An unexpected error has occurred.';
} elseif ($file['size'] > 2097152) {
$errors[$key] = 'File size must be less than 2 MB';
// upload file
} elseif (!move_uploaded_file($file['tmp_name'], $dir . '/' . $file['name'])) {
$errors[$key] = 'File could not be uploaded.';
}
}
}
if ($errors) {
print_r($errors);
} else {
echo 'no errors';
}
?>
(!) Do keep in mind that uniqid() is actually not unique.
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