jQuery and PHP Remote Upload - php

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().

Related

trim() expects parameter 1 to be string

Got a situation with image import process, before asking here of course - tried many ways to solve it by myself, but without any luck yet.
I'm getting error in model file: trim() expects parameter 1 to be string, array given in file /.../file.php on line 3875. Have to mention that - when there's single image - importing that perfectly, as soon as getting multiple images (more than one) - getting this error, and doesn't importing any image, just skipping.
Line 387: $image = trim($image);
Whole function code:
protected function imageHandler($field, &$config, $multiple = false, $item_id = NULL) {
$image_array = array();
if (empty($config['columns'][$field])) {
if ($multiple) {
return $image_array;
} else {
return '';
}
}
$sort_order = 0;
foreach ((array) $config['columns'][$field] as $images) {
if (!empty($config['multiple_separator']) && is_string($images)) {
$images = explode(#html_entity_decode($config['multiple_separator']), $images);
}
//is_array($images) && reset($images);
if ($multiple && is_array($images) && $config['columns']['image'] == $images[key($images)]) {
array_shift($images);
}
foreach ((array) $images as $image) {
$image = trim($image);
if ($config['image_download'] && $image) {
// if (substr($image, 0, 2) == '//') {
// $image = 'http:' . $image;
// }
$file_info = pathinfo(parse_url(trim($image), PHP_URL_PATH));
// if no extension, get it by mime
if (empty($file_info['extension'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, trim($image));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
switch($contentType) {
case 'image/bmp': $file_info['extension'] = 'bmp'; break;
case 'image/gif': $file_info['extension'] = 'gif'; break;
case 'image/jpeg': $file_info['extension'] = 'jpg'; break;
case 'image/pipeg': $file_info['extension'] = 'jfif'; break;
case 'image/tiff': $file_info['extension'] = 'tif'; break;
case 'image/png': $file_info['extension'] = 'png'; break;
default: $file_info['extension'] = '';
}
}
if (substr_count($file_info['dirname'], 'http')) {
// incorrect array extract
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $this->language->get('warning_incorrect_image_format') . ' ' . str_replace(' ', '%20', $image),
);
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if ($this->simulation) {
if (!$multiple) {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
return array('error_format', $image);
}*/
return $image;
} else {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$image_array[] = 'error_format';
continue;
}*/
$image_array[] = $image;
continue;
}
}
// detect if image is on actual server
if (strpos($image, 'http') === false) {
$filename = trim($image);
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
continue;
}
}
if (version_compare(VERSION, '2', '>=')) {
$path = 'catalog/';
//$http_path = HTTP_CATALOG . 'image/catalog/';
} else {
$path = 'data/';
//$http_path = HTTP_CATALOG . 'image/data/';
}
if (trim($config['image_location'], '/\\')) {
$path .= trim($config['image_location'], '/\\') . '/';
}
if ($config['image_keep_path'] && trim($file_info['dirname'], '/\\')) {
$path .= trim($file_info['dirname'], '/\\') . '/';
}
if (!is_dir(DIR_IMAGE . $path)) {
mkdir(DIR_IMAGE . $path, 0777, true);
}
$filename = $path . urldecode($file_info['filename']) . '.' . $file_info['extension'];
if (($item_id === false && $this->config->get('mlseo_insertautoimgname')) || ($item_id && $this->config->get('mlseo_editautoimgname'))) {
$this->load->model('tool/seo_package');
$seo_image_name = $this->model_tool_seo_package->transformProduct($this->config->get('mlseo_product_image_name_pattern'), $this->config->get('config_language_id'), $config['columns']);
$seoPath = pathinfo($filename);
if (!empty($seoPath['filename'])) {
$seoFilename = $this->model_tool_seo_package->filter_seo($seo_image_name, 'image', '', '');
$filename = $seoPath['dirname'] . '/' . $seoFilename . '.' . $seoPath['extension'];
if (file_exists(DIR_IMAGE . $filename)) {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $seoPath['dirname'] . '/' . $seoFilename . '-' . $x . '.' . $seoPath['extension'];
$x++;
}
}
}
}
if ($config['image_exists'] == 'rename') {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $path . urldecode($file_info['filename']) . '-' . $x++ . '.' . $file_info['extension'];
}
} else if ($config['image_exists'] == 'keep' && file_exists(DIR_IMAGE . $filename)) {
// image skipped
if (!$multiple) {
return $filename;
} else {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
continue;
}
}
// copy image, replace space chars for compatibility with copy()
// if (!#copy(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename)) {
$copyError = $this->copy_image(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename);
if ($copyError !== true) {
if (defined('GKD_CRON')) {
$this->cron_log($this->session->data['obui_current_line'] . ' - ' . $copyError);
} else {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $copyError,
);
}
$filename = '';
}
} else {
// get direct value
$filename = trim($image);
if ($this->simulation) {
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = $filename;
}
continue;
}
}
}
// one field only, directly return first value
if (!$multiple) {
return $filename;
}
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
}
}
return $image_array;
}
Tried to use return $image; after that line, even that didn't helped. Was trying to find similar problem to this one to find a solution without posting here, but seems like I won't move anywhere withou help. Thanks in advance!

Error when upload file Android

I want to upload image from galery to server. I succeed to upload image, but i just can upload 1 file. if i upload 2 file, the 2nd file will be upload. The 1st file will not upload. or if i edit and upload 2nd image file, then 1st image file will be replaced by 2nd image file.
this is webservicecontroller.php
$imagePath = IMAGE_PATH_FOR_TIM_THUMB.'/'.STUDY_MATERIAL_DIR.'/';
if (!empty($_POST))
{
$this->loadModel('StudyMaterial');
if($_POST['type'] != 'delete')
{
$shift = array();
if($_POST['type'] == 'edit')
{
$shift['StudyMaterial']['id'] = $_POST['study_material_id'];
}
$shift['StudyMaterial']['user_id'] = $_POST['user_id'];
$shift['StudyMaterial']['standard_id'] = $_POST['standard_id'];
$shift['StudyMaterial']['subject_id'] = $_POST['subject_id'];
$shift['StudyMaterial']['topic_id'] = $_POST['topic_id'];
$shift['StudyMaterial']['lesson_id'] = $_POST['lesson_id'];
$shift['StudyMaterial']['name'] = $_POST['name'];
$shift['StudyMaterial']['description'] = $_POST['description'];
$this->StudyMaterial->save($shift);
$study_material_id = $this->StudyMaterial->id;
if(isset($_FILES['study_material_file']) && !empty($_FILES['study_material_file']) && ($_FILES['study_material_file']['error'] == 0))
{
$name = $_FILES['study_material_file']['name'];
$ext = substr(strrchr($name, "."), 1);
$only_name = $name . "_" . time();
$filename = 'topic_file_'.microtime(true).'.'.strtolower($ext);
$original = STUDY_MATERIAL_DIR . "/" . $filename;
$file_type = $_POST['file_type'];
if($file_type == 'video')
{
if(strtolower($ext) == 'mov')
{
$original = STUDY_MATERIAL_DIR . "/" . $filename;
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
$new_filename = $only_name. '.mp4';
$srcFile = STUDY_MATERIAL_DIR . "/" . $filename;
$destFile = STUDY_MATERIAL_DIR . "/" . $new_filename;
exec('ffmpeg -i '.$srcFile.' -f mp4 -s 320x240 '.$destFile.'');
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
else
{
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
}
else
{
#move_uploaded_file($_FILES["study_material_file"]["tmp_name"], $original);
if($_POST['type'] == 'edit')
{
$checkAlready = $this->StudyMaterial->find('first',array('conditions'=>array('StudyMaterial.id'=>$_POST['study_material_id'])));
$image = $checkAlready['StudyMaterial']['file_name'];
if($image && file_exists(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image ))
{
#unlink(WWW_ROOT.STUDY_MATERIAL_DIR.DS.$image);
}
}
$this->StudyMaterial->saveField('file_name',$filename,false);
$this->StudyMaterial->saveField('type',$file_type,false);
}
}
else
{
if($_POST['type'] == 'edit')
{
$this->StudyMaterial->id = $_POST['study_material_id'];
$this->StudyMaterial->saveField('file_name','',false);
$this->StudyMaterial->saveField('type','',false);
}
}
if($_POST['type'] == 'edit')
{
$responseData = array(
'status' => 1,
'message' => "Study Material updated successfully."
);
}
else
{
$responseData = array(
'status' => 1,
'message' => "Study Material added successfully."
);
}
}
Is the problem in webservice or android? this is add_material.java
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
getActivity().startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Problem in your server side please check your database query where you update your column.

How do I modify this to upload multiple files?

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();
}
}

Blueimp Jquery File Upload S3 & Resize

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);
}

files arent creating aswell as folder structures not generating

im having trouble trying to get the file to upload. the aim is it to create a directory struction based on the work id, but its not creating the folder or uploading the file but it is returning that it has succeeded but also failed, ive spent the past few day trying to fix it but to no avail, can anyone see what is wrong with it or point me in the right direction
<?php
/**
* Handle file uploads via XMLHttpRequest
*/
class qqUploadedFileXhr {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()) {
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
return true;
}
function getName() {
return $_GET['qqfile'];
}
function getSize() {
if (isset($_SERVER["CONTENT_LENGTH"])) {
return (int) $_SERVER["CONTENT_LENGTH"];
} else {
throw new Exception('Getting content length is not supported.');
}
}
}
/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
class qqUploadedFileForm {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
return false;
}
return true;
}
function getName() {
return $_FILES['qqfile']['name'];
}
function getSize() {
return $_FILES['qqfile']['size'];
}
}
class qqFileUploader {
private $allowedExtensions = array();
private $sizeLimit = 10485760;
private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760) {
$allowedExtensions = array_map("strtolower", $allowedExtensions);
$this->allowedExtensions = $allowedExtensions;
$this->sizeLimit = $sizeLimit;
$this->checkServerSettings();
if (isset($_GET['qqfile'])) {
$this->file = new qqUploadedFileXhr();
} elseif (isset($_FILES['qqfile'])) {
$this->file = new qqUploadedFileForm();
} else {
$this->file = false;
}
}
private function checkServerSettings() {
$postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
}
}
private function toBytes($str) {
$val = trim($str);
$last = strtolower($str[strlen($str) - 1]);
switch ($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/**
* Returns array('success'=>true) or array('error'=>'error message')
*/
function handleUpload($uploadDirectory, $replaceOldFile = FALSE) {
if (!is_writable($uploadDirectory)) {
return array('error' => "Server error. Upload directory isn't writable.");
}
if (!$this->file) {
return array('error' => 'No files were uploaded.');
}
$size = $this->file->getSize();
if ($size == 0) {
return array('error' => 'File is empty');
}
if ($size > $this->sizeLimit) {
return array('error' => 'File is too large');
}
$pathinfo = pathinfo($this->file->getName());
$filename = $pathinfo['filename'];
//$filename = md5(uniqid());
$ext = $pathinfo['extension'];
if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of ' . $these . '.');
}
if (!$replaceOldFile) {
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)) {
return array('success' => true);
} else {
return array('error' => 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
}
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
//creates new folder if needed
$jid = $_GET['jobId'];
$fileType = $_GET['imgType'];
$dir = '\\JobData\\' . $jid . '\\' . $fileType . '\\' . '/n';
echo $dir;
//checks if directory exists if not creates it.
if (is_dir($dir)) {
$result = $uploader->handleUpload($dir);
} else {
if(!mkdir($dir,0,true))
{
die('Failed to create folders');
}
$result = $uploader->handleUpload($dir);
}
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
?>

Categories