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];
}
Related
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!
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();
}
}
hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}
I am using directory iterator to iterate through directories and resize images found in that directory, I am doing this from browser cause I don't have ssh access to that server.
Most pictures resize fine but for every 10 pictures (more or less) I get jiberish data out.
I think it's a picture source. in that data there is always a string CREATOR: gd-jpeg v1.0 so I'm wondering what is this? I disabled any error output with # sign.
EDIT:
Here is the code, and also I disabled error output cause there aren't any errors and I thought that disabling error output would disable this jiberish data, but data is displayed no matter.
Code:
<?php
/*
big = 350
thumb = 90
thumb2 = 70
top = 215
*/
set_time_limit(0);
ini_set('memory_limit', '128M');
ini_set('display_errors', 'On');
class ResizeImages
{
private $dir = 'images/articles_backup_2009-12-19';
private $imageType = array(
'_big' => 'h:350',
'_thumb' => 'm:90',
'_thumb2' => 'h:70',
'_top' => 'h:215'
);
public function __construct()
{
$this->deleteImages();
$this->resizeImages();
}
private function resizeImages()
{
$n = 0;
$dh = opendir($this->dir);
while (($file = readdir($dh)) !== false)
{
if(is_dir($this->dir."/".$file) && $file != '.' && $file != '..')
{
echo $this->dir."/".$file.'<br />';
$deldir = opendir($this->dir."/".$file);
while (($filedel = readdir($deldir)) !== false)
{
if ($filedel != '.' && $filedel != '..' && $filedel != 'Thumbs.db')
{
$val = $this->resize($this->dir."/".$file."/".$filedel);
$n++;
}
}
}
}
closedir($dh);
}
private function resize($target)
{
$img = $target;
$origSize = getimagesize($img);
$origWidth = $origSize[0];
$origHeight = $origSize[1];
foreach($this->imageType as $key=>$value)
{
$attr = explode(':', $value);
if(strpos($attr[0], 'w') !== false)
{
$this->imageWidth = $attr[1];
$this->imageHeight = false;
}
if(strpos($attr[0], 'h') !== false)
{
$this->imageHeight = $attr[1];
$this->imageWidth = false;
}
$imageTmp = explode('.', $img);
if(count($imageTmp) == 2) $image_name_fin = $imageTmp[0].$key.'.'.$imageTmp[1];
else if(count($imageTmp) == 4) $image_name_fin = $imageTmp[0].'.'.$imageTmp[1].$key.'.'.$imageTmp[2];
if($this->imageWidth != false)
{
if($origWidth <= $this->imageWidth)
{
$resizeHeight = $origHeight;
$resizeWidth = $origWidth;
}
else
{
$resizeHeight = round($origHeight / ($origWidth / $this->imageWidth));
$resizeWidth = $this->imageWidth;
}
}
else if($this->imageHeight != false)
{
if($origHeight <= $this->imageHeight)
{
$resizeHeight = $origHeight;
$resizeWidth = $origWidth;
}
else
{
$resizeWidth = round($origWidth / ($origHeight / $this->imageHeight));
$resizeHeight = $this->imageHeight;
}
}
$im = ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = ImageCreateFromPNG ($img) or // or PNG Image
$im = ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im)
{
$this->error = array(
'error' => true,
'notice' => 'UPLOADUNSUCCESSFULL'
);
return $this->error;
}
$thumb = ImageCreateTrueColor ($resizeWidth, $resizeHeight);
ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $resizeWidth, $resizeHeight, $origWidth, $origHeight);
ImageJPEG ($thumb, $image_name_fin, $this->imageQuality);
//echo $image_name_fin.'<br />';
}
$this->error = array(
'imageUrl' => $image_name,
'error' => false,
'notice' => 'IMAGEUPLOADED'
);
return $this->error;
}
private function deleteImages()
{
$dh = opendir($this->dir);
while (($file = readdir($dh)) !== false)
{
if(is_dir($this->dir."/".$file))
{
//echo $file.'<br />';
$deldir = opendir($this->dir."/".$file);
while (($filedel = readdir($deldir)) !== false)
{
if(strpos($this->dir."/".$file."/".$filedel, '_big.') !== false || strpos($this->dir."/".$file."/".$filedel, '_thumb.') !== false || strpos($this->dir."/".$file."/".$filedel, '_thumb2.') !== false || strpos($this->dir."/".$file."/".$filedel, '_top.') !== false)
{
unlink($this->dir."/".$file."/".$filedel);
}
}
}
}
closedir($dh);
}
}
$batch = new ResizeImages;
?>
At the top add this:
error_reporting(E_ALL);
And try changing this:
$im = ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = ImageCreateFromPNG ($img) or // or PNG Image
$im = ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
To this:
$im = ImageCreateFromString(file_get_contents($img));
Did it help? Also is there any pattern on the corrupted images? Are they all of the same type?
Well, the first thing would be to remove the error suppression to see if there is any errors. Seeing some of your code could be helpful as well.
EDIT
Ok, too late to fix your problem, but here is another suggestion for your code. All that "readdir, decide if file, build path" stuff is just a pain to use (and look at). Try this for an alternative:
class ImageFilterIterator extends FilterIterator
{
public function accept()
{
$ext = pathinfo($this->current()->getRealPath(), PATHINFO_EXTENSION);
return stripos('.gif|.jpg|.png', $ext);
}
}
$path = '.';
$images = new ImageFilterIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)));
Iterators are from the SPL and while they are somewhat puzzling to use at first, they can make development much easier once you understood them. With the above you can now loop over $image and get all filenames ending in .gif, .jpg or .png from all directories below path, like this:
foreach($images as $image) {
echo $image;
}
In fact, $image is not just a string, but an SplFileInfo object, so you also get a bunch of useful other methods with it.
How can I merge two images in PHP without GD?
PHP doesn't have the built in support to do what your asking. You'll need to
Execute another command line script/program that can
Install one of the many image manipulation libs and work with that
Possibly find a 3rd party API that you can send a request and get a response of the merged images?
Do as Emil suggested (Requires install: http://bg.php.net/manual/en/imagick.setup.php)
You can use Imagick.
You can't do image processing in PHP without some library like GD or ImageMagick.
i used this block of codes in my project to merge various images into one:
<?php
/* example invocation: http://www.yourserver.com/combine.php?dir=/images/ */
set_time_limit(5*60);
function sanitize($input) {
$input=strip_tags($input);
$input=str_replace("<","<",$input);
$input=str_replace(">",">",$input);
$input=str_replace("#","%23",$input);
$input=str_replace("'","`",$input);
$input=str_replace(";","%3B",$input);
$input=str_replace("script","",$input);
$input=str_replace("%3c","",$input);
$input=str_replace("%3e","",$input);
$input=trim($input);
return $input;
}
//accept path to images via http param dir (e.g. '/templates/corporate/images/okb/' -- include trailing slash)
$rel = '';
if (array_key_exists("dir", $_REQUEST)) $rel = sanitize($_REQUEST["dir"]);
if ($rel=='') die();
$rt = $_SERVER['DOCUMENT_ROOT'] . $rel;
$i = 0;
$imgBuf = array ();
$maxW=0; $maxH=0;
$imagesperline = 5;
$curlineW = 0;
$curlineMaxH = 0;
$imagespacing=5;
$dir = opendir ($rt);
while (false !== ($link = readdir($dir)))
{
$len = strlen($link);
$off = $len - 3;
$ext = substr($link, $off, 3);
$file = $rt . $link;
switch($ext)
{
case 'png':
$iTmp = imagecreatefrompng($file);
break;
case 'gif':
$iTmp = imagecreatefromgif($file);
break;
case 'jpeg':
case 'jpg':
$iTmp = imagecreatefromjpeg($file);
break;
default:
continue;
}
array_push ($imgBuf,$iTmp);
$i++;
if ($i == $imagesperline + 1)
{
$i = 0;
$maxW=($maxW>$curlineW)?$maxW:$curlineW;
$curlineW = 0;
$maxH+=$curlineMaxH+$imagespacing;
$curlineMaxH=0;
}
else
{
$ix = imagesx($iTmp);
$iy = imagesy($iTmp);
$curlineW+=$ix+$imagespacing;
$curlineMaxH=($iy>$curlineMaxH)?$iy:$curlineMaxH;
}
}
$iOut = imagecreate ($maxW,$maxH) ;
$i=1;
$curxpos = 0;
$curypos = 0;
$curlineMaxH=0;
foreach ($imgBuf as $img)
{
if ($i <= $imagesperline)
{
$ix = imagesx($img);
$iy = imagesy($img);
imagecopy ($iOut,$img,$curxpos,$curypos,0,0,$ix,$iy);
$curxpos+=$ix + $imagespacing;
$curlineMaxH=($iy>$curlineMaxH)?$iy:$curlineMaxH;
}
else
{
$i = 0;
$curxpos = 0;
$curypos += $curlineMaxH + $imagespacing;
$curlineMaxH = 0;
imagecopy ($iOut,$img,$curxpos,$curypos,0,0,$ix,$iy);
}
imagedestroy ($img);
$i++;
}
imagegif($iOut);
closedir ($dir);
?>