I have some problem with uploading image into PHP server. In this case, first I'l get image from gallery than create the output as base64, then I convert base64 to file using stream, then upload it into server. Here is my code.
UploadActivity.kt
private fun updatePhoto(variable: String, file: Bitmap, userId: String) {
val encode = encodedImage(file)
val outputDir: File = this.cacheDir
val f = File.createTempFile(userId, ".jpeg", outputDir)
var fos: FileOutputStream? = null
try {
fos = FileOutputStream(f)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
try {
fos!!.write(encode)
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
val builder = MultipartBody.Builder()
builder.setType(MultipartBody.FORM)
val requestFile = f.asRequestBody(getMimeType(f.path)?.toMediaTypeOrNull())
builder.addFormDataPart(variable, f.name, requestFile)
builder.addFormDataPart("userId", userId)
val apiService = ApiInterface.create()
val call = apiService.updatePicture(builder.build())
call.enqueue(object : Callback<UserModel> {
override fun onResponse(
call: Call<UserModel>,
response: retrofit2.Response<UserModel>?
) {
val jsonObject = response!!.body()
val returnedResponse = jsonObject!!.status
if (returnedResponse!!.trim { it <= ' ' } == "200") {
val intent = Intent(this#UploadPreviewActivity, ProfileActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
finish()
} else {
Toast.makeText(
this#UploadPreviewActivity,
"Terjadi kesalahan, harap coba kembali.",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: Call<UserModel>, t: Throwable) {
call.cancel()
Toast.makeText(
this#UploadPreviewActivity,
"Harap periksa koneksi internet anda",
Toast.LENGTH_LONG
).show()
}
})
}
Interface.kt
#POST("user-update-picture")
fun updatePicture(#Body requestBody: RequestBody): Call<UserModel>
Upload.php
function resize_image($file) {
$src = imagecreatefromstring($file);
if (!$src) return false;
$width = imagesx($src);
$height = imagesy($src);
$newwidth = $width*0.5;
$newheight = $height*0.5;
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
ob_start();
imagejpeg($dst);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$data2 = base64_decode($picturePath);
$thumb = $this->resize_image($data2);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
public function picture_post(){
date_default_timezone_set('Asia/Jakarta');
$Date = date('Y-m-d H:i:s');
$userId = filter_var($this->post('userId'), FILTER_SANITIZE_NUMBER_INT);
if (isset($_FILES['userPhotoPath']['tmp_name']) && !empty($_FILES['userPhotoPath']['tmp_name']) && $_FILES['userPhotoPath']['tmp_name']!=NULL) {
$photoPath = $_FILES['userPhotoPath']['tmp_name'];
$photoType = $_FILES['userPhotoPath']['type'];
$photoData = file_get_contents($photoPath);
$userPhotoPath = 'data:' . $photoType . ';base64,' . base64_encode($photoData);
if(file_exists("./files/images/users/".$userId.".jpg")){
$unlink = unlink("./files/images/users/".$userId.".jpg");
}
if(file_exists("./files/images/users_thumb/".$userId.".jpg")){
$unlink2 = unlink("./files/images/users_thumb/".$userId.".jpg");
}
$this->decodeImage($userPhotoPath, 'users', 'users_thumb', $userId);
}else{
$userPhotoPath = NULL;
}
}
Then when I upload the file from android I get this error in Okhttp Log
Message: imagecreatefromstring(): Data is not in a recognized format
Backtrace:
Function: imagecreatefromstring
I don't know why, because my PHP code work with my web version of this application with same upload method using javascript
I solve this issue by my self and this my mistake,
I change this code
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$data2 = base64_decode($picturePath);
$thumb = $this->resize_image($data2);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
into this
function decodeImage($picturePath, $dir, $dir_thumb, $userId){
$image = str_replace('data:image/png;base64,', '', str_replace('[removed]', '', $picturePath));
$image = str_replace(' ', '+', $image);
$data = base64_decode($image);
$thumb = $this->resize_image($data);
$file = './files/images/'.$dir.'/'.$userId.'.jpg';
$upload = file_put_contents($file, $data);
$file2 = './files/images/'.$dir_thumb.'/'.$userId.'.jpg';
$upload2 = file_put_contents($file2, $thumb);
}
This is my little mistake I forgot about the rezise_image content requirement, after change that code this upload work 100% without any problem again.
Related
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');
}
},
);
}
I have jquery plugin which send image in base 64 encoded format which i want to store in server
here is what I've tried
$post = json_decode($_POST['file'], true); $data = $post['output']['image'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
require('/home/example/public_html/files/image/class.upload.php');
$code = md5(time());
$handle = new upload($data);
if ($handle->uploaded) {
$handle->file_new_name_body = "$code";
$handle->mime_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = 600;
$handle->process('/home/example/public_html/files/blog/img/');
if ($handle->processed) {
$file_name = $handle->file_dst_name;
} else {
echo "error";
}
}
My above code image upload class works on every image but i'm unable to uploade base 64 encoded image, how can i achieve that
The upload class you're using doesn't support feeding base64 directly into it. You're best off using this method to save a temporary version to your directory first, using the class to do what you need to do, then deleting it:
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
require('/home/example/public_html/files/image/class.upload.php');
$code = md5(time());
$write_dir = "/home/example/public_html/files/blog/img/";
$temp_code = "temp_".$code;
$ifp = fopen($write_dir.$temp_code, "wb");
fwrite($ifp, $data);
fclose($ifp);
$handle = new upload($write_dir.$temp_code);
if ($handle->uploaded) {
$handle->file_new_name_body = "$code";
$handle->mime_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$handle->jpeg_quality = 70;
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = 600;
$handle->process($write_dir);
if ($handle->processed) {
$file_name = $handle->file_dst_name;
unlink($write_dir.$temp_code);
} else {
echo "error";
}
}
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've been creating a HTML5 Drag & Drop image up-loader. All is good with the Javascript side of things however the PHP is driving me crazy!
I've been able to create a script that successfully places a image in a folder upon the drop of an image, however once it tries to create a thumb nail for the image and place the image link into the users db table it all goes to pot. I've sat here for hours on end, trying and trying to no avail, so i believe as it is now just about 3am GMT i should admit defeat and ask for a little help.
The JavaScript:
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname:'pic',
maxfiles: 5,
maxfilesize: 200,
url: 'uploadCore.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files!');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 200mb.');
break;
default:
break;
}
},
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
image.attr('src',e.target.result);
};
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
Now for the PHP:
<?php
// db connection
include("db-info.php");
$link = mysql_connect($server, $user, $pass);
if(!mysql_select_db($database)) die(mysql_error());
include("loadsettings.inc.php");
//$upload_dir = 'pictures/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
if (isset($_SESSION["imagehost-user"]))
{
$session = true;
$username = $_SESSION["imagehost-user"];
$password = $_SESSION["imagehost-pass"];
$q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
if(!($result_set = mysql_query($q))) die(mysql_error());
$number = mysql_num_rows($result_set);
if (!$number) {
session_destroy();
$session = false;
}else {
$row = mysql_fetch_row($result_set);
$loggedId = $row[0];
}
}
$date = date("d-m-y");
$lastaccess = date("y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$type = "public";
$pic = $_FILES['pic'];
$n = $pic;
$rndName = md5($n . date("d-m-y") . time()) . "." . get_extension($pic['name']);
$upload_dir = "pictures/" . $rndName;
move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
// issues starts here
$imagePath = $upload_dir;
$img = imagecreatefromunknown($imagePath);
$mainWidth = imagesx($img);
$mainHeight = imagesy($img);
$a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
$div = $a / 150;
$thumbWidth = intval($mainWidth / $div);
$thumbHeight = intval($mainHeight / $div);
$myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
$thumbPath = "thumbnails/" . basename($imagePath);
imagejpeg($myThumb, $thumbPath);
$details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
$id = md5($thumbPath . date("d-m-y") . time());
$q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
if(!($result_set = mysql_query($q))) die(mysql_error());*/
exit_status('File was uploaded successfuly!');
// to here
$result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
$number = mysql_num_rows($result);
if ($number) die(""); // blocked IP message
function imagecreatefromunknown($path) {
$exten = get_extension($path);
switch ($exten) {
case "jpg":
$img = imagecreatefromjpeg($path);
break;
case "gif":
$img = imagecreatefromgif($path);
break;
case "png":
$img = imagecreatefrompng($path);
break;
}
return $img;
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
It seems you pass wrong path to the imagecreatefromunknown() function. You pass $imagePath that equals $upload_dir, but your image destination is $upload_dir.$pic['name']