Created
July 6, 2011 21:08
-
-
Save gpbmike/1068331 to your computer and use it in GitHub Desktop.
php backend for streaming file upload with XMLHttpRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class File_Streamer | |
{ | |
private $_fileName; | |
private $_contentLength; | |
private $_destination; | |
public function __construct() | |
{ | |
if (!isset($_SERVER['HTTP_X_FILE_NAME']) | |
&& !isset($_SERVER['CONTENT_LENGTH'])) { | |
throw new Exception("No headers found!"); | |
} | |
$this->_fileName = $_SERVER['HTTP_X_FILE_NAME']; | |
$this->_contentLength = $_SERVER['CONTENT_LENGTH']; | |
} | |
public function isValid() | |
{ | |
if (($this->_contentLength > 0)) { | |
return true; | |
} | |
return false; | |
} | |
public function setDestination($destination) | |
{ | |
$this->_destination = $destination; | |
} | |
public function receive() | |
{ | |
if (!$this->isValid()) { | |
throw new Exception('No file uploaded!'); | |
} | |
$fileReader = fopen('php://input', "r"); | |
$fileWriter = fopen($this->_destination . $this->_fileName, "w+"); | |
while(true) { | |
$buffer = fgets($fileReader, 4096); | |
if (strlen($buffer) == 0) { | |
fclose($fileReader); | |
fclose($fileWriter); | |
return true; | |
} | |
fwrite($fileWriter, $buffer); | |
} | |
return false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once('Streamer.php'); | |
$ft = new File_Streamer(); | |
$ft->setDestination('data/'); | |
$ft->receive(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment