imagescale function while uploading file - php

I try to implement a very simple scale function while uploading the file to the server. My host has 5.5.38 php version and gd is included and is 2.1.0 version.
The upload function worked until I tried to use the scale function. Obviously I am doing the wrong way but honestly I don't know what I am doing wrong and after a lot of research i am here to ask for your help..
This is the code that i use to upload file and scale it:
$id2 = $_POST['hiddenId'];
$ds = DIRECTORY_SEPARATOR;
// CREATE DIRECTORY
$dir = "gallery/g";
$dir .= $id2;
$dir .= "/";
$dir2 = '../../' . $dir;
if (!mkdir($dir2,0777,true));
$foldername = $dir;
if (!empty($_FILES)) {
/* DATA FOR DATABASE */
$images = '';
$images .= $dir;
$images .= $_FILES['file']['name'];
/* UPLOAD FILE */
$fileupload = basename( $_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
//$targetPath = dirname( __FILE__ ) . $ds . $foldername . $ds;
// FILE DIRECTORY
$targetPath = '../../' . $foldername;
// TRY TO SCALE IMAGE
$imagenew = ''; // NEW VARIABLE
$imagenew = imagecreatefromjpeg($tempFile); // PASSING THE TEMPFILE
$imagescaled = imagescale($imagenew, 800); // SCALING THE FILE
$targetFile = $targetPath. $imagescaled;
// MOVE SCALED FILE TO THE SERVER
move_uploaded_file($tempFile,$targetFile);
// UPDATE DATABASE
update_gallery($id2,$images,$con);
}
i inspected the code with firebug but it returns no error so I don't know where to start to catch the error.. May you help me please?

Related

File uploads in Laravel

I'm just starting out with Laravel and trying to get file uploads working using Dropzone JS. I can upload files successfully, but they're landing in app/Http/Controllers, where they're not then publicly accessible.
It seems to be treating this directory as the root, so if I specify /uploads as the folder then they'll go in app/Http/Controllers/uploads (which is obviously no good either). Using ..s doesn't seem to have any effect.
This is my store method for the file uploads:
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '';
if ( ! empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
I've also tried a number of other methods I found (below) but I get 500 errors in Chrome's element inspector with those.
From official docs
$path = $request->file('file')->store('uploads');
From a tutorial I found
$file = $request->file('file');
$destinationPath = '/';
$file->move($destinationPath,$file->getClientOriginalName());
From another tutorial
$uploadedFile = $request->file('file');
$filename = time().$uploadedFile->getClientOriginalName();
Storage::disk('local')->putFileAs(
'/'.$filename,
$uploadedFile,
$filename
);
The current method seems fine but just needs to store files in public/uploads.
Use this path instead:
$targetPath = public_path().'/uploads/';
I also suggest making a perfect route for our storage path so when someone adds hostname/storage it will not show your directory to someone only files can be accessible
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});

Image Upload is not working in a Laravel Project hosted in a shared server

I have deployed a Laravel project in a shared hosting. I have changed my .env file and copied all files from the public folder to the main directory and deleted the public folder. Now the problem is, whenever I am trying to upload an image, I am getting an internal server error. I suppose the problem is the Image Intervention is not getting the right folder to save the image. I have tried the both ways given below:
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('/images/admin/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
and
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = '/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
But None of these is working. Any possible Solution?
Use laravel base_path function, so your code will look like this
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = base_path().'/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
Answer Update
Issue was fileinfo extension missing or disbaled.
Try This.
use Storage;
use File;
if(!empty($request->file('admin_pro_pic')))
{
$file = $request->file('admin_pro_pic') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$admin->image=$fileName;
}
Create imges inside public directory.
I am handling it like this:
// check for defined upload folder inside .env file, otherwise use 'public'
$publicUploadDir = env('UPLOAD_PUBLIC', 'public/');
// get file from request
$image = $request->file('admin_pro_pic');
// hasing is not necessary, but recommended
$new['path'] = hash('sha256', time());
$new['folder] = 'images/admin/';
$new['extension'] = $file->extension();
// store uploaded file and retrieve path
$image->storeAs($publicUploadDir, implode($new, '.'));

How Do I Upload a File using a Laravel Package?

I have a file attachment feature in a Laravel package. I want the uploaded attachment to save in the project directory using the package and NOT within the package. Currently, the file is uploaded into the package uploads directory instead of the project uploads directory. Any suggestions on how to save this file in the right location?
Controller:
$attachment->spot_buy_item_id = $id;
$attachment->name = $_FILES['uploadedfile']['name'];
$attachment->created_ts = Carbon::now();
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = '../../../resources/uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['uploadedfile']['tmp_name']; //3
$extension = pathinfo($_FILES['uploadedfile']['name'], PATHINFO_EXTENSION);
$attachment_hash = md5($tempFile);
$new = $attachment_hash.'.'.$extension;
// complete creating attachment object with newly created attachment_hash
$attachment->hash = $new;
$attachment->save();
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $new; //5
move_uploaded_file($tempFile,$targetFile); //6
chmod($targetFile, 0777);
}
else
{
return "error";
}
Service Provider (I thought publishing the uploads folder might work - nope.)
public function boot()
{
require __DIR__ . '/Http/routes.php';
$this->loadViewsFrom(__DIR__ . '/resources/views', 'ariel');
$this->publishes([
__DIR__ . '/resources/uploads' => public_path('vendor/uploads'),
], 'public');
$this->publishes([
__DIR__ . '/../database/migrations' => database_path('migrations')], 'migrations');
}
HERE WE GO. I used the (well-documented) the Storage facade to work with the local filesystem (project).
https://laravel.com/docs/5.1/filesystem
$attachment->spot_buy_item_id = $id;
$attachment->name = $_FILES['uploadedfile']['name'];
$attachment->created_ts = Carbon::now();
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['uploadedfile']['tmp_name']; //3
$extension = pathinfo($_FILES['uploadedfile']['name'], PATHINFO_EXTENSION);
$attachment_hash = md5($tempFile);
$new = $attachment_hash.'.'.$extension;
// complete creating attachment object with newly created attachment_hash
$attachment->hash = $new;
$attachment->save();
$tmpPath = $storeFolder . $ds;
$targetFile = $tmpPath . $new; //5
Storage::disk('local')->put($targetFile, file_get_contents($request->file('uploadedfile')));
}
else
{
return "error";
}

Having trouble with explode() in uploadify.php

I have this snippet from my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
// this portion here will be true if and only if the file name of the uploaded file does not contain '.', except of course the dot(.) before the file extension
$count = 1;
list( $filename, $ext) = explode( '.', $name, );
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$count . ')' . '.' . $ext;
}
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Basically this is quite working. Uploading the file and getting the path of the file which will then be inserted on the database and so on. But, I tried uploading a file which file name looks like this,
filename.1.5.3.pdf
and when succesfully uploaded, the file name then became filename alone, without having the file extension and not to mention the file name is not complete. From what I understood, the problem lies on my explode(). It exploded the string having the delimiter '.' and then assigns it to the variables. What will I do to make the explode() cut the string into two where the first half is the filename and the second is the file extension? PLease help.
Don't use explode, use a function designed for the job: pathinfo()
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);

Help With Renaming Files With Uploadify

This is my code -
<?php
session_start();
include('connect.php');
mysqli_select_db($connect, "users");
$s = "select * from name where sessionusername = '$u'";
$q = mysqli_query($connect, $s);
$f = mysqli_fetch_array($q);
$name = $f['name'];
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
// Get the extension, and build the file name
//$extension = pathinfo($tempFile, PATHINFO_EXTENSION);
$extension = end(explode(".",$_FILES['Filedata']["name"]));
$new_file_name = '".$name."'".".$extension;
$targetFile = str_replace('//','/',$targetPath) . $new_file_name;
// $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
// } else {
// echo 'Invalid file type.';
// }
}
?>
Why is the above not working? As you can see, I am trying to pull down the name from the users database, and then rename the uploaded file to the name that was pulled from the db.
Can you help me out? Thanks a lot.
Is form enctype == 'multipart/form-data' ?
Ah, now I understand what you're talking about. You should remove your other post. This is an error I've actually encountered with Uploadify before, but I'm not sure what is going on here, specifically. Definitely, checkout your enctype, but for debugging, I implemented this solution for error reporting with Uploadify here: http://www.uploadify.com/forums/discussion/14/upload-script-error-reporting/p1.

Categories