Error when upload file Android - php

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.

Related

Flutter: Scanned 'Path' On Null

I'm trying to upload an image taken using the image picker package to my localhost server using a PHP API.
When the picture is taken, a message in the debug console appears saying "scanned (some path) to null" and the image path isn't saved.
I'd be very grateful if anyone who knows anything about this fills me in on how I can fix it. thank you in advance!
Here's my Relevant code:
-(PHP Backend)inserting an image to the database:
include_once "../../api/patients/create_image.php";
if (
isset($_POST["id"])
) {
if (!empty($_FILES["file"]['name']) )
{
$image = uploadImage("file", '../images/', 200,600);
$img_image = $image["image"];
}
else{
$img_image = "";
}
$id = $_POST["id"];
$insertArray = array();
array_push($insertArray, htmlspecialchars(strip_tags($img_image)));
array_push($insertArray, htmlspecialchars(strip_tags($id)));
$sql = "insert into patient_images (image, file_id) values (?,?)";
$result = dbExec($sql, $insertArray);
$resJson = array("result" => "success", "code" => 200, "body" => $insertArray);
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
} else {
//bad request
$resJson = array("result" => "fail", "code" => "400");
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
}
unction uploadImage($inputName, $uploadDir , $thumbnail_width , $image_width)
{
$image = $_FILES[$inputName];
//echo "error " . $image['name'] . $image['tmp_name'] . "end;";
$imagePath = '';
$thumbnailPath = '';
// echo "before";
// if a file is given
if (trim($image['tmp_name']) != '') {
$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];
// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";
list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);
// make sure the image width does not exceed the
// maximum allowed width
if ($width > $image_width) {
// echo "after";
$result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, $image_width);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
}
if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, $thumbnail_width);
// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}
(Front-end):
Future<bool> uploadFile(File imageFile, String id) async {
var stream = http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(path_api + 'patients/insertImage.php');
print(uri.path);
var request = http.MultipartRequest('POST', uri);
var multiPartFile = http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.fields['id'] = id;
request.files.add(multiPartFile);
var response = await request.send();
if (response.statusCode == 200) {
print('ok');
} else {
print('nope');
}
}
Future getImageCamera() async {
var image = await picker.pickImage(source: ImageSource.camera);
setState(
() {
if (image != null) {
_image = File(image.path);
} else {
print('no image selected');
}
},
);
}

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!

How to add user_id at the beginning of filename when upload to server

How to an add user_id ($_POST['pk']) at the beginning of the filename when I upload an image to server with the below function update_customer().
With this I can easily discover the correct files of a specific user.
Result should be:
filename = $_POST['pk'].'-'.$_POST['name']
function update_customer() {
if(isset($_POST['name']) && isset($_POST['pk'])) {
//print_r($_FILES['image']);exit;
$filename = '';
if(isset($_FILES['image']) && $_FILES['image']['tmp_name'] && $_FILES['image']['error'] == 0) {
$filename = $_FILES['image']['name'];
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/wp-content/uploads/agent_company_logos/';
$wp_filetype = wp_check_filetype_and_ext( $_FILES['image']['tmp_name'], $_FILES['image']['name'] );
if($wp_filetype['proper_filename'])
$_FILES['image']['name'] = $wp_filetype['proper_filename'];
if ( ( !$wp_filetype['type'] || !$wp_filetype['ext'] ) ) {
$arrErrors['file'] = __('File type not allowed', 'agent-plugin');
}
else {
move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir.$_FILES['image']['name']);
}
if(!empty($arrErrors) && count($arrErrors) == 0) {
die (json_encode(array('file' => agent_get_user_file_path($_FILES['image']['name']), 'caption' => '', 'status' => 1)));
}
//echo $_FILES['image']['name'];
}
$updated = $GLOBALS['wpdb']->update($GLOBALS['wpdb']->prefix.'agent_customer', array('company_logo' => $filename), array('user_id' => $_POST['pk']));
$dir = wp_upload_dir();
echo $dir['baseurl'] . '/agent_company_logos/'.$filename; exit(0);
}
echo 0;
die();
}
you can use
$basname = $_POST['pk'].basename($file);

I need to put resize image 150x130

I need help with image resize I don't know how to put in
<?php
if (isset($_POST['newcover'])) {
////GET image uploading settings
$select_upload_options = mysql_query("SELECT * FROM covers_submit_options");
$uop = mysql_fetch_assoc($select_upload_options);
$poster = $uop['cover_who_post'];
$approve = $uop['cover_approve'];
$server = $uop['cover_server'];
$default_user = $uop['cover_default_user'];
$cover_title = $_POST['title'];
$cover_desc = $_POST['desc'];
$cover_desc2 = $_POST['desc2'];
$cover_date = $_POST['date'];
$cover_tags = $_POST['tags'];
$cover_okvir = $_POST['okvir'];
$cover_velicina = $_POST['velicina'];
$cover_image2 = $_POST['image2'];
$cover_category = $_POST['huge'];
if ($poster != 'user' && $_SESSION['userid'] == '') {
$poster_user = $default_user;
} else {
$poster_user = $_SESSION['userid'];
}
if ($cover_title == '') {
$post_error = '<div class="alert alert-danger"><h3>Unesite Ime i Prezme</h3></div>';
} elseif ($cover_category == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Grad ii Općinu</h3></div>';
} elseif ($cover_date == '') {
$post_error = '<div class="alert alert-danger"><h3>Unesite Datum-Godište Npr. 1965-2016</h3></div>';
} elseif ($cover_okvir == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Izgled Osmrtnice</h3></div>';
} elseif ($poster_user == '') {
$poster_user = '1';
} elseif ($_FILES['photo']['size'] == '1') {
$post_error = '<div class="alert alert-danger"><h3>Please Select Image</h3></div>';
} else {
$post_error = '';
}
if ($post_error == '') {
if ($server == 'amazon') {
////////UPLOAD TO AMAZON/////////////////////
include('includes/amazonUpload.php');
////////UPLOAD TO AMAZON/////////////////////
} else {
////////////REGULAR UPLOADER TO SERVER/////////
list($file, $error) = upload('photo', 'images/covers/', 'jpg,jpeg,gif,png');
list($width, $height, $type, $attr) = ('images/covers/' . $file);
////////////Da bi upload slike mogao da radi uklonio sam dio koda orginal kod je ovaj dolje getimagesize prije zagrade images/covers /////////
if ($width < 0 || $height < 0) {
$post_error = "<div class='alert alert-danger'><h3>The Cover is Small<br>Please note that the Minimum allowed hight is 300px and Minimum Width is 800px </h3></div>";
unlink('images/covers/' . $file);
} else {
$image = 'images/covers/' . $file;
}
////////////REGULAR UPLOADER TO SERVER/////////
$error = $post_error;
}
////Store Into Database
if (!$error) {
$string = $slug;
if (strlen($string) != mb_strlen($string, 'utf-8')) {
$slug = date("M-D-His");
} else {
$slug = preg_replace("/[^a-zA-Z0-9_\-]/", '', $cover_title);
//$slug = preg_replace('/\s+/', '-', $cover_title);
$slug = strtolower($slug);
}
$is_slug_exists = mysql_query("SELECT * FROM covers_posts WHERE post_slug = '$slug' ");
$slug_exsits = mysql_num_rows($is_slug_exists);
if ($slug_exsits != '0') {
$slug = $slug . '-' . date('sy');
} else {
$slug = $slug;
}
$cover_datum = date("d-m-Y");
$insert = mysql_query("INSERT INTO covers_posts VALUES ('',
'$cover_title',
'$cover_desc',
'$cover_desc2',
'$cover_date',
'$cover_tags',
'$cover_okvir',
'$cover_velicina',
'$slug',
'$image',
'$cover_image2',
'$cover_category',
'1',
'$poster_user',
'$approve',
'0',
'0',
'0',
'$cover_datum'
) ");
order_badge($poster_user);
$post_error = '<div class="alert alert-success"><h3>Uspješno Ste Dodali Osmrtnicu , Prebacit će vas za 5 sekundi<br>
Ukolko ste zastali Kliknite Ovde
</h3></div>';
$redir = 'osmrtnica-' . $slug . '.html';
redirect($redir, '5');
} else {
$post_error = '<div class="alert alert-danger"><h3>' . $error . '</h3></div>';
}
} else {
$post_error = $post_error;
}
$smarty->assign('UploadResult', $post_error);
}
ok I know it is older script and I changed later in mysqli connection.
I read manual about upload and resize image now it is resize image but all image are black
elseif ($cover_okvir == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Izgled Osmrtnice</h3></div>';
}
elseif ($poster_user == '') {
$poster_user = '1';
}else{
////////////REGULAR UPLOADER TO SERVER/////////
list($file,$error) = upload('photo','images/covers/','jpg,jpeg,gif,png');
list($width, $height, $type, $attr) = getimagesize('images/covers/'.$file);
$width = 140;
$height = 150;
////////////REGULAR UPLOADER TO SERVER/////////
$src = imagecreatefromstring('images/covers/'.$file);
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height);
imagedestroy($src);
imagepng($dst,'images/covers/'.$file); // adjust format as needed
imagedestroy($dst);
}
$image = 'images/covers/'.$file;
enter code here

jQuery and PHP Remote Upload

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

Categories