I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
Related
This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)
Not sure why I am unable to send the formData over to my PHP script.
I have used this same code before with success.
Here is the HTML:
<form role="form" id="uploadForm" name="uploadForm" action="index.php" enctype="multipart/form-data" method="post">
<input type="file" id="file" name="file" />
<button type="button" id="uploadSubmit" class="btn btn-sm btn-flat btn-primary uploadSubmit">Upload Proforma</button>
</form>
Here is the JavaScript
$('#uploadSubmit').on('click', function(e){
e.preventDefault();
var formData = new FormData();
formData.append("file", document.getElementById('file').files[0]);
$.ajax({
url: 'api/uploadDoc.php',
method: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: ' + errorThrown);
}
});
return false;
});
Here is the PHP uploadDoc.php script:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
print_r($_POST);
?>
I just added the headers in the PHP script, as found here:
FormData not posting data to php backend script
Using print_r($_POST), I am only getting a blank array in the console that looks like the following:
Array
(
)
Not sure what I am doing wrong.
Why is the post showing a blank array and the file information or formData?
How do I correct this issue so that the PHP script can retrieve the file that I am uploading?
You need to get the files using the variable $_FILES instead of $_POST
You can make sure the uploaded file by using is_uploaded_file. But if you want to retrieve the file contents, simply you can use readfile as following:
if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
die("Possible file upload attack: filename '". $_FILES['file']['tmp_name'] . "'.");
}
echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['file']['tmp_name']);
I found my answer here:
jQuery AJAX file upload PHP
I updated my onClick event to read as follows:
$('#uploadProformaSubmit').on('click', function(e){
e.preventDefault();
var file_data = $('#file').prop('files')[0]; // <-- added this
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'api/uploadDoc.php',
method: "POST",
type: "post", // <-- added this
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: ' + errorThrown);
}
});
return false;
});
Over in the PHP script, I could do the following:
<?php
if(isset($_FILES['file'])){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
echo "this is the file " . $file;
?>
And now the file is posting.
Maybe because the site is using an older version of JQuery (1.8.2.min.js), though I cannot be certain.
I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
I want to try uploading an image using php and mysql. I'm using a form to send data using ajax.
My Html Code:
<input type="file" name="logo" id="logo" class="styled">
<textarea rows="5" cols="5" name="desc" id="desc" class="form-control"></textarea>
<input type="submit" value="Add" id="btnSubmit" class="btn btn-primary">
Ajax Code:
var formData = new FormData($("#frm_data")[0]);
$("#btnSubmit").attr('value', 'Please Wait...');
$.ajax({
url: 'submit_job.php',
data: formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
my php code (submit_job.php):
$desc = mysqli_real_escape_string($con, $_POST['desc']);
$date = date('Y-m-d H:i:s');
$target_dir = "jobimg/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file);
Try this:
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData(); // Create a FormData object
form_data.append('file', file_data); // Append all element in FormData object
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the input type file */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
Security is a major part in the web designing. Try following validations for more security.
Checking for the file in $_FILES
if (empty($_FILES['image']))
throw new Exception('Image file is missing');
Checking for upload time errors
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
Checking the uploaded file
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
Checking the file size
$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
Validating the image
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
Validating the Mime Type
$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
Hope this helps others to create an upload PHP script without security issues.
Source
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function (event) {
event.preventDefault();
var formdata = new FormData($('form')[0]);
var url = $("form").attr('action');
$.ajax({
url: url,
type: "POST",
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
}
});
});
});
</script>
I have been trying to upload a file from my webpage to a folder on the server using jQuery and PHP.
Here is my JavaScript code for generating the file to send and then using a POST request to send the file to my PHP script so that it can then handle the file and save it to a particular folder.
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('Character', characterBlob);
//Communicate with the server
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // 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(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
Here is my PHP script to handle the sent file and save it in a specified folder.
<?php
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/Applications/AMPPS/www/webGL/upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
?>
When I try to send the file from my webpage nothing appears in the 'Upload' folder that I am trying to save the file to.
Could someone please tell me why a file is not saved in the 'Upload' folder? I am eventually looking to open this file in a Maya application on the server and run some Python code. Would I even need to save the file on the server before opening it in Maya? Or could I open Maya with the file straight away?
Try use my code and tell me if it works. This should work if you adapt it to your filenames and input, and other elements ids, it's tested by me:
$('#upload').on('click', function(e) {
$('#message').fadeOut();
e.preventDefault();
if ($('#file')[0].files.length == 0) {
alert('Choose a file!');
} else {
var file_data = $('#file').prop('files')[0]; //file object details
var form_data = new FormData($('#form')[0]);
form_data.append('file', file_data);
var unique_identifier = $('#unique_identifier').val();
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response) {
$('#message').html(php_script_response).fadeIn();
//alert(php_script_response); // display response from the PHP script, if any
}
});
}
});
<form id='form' action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='unique_identifier' id='unique_identifier' placeholder='unique identfier' value="<?php echo rand(1000000, 9999999); ?>">
<input type='file' name='file' id='file' />
<a id='upload'>Upload</a>
</form>
And the PHP script I made:
$unique_identifier = (isset($_POST['unique_identifier']))?trim($_POST['unique_identifier']):'';
$upload_directory = 'upload/' . $unique_identifier . '/';
if (!file_exists($upload_directory)) {
mkdir ($upload_directory, 0777);
}
$original_filename = basename($_FILES['file']['name']);
$destination = $upload_directory . $original_filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination)
Also, I recomend you to do some PHP validation.
It seems you are not appending the file to uploaded to the form data, May be you need something like this.
var elem = $(this).val() // lets say this is the element where you uploaded the photo
var formData = new FormData();
formData.append('file', elem[0].files[0]);
$.ajax({
url: "ExecuteMaya.php",
type: "POST",
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(result){
// your code executed successfully
}