I\'m working on a script to let the user upload a file and sees a upload status and the file is then saved on the server.
The problem is that I cannot use the php ap
Make an AJAX request to a PHP file, send the uploaded file properties like name, etc. and let it open that, move that, rename that or whatever needed. It should works, huh?
did I understood your question correctly?
Sample Code:
In Javascript:
// xhr
var http = new XMLHttpRequest();
var url = "file_handler.php";
var file_data = "name=mypic.jpg&size=123&othe=etc";
http.open("POST", url, true);
// headers
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", file_data.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(file_data);
In file_handler.php
:
// file data
$file_data = $_POST['file_data'];
// working on the file
$temp_dir = 'usr/upload/';
$new_dir = 'usr/photos/';
// new unique name
$new_name = time() . '_' . $file_data['name'];
// copy?
if (copy($temp_dir . $file_data['name'], $new_dir . $new_name)) {
unlink($temp_dir . $file_data['name']);
}
// rename?
rename($temp_dir . $file_data['name'], $temp_dir . $new_name);
// delete old file?
unlink($temp_dir . $file_data['name']);
// do whatever else needed here ...
// echo some JSON data to interact with your client-side JS code, maybe ...
I have a Gist on this. It uses xhr.send(FormData)
and shows minimal code
to handle the file in PHP.