I am using the Blueimp/jQuery-File-Uploader and the Amazon S3 plugin that is available for it and all is working out fine however I need to resize my images to be no more or less that 640px on the shortest side.
my current code is
global $s3;
if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
return "";
}
$upload = isset($_FILES['files']) ? $_FILES['files'] : null;
$info = array();
if ($upload && is_array($upload['tmp_name'])) {
foreach($upload['tmp_name'] as $index => $value) {
$fileTempName = $upload['tmp_name'][$index];
$file_name = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index]);
$extension=end(explode(".", $file_name));
$rand = rand(1,100000000);
$sha1 = sha1($rand);
$md5 = md5($sha1);
$filename = substr($md5, 0, 8);
$fileName=$filename.".".$extension;
$fileName = $prefix.str_replace(" ", "_", $fileName);
$response = $s3->create_object($bucket, $fileName, array('fileUpload' => $fileTempName, 'acl' => AmazonS3::ACL_PUBLIC, 'meta' => array('keywords' => 'example, test'),));
if ($response->isOK()) {
$info[] = getFileInfo($bucket, $fileName);
} else {
// echo "<strong>Something went wrong while uploading your file... sorry.</strong>";
}
}
And I have written this bit of PHP however I am not sure as to how I can get the two working together.
$image = new Imagick('test2.jpg');
$imageprops = $image->getImageGeometry();
$w=$imageprops['width'];
$h=$imageprops['height'];
$edge = min($w,$h);
$ratio = $edge / 640;
$tWidth = ceil($w / $ratio);
$tHeight = ceil($h / $ratio);
if ($imageprops['width'] <= 640 && $imageprops['height'] <= 640) {
// don't upscale
} else {
$image->resizeImage($tWidth,$tHeight,imagick::FILTER_LANCZOS, 0.9, true);
}
$image->writeImage("test2-resized.jpg");
any help will be gratefully received, thanks
This is based on the assumption that all code in the OP's message was correct, and simply re-arranged it as requested.
Update: four upvotes (so far) seems to indicate the OP was correct not only regarding the code, but also regarding the magnitude of the issue. I do OSS as a matter of course, so by all means, let me know explicitly if this is of any interest to you so we can improve on this on github (any action is fine -- upvote the question, upvote the answer, post a comment, or any combination thereof).
function resize($imgName, $srcName)
{
$image = new Imagick($imgName);
$imageprops = $image->getImageGeometry();
$w=$imageprops['width'];
$h=$imageprops['height'];
$edge = min($w,$h);
$ratio = $edge / 640;
$tWidth = ceil($w / $ratio);
$tHeight = ceil($h / $ratio);
if ($imageprops['width'] <= 640 && $imageprops['height'] <= 640) {
return $imgName;
} else {
$image->resizeImage($tWidth,$tHeight,imagick::FILTER_LANCZOS, 0.9, true);
}
$extension=end(explode(".", $srcName));
// Change "/tmp" if you're running this on Windows
$tmpName=tempnam("/tmp", "resizer_").".".$extension;
$image->writeImage($tmpName);
return $tmpName
}
global $s3;
if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
return "";
}
$upload = isset($_FILES['files']) ? $_FILES['files'] : null;
$info = array();
if ($upload && is_array($upload['tmp_name'])) {
foreach($upload['tmp_name'] as $index => $value) {
$file_name = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index]);
$fileTempName = resize($upload['tmp_name'][$index], $file_name);
$extension=end(explode(".", $file_name));
$rand = rand(1,100000000);
$sha1 = sha1($rand);
$md5 = md5($sha1);
$filename = substr($md5, 0, 8);
$fileName=$filename.".".$extension;
$fileName = $prefix.str_replace(" ", "_", $fileName);
$response = $s3->create_object($bucket, $fileName, array('fileUpload' => $fileTempName, 'acl' => AmazonS3::ACL_PUBLIC, 'meta' => array('keywords' => 'example, test'),));
if ($response->isOK()) {
$info[] = getFileInfo($bucket, $fileName);
} else {
// `echo "<strong>Something went wrong while uploading your file... sorry.</strong>";`
}
unlink($fileTempName);
}
Related
I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}
How can i add image converter for this upload function? I would like always save image with JPG format.
This is my PHP code :
foreach($_FILES["thpostimg"]["error"] as $key => $value) {
if($_FILES["thpostimg"]["tmp_name"][$key] == NULL)
{ $thpostimg = $_FILES["thpostimg"]["name"][$key]; } else
{
$ext = strtolower(pathinfo($_FILES["thpostimg"]["name"][$key], PATHINFO_EXTENSION));
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name = substr(str_shuffle($chars), 0, 30);
$path = uniqid().'-'.$rand_dir_name.'.' .$ext;
$thpostimg = $path;
}
if($_FILES["thpostimg"]["tmp_name"][$key] == NULL){ } else
{
$arr_image_details = getimagesize($_FILES["thpostimg"]["tmp_name"][$key]);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$mime = $arr_image_details['mime'];
copy($_FILES['thpostimg']['tmp_name'][$key], './upload/'.$thpostimg);
}
}
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().
I use a image upload script which has stopped working now that my host has turned register_globals off. However, I don't know how do make it work without it. I'd be glad if you could help me out. Here's the code:
$uploadedfile = $_FILES['photo']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
// get the date from EXIF data
$exif = exif_read_data($uploadedfile, 0, true);
foreach ($exif as $key => $section) {
foreach ($section as $name => $val) {
if ($name == 'DateTimeOriginal') {
$the_filename = explode(" ", $val);
$the_filenamedate = str_replace(":", "", $the_filename[0]);
$the_filenametime = str_replace(":", "", $the_filename[1]);
$newfilename = $the_filenamedate."-".$the_filenametime.".jpg";
$the_datetime = explode(" ", $val);
$the_date = str_replace(":", "-", $the_datetime[0]);
$the_time = $the_datetime[1];
$datetime = $the_date." ".$the_time;
$exif_db = 'y';
}
}
}
// use current date and time if no exif data
if (empty($newfilename)) {
$newfilename = date("Ymd-His").".jpg";
$datetime = date("Y-m-d H:i:s");
$exif_db = 'n';
}
// resize if necessary
list($width,$height) = getimagesize($uploadedfile);
if ($resize_it == 'y') {
if ($width > $maxwidth) {
$newwidth = $maxwidth;
$newheight = ($height/$width)*$newwidth;
} else {
$newwidth = $width;
$newheight = ($height/$width)*$newwidth;
}
} else {
$newwidth = $width;
$newheight = $height;
}
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $dirpath.$gal_id."/".$newfilename;
imagejpeg($tmp,$filename,100);
// create thumbnail
$uploadedthumb = $_FILES['photo']['tmp_name'];
$srcthumb = imagecreatefromjpeg($uploadedthumb);
list($widththumb,$heightthumb) = getimagesize($uploadedthumb);
if ($widththumb > $heightthumb) {
$newheightthumb = 100;
$newwidththumb = ($widththumb/$heightthumb)*$newheightthumb;
} elseif ($widththumb == $heightthumb) {
$newheightthumb = 100;
$newwidththumb = 100;
} elseif ($widththumb < $heightthumb) {
$newwidththumb = 100;
$newheightthumb = ($heightthumb/$widththumb)*$newwidththumb;
} else {
$newheightthumb = 100;
$newwidththumb = ($widththumb/$heightthumb)*$newheightthumb;
}
$tmpthumb = imagecreatetruecolor($newwidththumb,$newheightthumb);
imagecopyresampled($tmpthumb,$srcthumb,0,0,$src_top,$src_left,$newwidththumb,$newheightthumb,$widththumb,$heightthumb);
$thumbname = $dirpath.$gal_id."/zth_".$newfilename.".jpg";
imagejpeg($tmpthumb,$thumbname,100);
// free memory, destroying the source's and the pic's canvas
imagedestroy($srcthumb);
imagedestroy($tmpthumb);
imagedestroy($src);
imagedestroy($tmp);
Thanks in advance!
Use the $_POST array to read posted form fields. A field named emil will have the value in the PHP variable $_POST['emil'], not in $emil. You have to change all instances where you read form fields.
The same applies for variables in the querystring, which is now found in $_GET, cookies in $_COOKIE and session variables in $_SESSION.
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.