PHP Classes

File: files.php

Recommend this page to a friend!
  Classes of alismith   PHP Files Class   files.php   Download  
File: files.php
Role: Class source
Content type: text/plain
Description: Class file
Class: PHP Files Class
Manage uploaded files and serve them for download
Author: By
Last change: Update
Date: 4 years ago
Size: 34,990 bytes
 

Contents

Class file image Download
<?php namespace Utilities\File; class myStdClass extends \stdClass { public function __call($closure, $args) { return call_user_func_array($this->{$closure}->bindTo($this),$args); } } class Files implements \ArrayAccess, \IteratorAggregate { private $data = array(); private $absent = array(); private $validation = false; private $error_list = []; private $_loaded_file = false; private $error_msg = array( "EN" => [ "multiple" => 'You are not allowed to send multiple files', "type" => 'The file you submitted is incorrect', "mime" => 'The file you submitted is incorrect', "size" => 'The file size is incorrect', "min-size" => 'Minimum file size is not met', "max-size" => 'Maximum file size is not met', "width" => 'Wrong file width', "height" => 'Wrong file height' ], "FA" => [ "multiple" => '????? ????? ????? ???? ?? ??????', "type" => '???? ?????? ?????? ??????', "mime" => '???? ?????? ?????? ??????', "size" => '??? ???? ?????? ??????', "min-size" => '????? ?????? ???? ????? ???? ???', "max-size" => '?????? ?????? ???? ????? ???? ???', "width" => '??? ???? ?????? ???', "height" => '?????? ???? ?????? ??????' ] ); public function __construct($files=false,$validation=false){ if((is_array($files) && !$this->is_multi($files) && !$this->isAssoc($files)) || (is_string($files) && !empty($files))){ if($validation){ $this->validation = $this->validation_maker($validation); } $this->_file($files); }else{ if($this->is_Iterator($files)){ if(is_array($files)){ $this->data = $files; }else{ foreach($files as $k => $v){ $this->data[$k] = $v; } } foreach($data as $k => $v){ if(is_array($v)){ $this->error_list[$k] = []; foreach($v as $f){ if($f->error_list()){ $this->error_list[$k][$f->basename()] = $f->error_list(); } } if(empty($this->error_list[$k])){ unset($this->error_list[$k]); } }else{ if($v->error_list()){ $this->error_list[$v->_file_sender()] = [$v->basename()=>$v->error_list()]; } } } }else if(gettype($files) == "object" && get_class($files) == "Utilities\File\myStdClass"){ $this->data[$files->_file_sender()] = $files; if($files->error_list()){ $this->error_list[$files->_file_sender()] = [$files->basename()=>$files->error_list()]; } } } } private function _make_rule($rule){ $vtpl = array( "multiple" => false, "type" => '', "mime" => '', "size" => '', "min-size" => '', "max-size" => '', "width" => '', "height" => '' ); $rule = explode("|",$rule); $ret = []; foreach($rule as $r){ if(strstr($r,'=')){ $r[0] = trim(strtolower($r[0])); $r = explode("=",$r); $ret[$r[0]] = $r[1]; }else{ $ret[] = $r; } } $vt = []; foreach($vtpl as $k => $v){ if(array_key_exists($k,$ret)){ $ret[$k] = explode(",",$ret[$k]); $vt[$k] = $ret[$k]; } } if(!empty($vt)){ if(!array_key_exists("multiple",$vt)){ $vt["multiple"] = false; } return $vt; } return false; } private function validation_maker($validation){ if(is_array($validation) && !empty($validation)) { foreach($validation as $k => $v){ # ['slider'=>'multiple=true|mime=jpg,jpeg|max-size=1000000'] $v = $this->_make_rule($v); if($v){ $validation[$k] = $v; }else{ unset($validation[$k]); } } if(!empty($validation)){ return $validation; } } return false; } private function is_Iterator($abc) { return (is_array($abc) || $abc instanceof ArrayAccess); } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->data[] = $value; } else { $this->data[$offset] = $value; } } public function offsetExists($offset) { return isset($this->data[$offset]); } public function offsetUnset($offset) { unset($this->data[$offset]); } public function offsetGet($offset) { return isset($this->data[$offset]) ? $this->data[$offset] : null; } public function __set($key,$value) { $this->data[$key] = $value; } public function __get($key){ if(array_key_exists($key,$this->data)){ return $this->data[$key]; } } public function __isset($key) { return isset($this->data[$key]); } public function getIterator() { return new \ArrayIterator($this->data); } private function _check_valid_img($file,$mime){ $valid_mime_ext = ['jpg','jpeg','png','gif','bmp','wbmp','webp','swf','ico','iff','tiff','psd']; $valid_img_type = [IMAGETYPE_GIF,IMAGETYPE_JPEG,IMAGETYPE_PNG,IMAGETYPE_SWF,IMAGETYPE_PSD,IMAGETYPE_BMP,IMAGETYPE_TIFF_II,IMAGETYPE_TIFF_MM,IMAGETYPE_IFF,IMAGETYPE_WBMP,IMAGETYPE_ICO]; if (version_compare(PHP_VERSION, '7.0.0') >= 0) { $valid_img_type[] = IMAGETYPE_WEBP; } if(!in_array($mime,$valid_mime_ext)){ return true; }else{ if(in_array(exif_imagetype($file),$valid_img_type)){ return true; } } return false; } private function is_multi($array) { return (count($array) != count($array, 1)); } private function formatbytes($file, $type){ switch($type){ case "KB": $filesize = filesize($file) * .0009765625; // bytes to KB break; case "MB": $filesize = (filesize($file) * .0009765625) * .0009765625; // bytes to MB break; case "GB": $filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625; // bytes to GB break; } if($filesize <= 0){ return $filesize = 'unknown file size';} else{return round($filesize, 2).' '.$type;} } private function reArrayFiles($file_post) { $file_ary = array(); $file_count = count($file_post['name']); $file_keys = array_keys($file_post); for ($i=0; $i<$file_count; $i++) { foreach ($file_keys as $key) { $file_ary[$i][$key] = $file_post[$key][$i]; } } return $file_ary; } private function isAssoc($arr){ return array_keys($arr) !== range(0, count($arr) - 1); } private function _check_error($r,$v,$f){ switch ($r) { case 'mime': if(in_array($f->mime(),$v) && $this->_check_valid_img($f->tmp(),$f->mime())){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'ext': if(in_array($f->ext(),$v) && $this->_check_valid_img($f->tmp(),$f->mime())){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'type': if(in_array($f->type(),$v)){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'size': if($f->size() == $v[0]){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'min-size': if($f->size()>= $v[0]){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'max-size': if($f->size() <= $v[0]){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'width': if($f->isImage() && getimagesize($f->tmp())[0] == $v[0]){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; case 'height': if($f->isImage() && getimagesize($f->tmp())[1] == $v[0]){ return false; }else{ return $this->error_msg[DEFAULT_LANGUAGE][$r]; } break; } } private function has_validation_error($key,$f,$multi=false){ $error = false; if(is_array($this->validation) && !empty($this->validation)){ if(array_key_exists($key,$this->validation)){ $r = $this->validation[$key]; if(!$multi || $r['multiple']){ foreach($r as $k => $v){ $e = $this->_check_error($k,$v,$f); if($e){ $error = true; if(!array_key_exists($key,$this->error_list)){ $this->error_list[$key] = []; } if(!array_key_exists($f->basename(),$this->error_list[$key])){ $this->error_list[$key][$f->basename()] = []; } $this->error_list[$key][$f->basename()][] = $e; } } }else if($multi && !$r['multiple']){ $error = true; $this->error_list[$key] = $this->error_msg[DEFAULT_LANGUAGE]['multiple']; //"You are not allowed to send multiple files"; } } } return $error; } private function _file($files){ if(!is_array($files)){ $files = [$files]; } foreach($files as $file){ if(isset($_FILES[$file])){ if(is_array($_FILES[$file]['name'])){ $_FILES[$file] = $this->reArrayFiles($_FILES[$file]); } #======================================= $size = function($file,$type){ return $this->formatbytes($file,$type); }; $v = $_FILES[$file]; if($this->isAssoc($v)){ # Singel File $obj = new myStdClass(); $obj->_file_sender = function() use($file){ return $file; }; $obj->error = function() use($v){ return $v['error']; }; $obj->mime = function() use($v){ return strtolower(pathinfo($v['name'],PATHINFO_EXTENSION)); }; $obj->ext = function() use($v){ return strtolower(pathinfo($v['name'],PATHINFO_EXTENSION)); }; $obj->size = function($type='byte') use($size,$v){ return ($v['error'] == 0)? (in_array(strtolower($type),['kb','mb','gb']))? $size($v['tmp_name'],strtoupper($type)) : $v['size'] : 0; }; $obj->type = function() use($v){ return ($v['error'] == 0)? mime_content_type($v['tmp_name']) : null; }; $obj->name = function() use($v){ return pathinfo($v['name'], PATHINFO_FILENAME); }; $obj->basename = function() use($v){ return $v['name']; }; $obj->originalName = function() use($v){ return pathinfo($v['name'], PATHINFO_FILENAME); }; $obj->tmp = function() use($v){ return $v['tmp_name']; }; $obj->isImage = function() use($v){ return (getimagesize($v['tmp_name']) && exif_imagetype($v['tmp_name'])); }; if($this->has_validation_error($file,$obj)){ $obj->error = function(){ return 1; }; $e = $this->error_list[$file][$obj->basename()]; $obj->error_list = function() use($e){ return $e; }; }else{ $obj->error_list = function(){ return false; }; } $this->data[$file] = $obj; }else{ # Multi Files $file_arr = array(); foreach($v as $f){ $obj = new myStdClass(); $obj->_file_sender = function() use($file){ return $file; }; $obj->error = function() use($f){ return $f['error']; }; $obj->mime = function() use($f){ return strtolower(pathinfo($f['name'],PATHINFO_EXTENSION)); }; $obj->ext = function() use($f){ return strtolower(pathinfo($f['name'],PATHINFO_EXTENSION)); }; $obj->size = function($type='byte') use($size,$f){ return ($f['error'] == 0)? (in_array(strtolower($type),['kb','mb','gb']))? $size($f['tmp_name'],strtoupper($type)) : $f['size'] : 0; }; $obj->type = function() use($f){ return ($f['error'] == 0)? mime_content_type($f['tmp_name']) : null; }; $obj->name = function() use($f){ return pathinfo($f['name'], PATHINFO_FILENAME); }; $obj->basename = function() use($f){ return $f['name']; }; $obj->originalName = function() use($f){ return pathinfo($f['name'], PATHINFO_FILENAME); }; $obj->tmp = function() use($f){ return $f['tmp_name']; }; $obj->isImage = function() use($f){ return (getimagesize($f['tmp_name']) && exif_imagetype($f['tmp_name'])); }; if($this->has_validation_error($file,$obj,true)){ $obj->error = function(){ return 1; }; $e = $this->error_list[$file][$obj->basename()]; $obj->error_list = function() use($e){ return $e; }; }else{ $obj->error_list = function(){ return false; }; } $file_arr[]= $obj; } $this->data[$file] = $file_arr; } }else{ $this->absent[] = $file; } } } public function first(){ $file = reset($this->data); if($file){ if(is_array($file)){ $file = $file[0]; } return $file; } return false; } public function getAll($file=null){ if(!empty($this->data)){ if(is_null($file)){ return $this->data; }else{ if(array_key_exists($file,$this->data)){ return $this->data[$file]; } } } return false; } public function get($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]; }else if($i == 0){ return $file; } }else if(!is_null($file)){ if($i == 0){ return $file; } } } return false; } public function error_list($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->error_list(); } }else if(!is_null($file)){ if($i == 0){ return $file->error_list(); } } } return null; } public function error($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->error(); } }else if(!is_null($file)){ if($i == 0){ return $file->error(); } } } return null; } public function mime($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->mime(); } }else if(!is_null($file)){ if($i == 0){ return $file->mime(); } } } return false; } public function ext($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->ext(); } }else if(!is_null($file)){ if($i == 0){ return $file->ext(); } } } return false; } public function name($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->name(); } }else if(!is_null($file)){ if($i == 0){ return $file->name(); } } } return false; } public function basename($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->basename(); } }else if(!is_null($file)){ if($i == 0){ return $file->basename(); } } } return false; } public function originalName($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->originalName(); } }else if(!is_null($file)){ if($i == 0){ return $file->originalName(); } } } return false; } public function tmp($file=null,$i=0){ if(!empty($this->data)){ if(is_null($file)){ $file = reset($this->data); }else{ if(array_key_exists($file,$this->data)){ $file = $this->data[$file]; }else{ $file = null; } } if(is_array($file)){ if($i >= 0 && $i < count($file)){ return $file[$i]->tmp(); } }else if(!is_null($file)){ if($i == 0){ return $file->tmp(); } } } return false; } private function failed_success(&$array,$key,$file){ if(array_key_exists($key,$array)){ $array[$key][] = $file; }else{ $array[$key] = []; $array[$key][] = $file; } } public function store($path,$name=false,$options=false){ $move_path = ''; $img_data = ''; $img_new = ''; $fn = ''; $save_list = []; $overwrite = false; $convert = false; $resize = false; $failed = []; $success = []; if(is_array($options)){ $options = array_change_key_case($options,CASE_LOWER); } if(is_array($options) && array_key_exists("overwrite",$options) && is_bool($options['overwrite'])){ $overwrite = $options['overwrite']; } if(is_array($options) && array_key_exists("convert",$options) && in_array(strtolower($options['convert']),['jpg','jpeg','png','gif','bmp','wbmp','webp'])){ $convert = strtolower($options['convert']); } if(is_array($options) && array_key_exists("resize",$options) && !empty($options['resize'])){ $resize = $options['resize']; } if(!empty($this->data)){ foreach($this->data as $key => $file){ $move_path = ''; $img_data = ''; $img_new = ''; $fn = ''; $ffn = ''; if(!is_array($path)){ $move_path = $path; }else if(array_key_exists($key,$path)){ $move_path = $path[$key]; } if(!empty($move_path)){ $move_path = BASE_UPLOAD_DIR.'/'.$move_path.'/'; $move_path = str_replace('///','/',$move_path); $move_path = str_replace('//','/',$move_path); if(!is_array($file)){ $file = [$file]; } for($i=0;$i<count($file);$i++){ if($file[$i]->error() == 0){ if(!$name){ $fn = $file[$i]->name(); }else if(!is_array($name)){ $fn = $name; if($i>0 && !$overwrite){ $fn = $fn.$i; } }else{ if(array_key_exists($key,$name)){ $fn = $name[$key]; if($i>0 && !$overwrite){ $fn = $fn.$i; } }else{ $fn = $file[$i]->name(); } } $move_path = $move_path.$fn; if($convert && $file[$i]->isImage()){ $move_path = $move_path.'.'.$convert; $ffn = $fn.'.'.$convert; }else{ $move_path = $move_path.'.'.$file[$i]->ext(); $ffn = $fn.'.'.$file[$i]->ext(); } if($overwrite || !file_exists($move_path)){ if($file[$i]->isImage() && ($convert || $resize)){ $img_data = imagecreatefromstring(file_get_contents($file[$i]->tmp())); if($resize){ $width_new = 0; $height_new = 0; if(strstr($resize,'*')){ $resize = explode('*',$resize); $width_new = $resize[0]; $height_new = $resize[1]; }else if(strstr($resize,'/')){ $resize = explode('/',$resize); $width_new = $resize[0]; $height_new = $resize[1]; }else{ $width_new = $resize; $height_new = $resize; } $width = imagesx($img_data); $height = imagesy($img_data); $img_new = imagecreatetruecolor($width_new, $height_new); imagecopyresampled($img_new, $img_data, 0, 0, 0, 0, $width_new, $height_new, $width, $height); $img_data = $img_new; unset($img_new); } $img_ext = $file[$i]->ext(); if($convert){ $img_ext = $convert; } if($img_ext == 'png'){ if(imagepng($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } }else if($img_ext == 'jpg' || $img_ext == 'jpeg'){ if(imagejpeg($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } }else if($img_ext == 'gif'){ if(imagegif($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } }else if($img_ext == 'bmp'){ if(imagebmp($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } }else if($img_ext == 'wbmp'){ if(imagewbmp($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } }else if($img_ext == 'webp'){ if (version_compare(PHP_VERSION, '7.0.0') >= 0) { if(imagewebp($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } }else{ $this->failed_success($failed,$key,$ffn); } }else{ if(imagejpeg($img_data, $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } } imagedestroy($img_data); }else{ if(move_uploaded_file($file[$i]->tmp(), $move_path)){ $this->failed_success($success,$key,$ffn); }else{ $this->failed_success($failed,$key,$ffn); } } }else{ $this->failed_success($failed,$key,$ffn); } } } } } } return ['success'=>$success,'failed'=>$failed,'error_list'=>$this->error_list]; } public function load($file){ if(is_file($file) && is_readable($file)){ $this->_loaded_file = $file; } return $this; } public function copyTo($dir,$name=false,$mkdir=true){ $dir_error = true; if($this->_loaded_file){ if(is_dir($dir) && is_writable($dir)){ $dir_error = false; }else if($mkdir){ if(mkdir($dir, 0755)){ $dir_error = false; } } if(!$dir_error){ if(!$name){ $name = pathinfo($this->_loaded_file,PATHINFO_BASENAME); } $dir = $dir.'/'; $dir = str_replace('///','/',$dir); $dir = str_replace('//','/',$dir); $dir = $dir.$name; if($dir == $this->_loaded_file){ return false; } return $this->chunked_copy($this->_loaded_file,$dir); } } return false; } public function moveTo($dir,$name=false,$mkdir=true){ if($this->copyTo($dir,$name,$mkdir)){ unlink($this->_loaded_file); $this->_loaded_file = false; return true; } return false; } public function download($stream=false){ if($this->_loaded_file){ /** * Copyright 2012 Armand Niculescu - media-division.com * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // hide notices @ini_set('error_reporting', E_ALL & ~ E_NOTICE); //- turn off compression on the server @apache_setenv('no-gzip', 1); @ini_set('zlib.output_compression', 'Off'); $file_size = filesize($this->_loaded_file); $file = @fopen($this->_loaded_file,"rb"); $file_name = pathinfo($this->_loaded_file,PATHINFO_BASENAME); $file_ext = strtolower(pathinfo($this->_loaded_file,PATHINFO_EXTENSION)); if ($file) { ob_clean(); // set the headers, prevent caching header("Pragma: public"); header("Expires: -1"); header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0"); //header("Content-Disposition: attachment; filename=\"$file_name\""); // set appropriate headers for attachment or streamed file if (!$stream) header("Content-Disposition: attachment; filename=\"$file_name\""); else header('Content-Disposition: inline;'); // set the mime type based on extension, add yours if needed. $ctype_default = "application/octet-stream"; $content_types = array( "exe" => "application/octet-stream", "zip" => "application/zip", "mp3" => "audio/mpeg", "mpg" => "video/mpeg", "avi" => "video/x-msvideo" ); $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default; header("Content-Type: " . $ctype); //check if http_range is sent by browser (or download manager) if(isset($_SERVER['HTTP_RANGE'])) { list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2); if ($size_unit == 'bytes') { //multiple ranges could be specified at the same time, but for simplicity only serve the first range //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt list($range, $extra_ranges) = explode(',', $range_orig, 2); } else { $range = ''; header('HTTP/1.1 416 Requested Range Not Satisfiable'); exit; } } else { $range = ''; } //figure out download piece from range (if set) list($seek_start, $seek_end) = explode('-', $range, 2); //set start and end based on range (if set), else set defaults //also check for invalid ranges. $seek_end = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1)); $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0); //Only send partial content header if downloading a piece of the file (IE workaround) if ($seek_start > 0 || $seek_end < ($file_size - 1)) { header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size); header('Content-Length: '.($seek_end - $seek_start + 1)); } else header("Content-Length: $file_size"); header('Accept-Ranges: bytes'); set_time_limit(0); fseek($file, $seek_start); while(!feof($file)) { print(@fread($file, 1024*8)); ob_flush(); flush(); if (connection_status()!=0) { @fclose($file); exit; } } // file save was a success @fclose($file); exit; } else { // file couldn't be opened header("HTTP/1.0 500 Internal Server Error"); exit; } } } private function chunked_copy($from, $to) { # 1 meg at a time, you can adjust this. $buffer_size = 1048576; $ret = 0; $fin = fopen($from, "rb"); $fout = fopen($to, "w"); while(!feof($fin)) { $ret += fwrite($fout, fread($fin, $buffer_size)); } fclose($fin); fclose($fout); return $ret; # return number of bytes written } }