I have this function
public static function upload($path_folder, $input_file_name) {
$photo_file = $_FILES[$input_file_name]; // FILE NAME
$photo_name = $photo_file['name']; // PHOTO NAME
$photo_tmp_name = $photo_file['tmp_name']; // TMP NAME
$photo_extension = pathinfo($photo_name, PATHINFO_EXTENSION); // EXTENSION
// soon GIFs
$rand_num = random_int(1, 3);
switch ($rand_num) {
case 1:
$hash = mb_strtoupper(Hash::create(), 'UTF-8');
break;
case 2:
$hash = mb_strtolower(Hash::create(), 'UTF-8');
break;
case 3:
$hash = str_shuffle(Hash::create());
break;
default:
$hash = Hash::create();
break;
}
$photo_with_extension = $hash . '.' . $photo_extension; // NEW FILE NAME
$factory_destination = 'photos/factory/' . $photo_with_extension; // FACTORY
if(move_uploaded_file($photo_tmp_name, $factory_destination)) {
if(file_exists($factory_destination)) {
if(
($photo_extension === 'jpg') ||
($photo_extension === 'jpeg') ||
($photo_extension === 'JPG') ||
($photo_extension === 'JPEG') ||
($photo_extension === 'png') ||
($photo_extension === 'PNG')
) {
if(
($photo_extension === 'jpg') ||
($photo_extension === 'jpeg') ||
($photo_extension === 'JPG') ||
($photo_extension === 'JPEG')
) {
if(imagecreatefromjpeg($factory_destination)) { // JPEG
$photo_create = imagecreatefromjpeg($factory_destination);
}
}
if(
($photo_extension === 'png') ||
($photo_extension === 'PNG')
) {
if(imagecreatefrompng($factory_destination)) { // PNG
$photo_create = imagecreatefrompng($factory_destination);
}
}
if(getimagesize($photo_tmp_name)) {
list($photo_width, $photo_height) = getimagesize($photo_tmp_name); // WIDTH & HEIGHT
$photo_new_width = 300; // NEW WIDTH
$photo_new_height = 300;
//$photo_new_height = ($photo_height / $photo_width) * $photo_new_width; // NEW HEIGHT
$true_color = imagecreatetruecolor($photo_new_width, $photo_new_height); // TRUE COLOR
if(imagecopyresampled($true_color, $photo_create, 0, 0, 0, 0, $photo_new_width, $photo_new_height, $photo_width, $photo_height)) {
$photo_copy = imagecopyresampled($true_color, $photo_create, 0, 0, 0, 0, $photo_new_width, $photo_new_height, $photo_width, $photo_height); // COPY
$mime = mime_content_type($factory_destination);
if(($mime === 'image/jpeg') || ($mime === 'image/png')) {
switch ($path_folder) {
case 1:
$folder = 'profile';
break;
case 2:
$folder = 'identities';
break;
default:
$folder = 'errors';
break;
}
$new_destination = 'photos/' . $folder . '/';
//$image = imagecreatefromstring(file_get_contents($photo_tmp_name));
$exif = exif_read_data($factory_destination);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$true_color = imagerotate($true_color,90,0);
break;
case 3:
$true_color = imagerotate($true_color,180,0);
break;
case 6:
$true_color = imagerotate($true_color,-90,0);
break;
}
}
if(imagejpeg($true_color, $new_destination . $photo_with_extension, 75)) { // DESIGNATED PATHS
imagedestroy($true_color); // return
if(unlink($factory_destination)) {
return $photo_with_extension; // AUTO UPDATE ADMIN THAT THERE IS A PROBLEM
} else { return 'unlink last'; }
} else { return 'imagejpeg'; }
} else { return 'mime'; }
/*move*/
} else { return 'resampled'; }
} else { return 'get image:' . $photo_tmp_name; }
} else { return 'wrong ext'; }
} else { return 'default2.png'; }
} else { return 'move'; }
return empty($photo_with_extension) ? '' : 'false';
}
the function works upto move_uploaded_file() after that nothing is happening.
This is on production, GD enabled and compatible, Linux server. Where do you think that my codes went wrong ? This works perfectly fine on my localhost though.
To be precise, the imagejpeg() is the one that is not working
New info;
It seems that the problem occurs on getimagesize($photo_tmp_name) it returns false
Newer info:
the tmp_name that given on getimagesize() is correct when I echo it, but it returns false.
if after move_uploaded_file() func,it should be destroy the tmp_file,you could replace the tmp_file with the moved files already,as php will execute the process blocked,so that is safe to do!
Related
I'm having a hard time implemeting the php code will ensure that all uploaded photos will be oriented correctly upon upload.
here is my upload.php function ...
function process_image_upload($field)
{
if(!isset($_FILES[$field]['tmp_name']) || ! $_FILES[$field]['name'])
{
return 'empty';
}
$temp_image_path = $_FILES[$field]['tmp_name'];
$temp_image_name = $_FILES[$field]['name'];
list($iwidth, $iheight, $temp_image_type) =
getimagesize($temp_image_path);
if ($temp_image_type === NULL) {
return false;
}
elseif( $iwidth < 400 )
return 'size';
switch ($temp_image_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
move_uploaded_file($temp_image_path, $uploaded_image_path);
$thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION .
preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$main_image_path = MAIN_IMAGE_DESTINATION . preg_replace('{\\.[^\\.]+$}', '.jpg', $temp_image_name);
$result =
generate_image_thumbnail($uploaded_image_path,
$thumbnail_image_path,150,150
); if( $result )
$result =
generate_image_thumbnail($uploaded_image_path,$main_image_path,400,400,
true);
return $result ? array($uploaded_image_path, $thumbnail_image_path) :
false;
}
if(isset($_POST['upload'])):
$result = process_image_upload('image');
if ($result === false) {
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>An error occurred while processing upload</p></div>');
} else if( $result === 'empty')
{
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>Please select a Image file</p></div>');
}
elseif( $result === 'size')
{
update_option('meme_message','<div class="error" style="margin-
left:0;"><p>Image width must be greater than 400px;</p></div>');
}
else {
update_option('meme_message','<div style="margin-left:0;"
class="updated"><p>Image uploaded successfully</p></div>');
$guploaderr = false;
$count = intval(get_option('meme_image_count'));
update_option('meme_image_count', $count+1);
}
endif;
and here is some php that I know will work to rotate... but I don't know how to implement.
<?php
$image =
imagecreatefromstring(file_get_contents($_FILES['image_upload']
['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$image = imagerotate($image,90,0);
break;
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
}
}
// $image now contains a resource with the image oriented correctly
?>
I'm trying to create 3 Thumbnail Images of different sizes, from the same uploaded Image. Presently, I use the code below to create 1 thumbnail that's 150px wide.
Is there an easy way to do this instead of repeating the same code thrice for each thumbnail I need?
I'm trying to create thumbnails in 3 sizes: 750px wide, 150px wide and 70px wide.
Here's the code I use to do the Thumbnail that's 150Px wide.
Does PHP have a function to do such a thing, or is repeating the code below for each size I need my only option.
if(file_exists($thisImage)) {
$imageName = $thisImage;
$imageInfo = finfo_open(FILEINFO_MIME_TYPE);
$imageType = finfo_file($imageInfo, $imageName);
finfo_close($imageInfo);
if($imageType == 'image/pjeg' || $imageType == 'image/jpeg' || $imageType == 'image/jpg') {
$imgSource = imagecreatefromjpeg($thisImage);
} elseif ($imageType == 'image/png') {
$imgSource = imagecreatefrompng($thisImage);
} elseif ($imageType == 'image/gif') {
$imgSource = imagecreatefromgif($thisImage);
} else {
$imgSource = false;
return false;
}
if($imgSource) {
list($width,$height)=getimagesize($thisImage);
$thumbImageWidth = 150;
$thumbImageHeight = ($height/$width)*$thumbImageWidth;
$tempThumbImage = imagecreatetruecolor($thumbImageWidth,$thumbImageHeight);
if(!imagecopyresampled($tempThumbImage,$imgSource,0,0,0,0,$thumbImageWidth,$thumbImageHeight,$width,$height)) return false;
$thumbImageTarget = $thisPath.$thisName;
if(!imagejpeg($tempThumbImage,$thumbImageTarget,100)) return false;
if(!imagedestroy($imgSource)) return false;
if(!imagedestroy($tempThumbImage)) return false;
if(!unlink($thisImage)) return false;
return true;
}
} else {
return false;
}
PHP dont have that function. But you can create a function named resize($width, $heigh) and put your resize part in.
zairwolf's answer is basically correct, although not thorough.
You need to create a user defined function.
resize($thisImage, 70, $thisPath.$thisName."-thumb1.jpg");
resize($thisImage, 150, $thisPath.$thisName."-thumb2.jpg");
resize($thisImage, 750, $thisPath.$thisName."-thumb3.jpg");
function resize($imageName, $thumbImageWidth, $thumbImageTarget)
{
if(file_exists($imageName)) {
$imageInfo = finfo_open(FILEINFO_MIME_TYPE);
$imageType = finfo_file($imageInfo, $imageName);
finfo_close($imageInfo);
if($imageType == 'image/pjeg' || $imageType == 'image/jpeg' || $imageType == 'image/jpg') {
$imgSource = imagecreatefromjpeg($imageName);
} elseif ($imageType == 'image/png') {
$imgSource = imagecreatefrompng($imageName);
} elseif ($imageType == 'image/gif') {
$imgSource = imagecreatefromgif($imageName);
} else {
$imgSource = false;
return false;
}
if($imgSource) {
list($width,$height)=getimagesize($imageName);
$thumbImageHeight = ($height/$width)*$thumbImageWidth;
$tempThumbImage = imagecreatetruecolor($thumbImageWidth,$thumbImageHeight);
if(!imagecopyresampled($tempThumbImage,$imgSource,0,0,0,0,$thumbImageWidth,$thumbImageHeight,$width,$height)) return false;
if(!imagejpeg($tempThumbImage,$thumbImageTarget,100)) return false;
if(!imagedestroy($imgSource)) return false;
if(!imagedestroy($tempThumbImage)) return false;
if(!unlink($imageName)) return false;
return true;
}
} else {
return false;
}
}
I want to validate my upload files is it an images or not. after searching i found two way that i think is a good way to do it. the first code is:
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
if (!in_array(finfo_file($fileinfo, $file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
and the second code:
if (!getimagesize($_FILES['photo']['tmp_name'])) {
$error[] = "Uploaded file is not a valid image";
}
which code is more reliable to check that it's an images and why? or is it any better way than this? thanks.
finfo_* library would be good but it will work with >= 5.3.0 versions,
AND getimagesize() GD library function that is return image info WxH and size
if image invalid then getimagesize() show warning so better to use to validate image using finfo_* function,
you can also do for cross version code, see below sample code
<?php
$file = $_FILES['photo'];
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
$error = null;
if(function_exists('finfo_open')){ //(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
if (!in_array(finfo_file($fileinfo, $file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
}else if(function_exists('mime_content_type')){ //supported (PHP 4 >= 4.3.0, PHP 5)
if (!in_array(mime_content_type($file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
}else{
if (!#getimagesize($file['tmp_name'])) { //# - for hide warning when image not valid
$error[] = "Uploaded file is not a valid image";
}
}
Why not use exif_imagetype:
if (exif_imagetype($file['tmp_name']) != (IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_PNG)) {
$error[] = "Uploaded file is not a valid image";
}
It's probably going to be faster than any of the others. (PHP 4 >= 4.3.0, PHP 5)
From a security standpoint, you might be better off converting an uploaded file presumed to be an image, see if it succeeds, and keep and serve the converted result from there on.
You could use one of those imagecreatefrom...() functions from the GD library, based on the MIME type you detected, e.g. from the $_FILES array, and/or from exif_imagetype(), finfo_file() etc.
The issue is that there are some exploits out there that pretend to be valid images (and in some cases are valid images) but are also valid JavaScript, Flash or other code containers that may be run by the client's browser under certain circumstances.
See also e.g. https://www.defcon.org/images/defcon-15/dc15-presentations/dc-15-schrenk.pdf
The fastest way I use is custom PHP function which reads specific bytes from file. It works much faster than getimagesize when check file is very large (movies, iso images etc.).
fastImageGet('image.jpg'); // returns size and image type in array or false if not image
fastImageGet('image.jpg', 'type'); // returns image type only
fastImageGet('image.jpg', 'size'); // returns image size only
function fastImageGet($file, $what=null) {
if (!in_array($what, ['size', 'type']))
$what = null;
// INIT
$pos = 0; $str = null;
if (is_resource($file))
$fp = $file;
elseif (!#filesize($file))
return false;
else
try {
$fp = fopen($file, 'r', false);
} catch (\Exception $e) {
return false;
}
// HELPER FUNCTIONS
$getChars = function($n) use (&$fp, &$pos, &$str) {
$response = null;
if (($pos + $n - 1) >= strlen($str)) {
$end = $pos + $n;
while ((strlen($str) < $end) && ($response !== false)) {
$need = $end - ftell($fp);
if (false !== ($response = fread($fp, $need)))
$str .= $response;
else
return false;
}
}
$result = substr($str, $pos, $n);
$pos += $n;
return $result;
};
$getByte = function() use ($getChars) {
$c = $getChars(1);
$b = unpack('C', $c);
return reset($b);
};
$readInt = function ($str) {
$size = unpack('C*', $str);
return ($size[1] << 8) + $size[2];
};
// GET TYPE
$t2 = $getChars(2);
if ($t2 === 'BM')
$type = 'bmp';
elseif ($t2 === 'GI')
$type = 'gif';
elseif ($t2 === chr(0xFF) . chr(0xd8))
$type = 'jpeg';
elseif ($t2 === chr(0x89) . 'P')
$type = 'png';
else
$type = false;
if (($type === false) || ($what === 'type')) {
fclose($fp);
return $type;
}
// GET SIZE
$pos = 0;
if ($type === 'bmp') {
$chars = $getChars(29);
$chars = substr($chars, 14, 14);
$ctype = unpack('C', $chars);
$size = (reset($ctype) == 40)
? unpack('L*', substr($chars, 4))
: unpack('L*', substr($chars, 4, 8));
} elseif ($type === 'gif') {
$chars = $getChars(11);
$size = unpack('S*', substr($chars, 6, 4));
} elseif ($type === 'jpeg') {
$state = null;
while (true) {
switch ($state) {
default:
$getChars(2);
$state = 'started';
break;
case 'started':
$b = $getByte();
if ($b === false) {
$size = false;
break 2;
}
$state = $b == 0xFF ? 'sof' : 'started';
break;
case 'sof':
$b = $getByte();
if (in_array($b, range(0xE0, 0xEF)))
$state = 'skipframe';
elseif (in_array($b, array_merge(range(0xC0, 0xC3), range(0xC5, 0xC7), range(0xC9, 0xCB), range(0xCD, 0xCF))))
$state = 'readsize';
elseif ($b == 0xFF)
$state = 'sof';
else
$state = 'skipframe';
break;
case 'skipframe':
$skip = $readInt($getChars(2)) - 2;
$state = 'doskip';
break;
case 'doskip':
$getChars($skip);
$state = 'started';
break;
case 'readsize':
$c = $getChars(7);
$size = [$readInt(substr($c, 5, 2)), $readInt(substr($c, 3, 2))];
break 2;
}
}
} elseif ($type === 'png') {
$chars = $getChars(25);
$size = unpack('N*', substr($chars, 16, 8));
}
// COMPLETE
fclose($fp);
if (is_array($size))
$size = array_values($size);
return ($what === 'size') ? $size : [$type, $size];
}
My upload code is this. I submit the image to it with postdata. I want to make the file select box accept multiple picutes, and have it work on the backend. I can get the header location to work just fine on my own, but using an array of files has proved to be difficult, even though I've spent hours on stack overflow and google. I'd love it if somebody could show me how to do it.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$browse = $_POST["browse"];
preg_match('/\.([a-zA-Z]+?)$/', $_FILES['userfile']['name'], $matches);
if(in_array(strtolower($matches[1]), $accepted)) {
if($_FILES['userfile']['size'] <= $maxsize) {
$newname = md5_file($_FILES['userfile']['tmp_name']).'.'.$matches[1];
$browse = $_POST["browse"];
if ($browse == "1") {
$filedir = 'img';
} else if ($browse == "2") {
$filedir = 'zega';
} else if ($browse == "3") {
$filedir = 'noimg';
} else if ($browse == "4") {
$filedir = 'adult';
} else if ($browse == "5") {
$filedir = 'temp';
} else {
$filedir = 'noimg';
}
move_uploaded_file($_FILES['userfile']['tmp_name'], $filedir.'/'.$newname);
$path = $filedir.'/'.$newname;
if (strpos($path,'jpg') !== false){
$img = imagecreatefromjpeg ($path);
imagejpeg ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'gif') !== false){
$img = imagecreatefromgif ($path);
imagegif ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'bmp') !== false){
$img = imagecreatefrombmp ($path);
imagebmp ($img, $path, 100);
imagedestroy ($img);
}
header("Location: index.php?p=uploaded&img=$newname");
} else
header("Location: index.php?p=error&num=2");
} else
header("Location: index.php?p=error&num=1");
}
?>
foreach($_FILES as $key_file=>$file_info){
//your code here instead $_FILES['userfile']['tmp_name'] use $file_info['tmp_name']
}
i wrote a class for uploads sometimes ago.
this class has ability to upload mutiple files at the same time(such as picture .etc).
it also has other ability such as :
-if you upload mutiple files with the same name it will automatically change their name
-you can add permitted types
-set maximum size of uploaded files
...
class Upload {
protected $_uploaded = array();
protected $_destination_upload_folder;
//Constraint
protected $_max_upload_size = 512000;
protected $_permitted_files = array('image/gif', 'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg');
protected $_error_messages = array();
protected $_renamed_file = false;
public function __construct($input_upload_path) {
if(!is_dir($input_upload_path) || !is_writable($input_upload_path)){
throw new Exception("$input_upload_path must be a valid,writable path!");
}
$this->_destination_upload_folder = $input_upload_path;
$this->_uploaded = $_FILES;
}
protected function checkError($fileName, $error){
switch ($error) {
case 0:
return true;
case 1:
case 2:
$this->_error_messages[] = "$fileName exceeds maximum file size : "
.$this->getMaxSize();
return true;
case 3:
$this->_error_messages[] = "Error while uploading $fileName.please try again.";
return false;
case 4:
$this->_error_messages[] = "No file selected.";
return false;
default:
$this->_error_messages[] = "System Error uploading $fileName.Please contact administrator.";
return false;
return false;
}
}
protected function checkSize($fileName, $size){
if($size == 0){
return false;
}else if($size > $this->_max_upload_size){
$this->_error_messages[] = "$fileName exceeds maximum size : ".
$this->_max_upload_size;
return false;
}else{
return true;
}
}
protected function checkType($fileName, $type){
if(!in_array($type, $this->_permitted_files)){
$this->_error_messages[] = 'This type of file is not allowed for uploading '
.'.please upload permitted files.';
return false;
}else{
return true;
}
}
public function checkName($input_file_name, $overwrite)
{
$input_file_name_without_spaces = str_replace(' ', '_', $input_file_name);
if($input_file_name_without_spaces != $input_file_name){
$this->_renamed_file = true;
}
if(!$overwrite){
$all_files_in_upload_directory = scandir($this->_destination_upload_folder);
if(in_array($input_file_name_without_spaces, $all_files_in_upload_directory)){
$dot_position = strrpos($input_file_name_without_spaces, '.');
if($dot_position){
$base = substr($input_file_name_without_spaces, 0, $dot_position);
$extension = substr($input_file_name_without_spaces, $dot_position);
}else{
$base = substr($input_file_name_without_spaces);
$extension = '';
}
$i = 1;
do{
$input_file_name_without_spaces = $base.'_'.$i++.$extension;
}while(in_array($input_file_name_without_spaces, $all_files_in_upload_directory));
$this->_renamed_file = true;
}
}
return $input_file_name_without_spaces;
}
protected function getMaxSize(){
return number_format(($this->_max_upload_size)/1024, 1).'kb';
}
protected function isValidMime($types)
{
$also_valid_mimes = array('application/pdf', 'text/plain', 'text/rtf');
$all_valid_mimes = array_merge($this->_permitted_files, $also_valid_mimes);
foreach($types as $type){
if(!in_array($type, $all_valid_mimes)){
throw new Exception("$type is not a valid permitted mime type!");
}
}
}
public function addPermittedType($input_type_name)
{
$input_type_name_array = (array)$input_type_name;
$this->isValidMime($input_type_name_array);
$this->_permitted_files = array_merge($this->_permitted_files, $input_type_name_array);
}
protected function processFile($fileName, $error, $size, $type, $tmp_name, $overwrite)
{
$check_upload_error = $this->checkError($fileName, $error);
if($check_upload_error){
$check_uploaded_file_type = $this->checkType($fileName, $type);
$check_uploaded_file_size = $this->checkSize($fileName, $size);
if($check_uploaded_file_type && $check_uploaded_file_size){
$new_uploaded_file_name = $this->checkName($fileName, $overwrite);
$upload_result = move_uploaded_file($tmp_name, $this->_destination_upload_folder.$new_uploaded_file_name);
if($upload_result){
$messages = $new_uploaded_file_name.' uploaded successfully! <br >';
if($this->_renamed_file){
$messages .= ' and renamed successfully!';
}
$this->_error_messages[] = $messages;
} else {
$this->_error_messages[] = 'Could`nt upload '.$fileName;
}
}
}
}
public function move($overwrite = FALSE){
$file = current($this->_uploaded);
if(is_array($file['name'])){
foreach($file['name'] as $index => $filename){
$this->_renamed_file = false;
$this->processFile($filename, $file['error'][$index],
$file['size'][$index], $file['type'][$index], $file['tmp_name'][$index], $overwrite);
}
}else{
$this->processFile($file['filename'], $file['error'], $file['size'], $file['type']
, $file['tmp_name'], $overwrite);
}
}
public function getErrorMessages(){
return $this->_error_messages;
}
public function setMaxSize($new_upload_size)
{
if(!is_numeric($new_upload_size) || $new_upload_size <= 0){
throw new Exception("new maximum upload size must a number!");
}
$this->_max_upload_size = (int)$new_upload_size;
}
}
$max_upload_size = 1024 * 1024;
if(isset($_POST['upload_button'])){
$destination_upload_folder = 'destination of upload folder here....';
require_once 'Upload class filename...';
try{
$upload = new Upload($destination_upload_folder);
$upload->setMaxSize($max_upload_size);
$upload->addPermittedType('application/pdf');
$upload->move(true);
$result = $upload->getErrorMessages();
}catch(Exception $e){
echo $e->getMessage();
}
}
I need help with a Remote Upload Script that has a page named 'uploadHandler.php'. I need to create a Remote Upload Script with jQuery PHP File Upload (jQuery File Upload). I would like to upload through this script a file that comes from a different server by entering only the URL. How can this be done?
Let me explain. I have a form that sends a request to uploadHandler.php when a user uploads a file from his computer. The problem is that the type is 'multipart/form-data' so I cannot upload via URL. I tried to put a URL but the system returns
[{"name":"","size":0,"type":null,"error":"File received has zero size."}]
So, what should I do to make sure that the file is processed by uploadHandler.php and then stored correctly? I had thought to download the file from the server and then upload it to do so treated. But how? I enclose the contents of uploadHandler.php for those who want to read it. Thank you in advance for your help, and I apologize for the grammar and vocabulary wrong: I'm not English.
class uploadHandler
{
private $options;
function __construct($options = null)
{
// get accepted file types
$acceptedFileTypes = getAcceptedFileTypes();
$this->options = array(
'script_url' => $_SERVER['PHP_SELF'],
'upload_dir' => _CONFIG_FILE_STORAGE_PATH,
'upload_url' => dirname($_SERVER['PHP_SELF']) . '/files/',
'param_name' => 'files',
'delete_hash' => '',
// The php.ini settings upload_max_filesize and post_max_size
// take precedence over the following max_file_size setting:
'max_file_size' => $this->get_max_upload_size(),
'min_file_size' => 1,
'accept_file_types' => COUNT($acceptedFileTypes) ? ('/(\.|\/)(' . str_replace(".", "", implode("|", $acceptedFileTypes)) . ')$/i') : '/.+$/i',
'max_number_of_files' => null,
'discard_aborted_uploads' => true,
'image_versions' => array(
'thumbnail' => array(
'upload_dir' => dirname(__FILE__) . '/thumbnails/',
'upload_url' => dirname($_SERVER['PHP_SELF']) . '/thumbnails/',
'max_width' => 80,
'max_height' => 80
)
)
);
if ($options)
{
$this->options = array_replace_recursive($this->options, $options);
}
}
private function get_max_upload_size()
{
// Initialize current user
$Auth = Auth::getAuth();
// max allowed upload size
$maxUploadSize = SITE_CONFIG_FREE_USER_MAX_UPLOAD_FILESIZE;
if ($Auth->loggedIn())
{
// check if user is a premium/paid user
if ($Auth->level != 'free user')
{
$maxUploadSize = SITE_CONFIG_PREMIUM_USER_MAX_UPLOAD_FILESIZE;
}
}
// if php restrictions are lower than permitted, override
$phpMaxSize = getPHPMaxUpload();
if ($phpMaxSize < $maxUploadSize)
{
$maxUploadSize = $phpMaxSize;
}
return $maxUploadSize;
}
private function get_file_object($file_name)
{
$file_path = $this->options['upload_dir'] . $file_name;
if (is_file($file_path) && $file_name[0] !== '.')
{
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->options['upload_url'] . rawurlencode($file->name);
foreach ($this->options['image_versions'] as $version => $options)
{
if (is_file($options['upload_dir'] . $file_name))
{
$file->{$version . '_url'} = $options['upload_url']
. rawurlencode($file->name);
}
}
$file->delete_url = '~d?' . $this->options['delete_hash'];
$file->info_url = '~i?' . $this->options['delete_hash'];
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
private function get_file_objects()
{
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->options['upload_dir'])
)));
}
private function create_scaled_image($file_name, $options)
{
$file_path = $this->options['upload_dir'] . $file_name;
$new_file_path = $options['upload_dir'] . $file_name;
list($img_width, $img_height) = #getimagesize($file_path);
if (!$img_width || !$img_height)
{
return false;
}
$scale = min(
$options['max_width'] / $img_width, $options['max_height'] / $img_height
);
if ($scale > 1)
{
$scale = 1;
}
$new_width = $img_width * $scale;
$new_height = $img_height * $scale;
$new_img = #imagecreatetruecolor($new_width, $new_height);
switch (strtolower(substr(strrchr($file_name, '.'), 1)))
{
case 'jpg':
case 'jpeg':
$src_img = #imagecreatefromjpeg($file_path);
$write_image = 'imagejpeg';
break;
case 'gif':
$src_img = #imagecreatefromgif($file_path);
$write_image = 'imagegif';
break;
case 'png':
$src_img = #imagecreatefrompng($file_path);
$write_image = 'imagepng';
break;
default:
$src_img = $image_method = null;
}
$success = $src_img && #imagecopyresampled(
$new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height
) && $write_image($new_img, $new_file_path);
// Free up memory (imagedestroy does not delete files):
#imagedestroy($src_img);
#imagedestroy($new_img);
return $success;
}
private function has_error($uploaded_file, $file, $error)
{
if ($error)
{
return $error;
}
if (!preg_match($this->options['accept_file_types'], $file->name))
{
return 'acceptFileTypes';
}
if ($uploaded_file && is_uploaded_file($uploaded_file))
{
$file_size = filesize($uploaded_file);
} else
{
$file_size = $_SERVER['CONTENT_LENGTH'];
}
if ($this->options['max_file_size'] && (
$file_size > $this->options['max_file_size'] ||
$file->size > $this->options['max_file_size'])
)
{
return 'maxFileSize';
}
if ($this->options['min_file_size'] &&
$file_size < $this->options['min_file_size'])
{
return 'minFileSize';
}
if (is_int($this->options['max_number_of_files']) && (
count($this->get_file_objects()) >= $this->options['max_number_of_files'])
)
{
return 'maxNumberOfFiles';
}
return $error;
}
private function handle_file_upload($uploaded_file, $name, $size, $type, $error)
{
$fileUpload = new stdClass();
$fileUpload->name = basename(stripslashes($name));
$fileUpload->size = intval($size);
$fileUpload->type = $type;
$fileUpload->error = null;
$extension = end(explode(".", $fileUpload->name));
$fileUpload->error = $this->has_error($uploaded_file, $fileUpload, $error);
if (!$fileUpload->error)
{
if (strlen(trim($fileUpload->name)) == 0)
{
$fileUpload->error = 'Filename not found.';
}
}
elseif (intval($size) == 0)
{
$fileUpload->error = 'File received has zero size.';
}
elseif (intval($size) > $this->options['max_file_size'])
{
$fileUpload->error = 'File received is larger than permitted.';
}
if (!$fileUpload->error && $fileUpload->name)
{
if ($fileUpload->name[0] === '.')
{
$fileUpload->name = substr($fileUpload->name, 1);
}
$newFilename = MD5(microtime());
// figure out upload type
$file_size = 0;
// select server from pool
$uploadServerId = getAvailableServerId();
$db = Database::getDatabase(true);
$uploadServerDetails = $db->getRow('SELECT * FROM file_server WHERE id = ' . $db->quote($uploadServerId));
// override storage path
if(strlen($uploadServerDetails['storagePath']))
{
$this->options['upload_dir'] = $uploadServerDetails['storagePath'];
if (substr($this->options['upload_dir'], strlen($this->options['upload_dir']) - 1, 1) == '/')
{
$this->options['upload_dir'] = substr($this->options['upload_dir'], 0, strlen($this->options['upload_dir']) - 1);
}
$this->options['upload_dir'] .= '/';
}
// move remotely via ftp
if($uploadServerDetails['serverType'] == 'remote')
{
// connect ftp
$conn_id = ftp_connect($uploadServerDetails['ipAddress'], $uploadServerDetails['ftpPort'], 30);
if($conn_id === false)
{
$fileUpload->error = 'Could not connect to file server '.$uploadServerDetails['ipAddress'];
}
// authenticate
if(!$fileUpload->error)
{
$login_result = ftp_login($conn_id, $uploadServerDetails['ftpUsername'], $uploadServerDetails['ftpPassword']);
if($login_result === false)
{
$fileUpload->error = 'Could not authenticate with file server '.$uploadServerDetails['ipAddress'];
}
}
// create the upload folder
if(!$fileUpload->error)
{
$uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
if(!ftp_mkdir($conn_id, $uploadPathDir))
{
// Error reporting removed for now as it causes issues with existing folders. Need to add a check in before here
// to see if the folder exists, then create if not.
// $fileUpload->error = 'There was a problem creating the storage folder on '.$uploadServerDetails['ipAddress'];
}
}
// upload via ftp
if(!$fileUpload->error)
{
$file_path = $uploadPathDir . '/' . $newFilename;
clearstatcache();
if ($uploaded_file && is_uploaded_file($uploaded_file))
{
// initiate ftp
$ret = ftp_nb_put($conn_id, $file_path, $uploaded_file,
FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA)
{
// continue uploading
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED)
{
$fileUpload->error = 'There was a problem uploading the file to '.$uploadServerDetails['ipAddress'];
}
else
{
$file_size = filesize($uploaded_file);
#unlink($uploaded_file);
}
}
}
// close ftp connection
ftp_close($conn_id);
}
// move into local storage
else
{
// create the upload folder
$uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
#mkdir($uploadPathDir);
$file_path = $uploadPathDir . '/' . $newFilename;
clearstatcache();
if ($uploaded_file && is_uploaded_file($uploaded_file))
{
move_uploaded_file($uploaded_file, $file_path);
}
$file_size = filesize($file_path);
}
// check filesize uploaded matches tmp uploaded
if ($file_size === $fileUpload->size)
{
$fileUpload->url = $this->options['upload_url'] . rawurlencode($fileUpload->name);
// insert into the db
$fileUpload->size = $file_size;
$fileUpload->delete_url = '~d?' . $this->options['delete_hash'];
$fileUpload->info_url = '~i?' . $this->options['delete_hash'];
$fileUpload->delete_type = 'DELETE';
// create delete hash, make sure it's unique
$deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime());
$existingFile = file::loadByDeleteHash($deleteHash);
while ($existingFile != false)
{
$deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime());
$existingFile = file::loadByDeleteHash($deleteHash);
}
// store in db
$db = Database::getDatabase(true);
$dbInsert = new DBObject("file", array("originalFilename", "shortUrl", "fileType", "extension", "fileSize", "localFilePath", "userId", "totalDownload", "uploadedIP", "uploadedDate", "statusId", "deleteHash", "serverId"));
$dbInsert->originalFilename = $fileUpload->name;
$dbInsert->shortUrl = 'temp';
$dbInsert->fileType = $fileUpload->type;
$dbInsert->extension = $extension;
$dbInsert->fileSize = $fileUpload->size;
$dbInsert->localFilePath = str_replace($this->options['upload_dir'], "", $file_path);
// add user id if user is logged in
$dbInsert->userId = NULL;
$Auth = Auth::getAuth();
if ($Auth->loggedIn())
{
$dbInsert->userId = (int) $Auth->id;
}
$dbInsert->totalDownload = 0;
$dbInsert->uploadedIP = getUsersIPAddress();
$dbInsert->uploadedDate = sqlDateTime();
$dbInsert->statusId = 1;
$dbInsert->deleteHash = $deleteHash;
$dbInsert->serverId = $uploadServerId;
if (!$dbInsert->insert())
{
$fileUpload->error = 'abort';
}
// create short url
$tracker = 1;
$shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
$fileTmp = file::loadByShortUrl($shortUrl);
while ($fileTmp)
{
$shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
$fileTmp = file::loadByShortUrl($shortUrl);
$tracker++;
}
// update short url
file::updateShortUrl($dbInsert->id, $shortUrl);
// update fileUpload with file location
$file = file::loadByShortUrl($shortUrl);
$fileUpload->url = $file->getFullShortUrl();
$fileUpload->delete_url = $file->getDeleteUrl();
$fileUpload->info_url = $file->getInfoUrl();
$fileUpload->stats_url = $file->getStatisticsUrl();
$fileUpload->short_url = $shortUrl;
}
else if ($this->options['discard_aborted_uploads'])
{
//#TODO - made ftp compatible
#unlink($file_path);
#unlink($uploaded_file);
if(!isset($fileUpload->error))
{
$fileUpload->error = 'maxFileSize';
}
}
}
return $fileUpload;
}
public function get()
{
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name)
{
$info = $this->get_file_object($file_name);
} else
{
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
public function post()
{
$upload = isset($_FILES[$this->options['param_name']]) ?
$_FILES[$this->options['param_name']] : array(
'tmp_name' => null,
'name' => null,
'size' => null,
'type' => null,
'error' => null
);
$info = array();
if (is_array($upload['tmp_name']))
{
foreach ($upload['tmp_name'] as $index => $value)
{
$info[] = $this->handle_file_upload($upload['tmp_name'][$index],
isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
$upload['error'][$index]
);
}
} else
{
$info[] = $this->handle_file_upload($upload['tmp_name'],
isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'],
isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'],
isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'],
$upload['error']
);
}
header('Vary: Accept');
if (isset($_SERVER['HTTP_ACCEPT']) &&
(strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false))
{
header('Content-type: application/json');
} else
{
header('Content-type: text/plain');
}
echo json_encode($info);
}
}
$upload_handler = new uploadHandler();
header('Pragma: no-cache');
header('Cache-Control: private, no-cache');
header('Content-Disposition: inline; filename="files.json"');
// check we are receiving the request from this script
if (!checkReferrer())
{
// exit
header('HTTP/1.0 400 Bad Request');
exit();
}
switch ($_SERVER['REQUEST_METHOD'])
{
case 'HEAD':
case 'GET':
$upload_handler->get();
break;
case 'POST':
$upload_handler->post();
break;
default:
header('HTTP/1.0 405 Method Not Allowed');
}
You need downloader. Not uploader. You want to download a file to your server from another server. To achieve that from PHP, you can use cUrl or file_get_contents. In the form, just take the URL and when the form is submitted, download the file from that URL to your server using cUrl or file_get_contents().