Hyosoka Poipo Hyosoka Poipo - 4 months ago 21
Javascript Question

Get Ajax Header Information in PHP

I'm making an ajax function for uploading files (video or image) like this :

function upload_file(file)
{
//create xhr object
xhr = new XMLHttpRequest();

//initiate request
xhr.open('post','hisoka_drop.php',true);//true for asynchronous

//set headers
xhr.setRequestHeader('Content-Type',"multipart/form-data");
xhr.setRequestHeader('X-File-Name',file.fileName);
xhr.setRequestHeader('X-File-Size',file.fileSize);
xhr.setRequestHeader('X-File-Type',file.fileType);

//send the file
xhr.send(file);

}


And in my hisoka_drop.php :

<?php
$str =file_get_contents('php://input');
$filename = ; //How to get ajax header about file.fileName;
$path = 'upload/'.$filename;
file_put_contents($path,$str);
echo $path;
?>


My question is simple, how do I get the ajax header that I have set before in order to get the real filename of the file that I want to upload to server...
Thanks in advance... :)

Answer

Since your custom HTTP header is called, X-File-Name, simply uppercase it, convert dashes to underscores, and prepend HTTP_ to form the key you would use to find it in the $_SERVER superglobal. e.g.:

$filename = $_SERVER['HTTP_X_FILE_NAME'];

For more info, see this answer.

Comments