issue uploading image on symfony - php

/**
* Upload the image while creating/updating records
* #param File Object $file
*/
public function setImageAttribute($file)
{
// Only if a file is selected
if ($file) {
File::exists(public_path() . '/uploads/') || File::makeDirectory(public_path() . '/uploads/');
File::exists(public_path() . '/' . $this->images_path) || File::makeDirectory(public_path() . '/' . $this->images_path);
File::exists(public_path() . '/' . $this->thumbs_path) || File::makeDirectory(public_path() . '/' . $this->thumbs_path);
$file_name = $file->getClientOriginalName();
$image = Image::make($file->getRealPath());
if (isset($this->attributes['image'])) {
// Delete old image
$old_image = $this->getImageAttribute();
File::exists($old_image) && File::delete($old_image);
}
if (isset($this->attributes['thumb'])) {
// Delete old thumbnail
$old_thumb = $this->getThumbAttribute();
File::exists($old_thumb) && File::delete($old_thumb);
}
$image->save($this->images_path . $file_name)
->fit(640, 180)
->save($this->thumbs_path . $file_name);
$this->attributes['image'] = $file_name;
}
}
and this is my error msg
production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function getClientOriginalName() on a non-object' in C:\Doptor\app\components\posts\models\Post.php:79
line 79 is here
$file_name = $file->getClientOriginalName();
$image = Image::make($file->getRealPath());

Check out this entry in the cookbook since I think you will get this easier uploading your image directly with Doctrine.
Secondly, you can also probe that your $file is the right object by checking this:
if ($file instanceof UploadedFile) {
// do stuff
} else {
exit("file is not the right object, so getClientOriginalName will not work");
}

Related

Image uploaded in Laravel 5.8 keep saving as private image

I am trying upload a single image into a Post and it keeps saving it as a private image--heck, I don't even know where to find that file.
PostController.php
...
if ($request->hasFile('photo')) {
$photo = $request->photo;
$ext = $photo->getClientOriginalExtension();
$filename = uniqid() . '.' . $ext;
$photo->storeAs('public/posts/' . $request->user()->id, $filename);
}
...
storeAs() function takes three parameters.
storeAs(path,name,options)
'options' is where you specify file visibility. In your case :
if ($request->hasFile('photo')) {
$photo = $request->photo;
$ext = $photo->getClientOriginalExtension();
$filename = uniqid() . '.' . $ext;
$photo->storeAs('posts/' . $request->user()->id, $filename,'public');
}

Getting file information while loading on page with Laravel

I have upload form where I'm able to upload any type of files and save their path to database. Without saving any relevant information in database such as: filetype, filesize etc can I get this information while I loop the results and showing them on page?
Here is what I tried so far
public function fileUpload()
{
$allFiles = Documents::paginate(20);
$files = array();
foreach ($allFiles as $file) {
$files[] = $this->fileInfo(pathinfo(public_path() . '/uploads/' . $file));
}
return View::make('admin.files', [
'files' => $files
]);
}
public function fileInfo($filePath)
{
$file = array();
$file['name'] = $filePath['filename'];
$file['extension'] = $filePath['extension'];
$file['size'] = filesize($filePath['dirname'] . '/' . $filePath['basename']);
return $file;
}
The error which I get when I run the page is
ErrorException: filesize(): stat failed for .....
Is this the correct way of doing this?
Update: dd($filePath['dirname'] . '/' . $filePath['basename']); return
string(126) "/var/www/html/site/public/uploads/{"id":2,"document_path":"aut6MnADFrPZTz4TJf0Y.pdf","document_name":"Some title for the file"}"
Change this line
$files[] = $this->fileInfo(pathinfo(public_path() . '/uploads/' . $file));
to
$files[] = $this->fileInfo(pathinfo(public_path() . '/uploads/' . $file->document_path));

How delete exif data in this function?

I don't know how delete exif data from uploaded pictures. Here is my function:
$uploadedFiles = $request->getUploadedFiles();
if ($uploadedFiles && $id) {
$usersPath = '/collections/' . date('Y/m') . '/' . $id .'/';
$uploadFolder = realpath(BASE_PATH . '/uploads');
$uploadFolder .= $usersPath;
$newName = md5(time() . serialize($uploadedFiles));
$fileExtension = strtolower($uploadedFiles[0]->getExtension());
$sourceImgPath = $uploadFolder .$newName .'.' .$fileExtension;
if (!file_exists($uploadFolder)) {
mkdir($uploadFolder, 0777, true );
}
if(in_array($fileExtension, array('jpg', 'jpeg', 'png', 'gif'))){
if ($uploadedFiles[0]->moveTo($sourceImgPath)) {
$info = pathinfo($sourceImgPath);
if ($info) {
$file_path = $usersPath . $info['filename'] . '.' . $fileExtension;
(new \Rapid\Storage\CollectionsStorage())->editImage($id, $file_path);
} else {
$session->set('msg_error', $this->translate->_('There was an unexpected error with uploading the file'));
}
}
}
} else {
$session->set('msg_error', $this->translate->_('Invalid file type'));
}
This piece of code should delete all EXIF information in JPEG
$img = new Imagick($uploadfile);
$img->stripImage();
$img->writeImage($uploadfile);
It depends on the graphics libraries you have access to.
If you have access to imagick, you can use stripImage().
If you have only access to gd, you need to create a new image from the upload and save that instead, see for example PHP remove exif data from images for a jpg image.

PHP file upload is creating filenames starting with "PHP" and with .tmp extension

I am using PHP (Symfony2) in my project which has image upload feature. Inside controller:
if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$index=(int)$request->request->get('index');
$image_file = $request->files->get('shop_bundle_managementbundle_posttype')['images'][$index]['file'];
$image= new Image();
$image->setFile($image_file);
$image->setSubDir('hg');
$image->upload();
$em->persist($image);
$em->flush();
}
I use a class UploadFileMover that handle the file upload. I didn't write the following code but as I understand, an MD5 hash will be created from the original file name and used as filename. But the instance of UploadedFile contains a file name like "PHP"+number.tmp, not the original as stored in computer filesystem.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath)
{
$originalName = $file->getFilename();
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i=1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
This class is instanciated when an image is uploaded. In other words, I have an Entity Image that has a method upload. Inside entity class:
public function upload()
{
if (null === $this->getFile()) {
return;
}
$uploadFileMover = new UploadFileMover();
$this->path = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDir(),$this->subDir);
$this->file = null;
}
I var_dumped the filename all across the different steps but I cannot figure out where it is transformed to PHP16653.tmp.
Can it be related to an APACHE related configuration? Your help is appreciated. I really did a lot of research for similar issue in the web to no avail.
The problem was created by the line:
$originalName = $file->getFilename();
Use:
$originalName = $file->getClientOriginalName();
instead.

Adding image file check security to Valums Ajax Uploader

I've been doing research on image file upload security for a while but can't seem to crack it. I want to add some security to the fantastic Valums Ajax Uploader by checking whether or not a file is actually an image before saving to a server. The only extensions allowed are .jpg, .png and .gif, which of course the extensions are checked but I'm looking to validate it's an image file via GD processing. I know very little about this subject so I'm taking cues from this and this post. As it stands now, I can easily save a random file with an image extension and it will be saved the server, which I want to prevent. Here is the script I've come up with thus far, which I've added to the handleUpload function in the php.php file. Unfortunately the result is that it returns an error no matter what file I upload, valid image or not. Please excuse my utter newbishness.
$newIm = #imagecreatefromjpeg($uploadDirectory . $filename . '.' . $ext);
$newIm2 = #imagecreatefrompng($uploadDirectory . $filename . '.' . $ext);
$newIm3 = #imagecreatefromgif($uploadDirectory . $filename . '.' . $ext);
if (!$newIm && !$newIm2 && !$newIm3) {
return array('error' => 'File is not an image. Please try again');
}else{
imagedestroy($newIm);
imagedestroy($newim2);
imagedestroy($newIm3);
}
Here's most of my php.php file. By the way, my files are not being submitted via a regular form but by the default uploader:
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 = 2097152;
private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 2097152){
$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 * 1024 * 1024);
case 'm': $val *= (1024 * 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, please upload files that are less than 2MB');
}
$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);
}
}
$newIm = #imagecreatefromjpeg($uploadDirectory . $filename . '.' . $ext);
$newIm2 = #imagecreatefrompng($uploadDirectory . $filename . '.' . $ext);
$newIm3 = #imagecreatefromgif($uploadDirectory . $filename . '.' . $ext);
if (!$newIm && !$newIm2 && !$newIm3) {
return array('error' => 'File is not an image. Please try again');
}else{
imagedestroy($newIm);
imagedestroy($newim2);
imagedestroy($newIm3);
}
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
// At this point you could use $result to do resizing of images or similar operations
if(strtolower($ext) == 'jpg' || strtolower($ext) == 'jpeg' || strtolower($ext) == 'gif' || strtolower($ext) == 'png'){
$imgSize=getimagesize($uploadDirectory . $filename . '.' . $ext);
if($imgSize[0] > 100 || $imgSize[1]> 100){
$thumbcheck = make_thumb($uploadDirectory . $filename . '.' . $ext,$uploadDirectory . "thumbs/" . $filename ."_thmb" . '.' . $ext,100,100);
if($thumbcheck == "true"){
$thumbnailPath = $uploadDirectory . "thumbs/" . $filename ."_thmb". '.' . $ext;
}
}else{
$this->file->save($uploadDirectory . "thumbs/" . $filename ."_thmb" . '.' . $ext);
$thumbnailPath = $uploadDirectory . "thumbs/" . $filename ."_thmb". '.' . $ext;
}
if($imgSize[0] > 500 || $imgSize[1] > 500){
resize_orig($uploadDirectory . $filename . '.' . $ext,$uploadDirectory . $filename . '.' . $ext,500,500);
$imgPath = $uploadDirectory . $filename . '.' . $ext;
$newsize = getimagesize($imgPath);
$imgWidth = ($newsize[0]+30);
$imgHeight = ($newsize[1]+50);
}else{
$imgPath = $uploadDirectory . $filename . '.' . $ext;
$newsize = getimagesize($imgPath);
$imgWidth = ($newsize[0]+30);
$imgHeight = ($newsize[1]+50);
}
}
return array('success'=>true,
'thumbnailPath'=>$thumbnailPath,
'imgPath'=>$imgPath,
'imgWidth'=>$imgWidth,
'imgHeight'=>$imgHeight
);
} 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 = 2097152;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload('uploads/');
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
If someone can point me in the right direction about what I'm doing wrong, it would be most appreciated.
Edit:
Thanks Mark B for the help and clarification. So the new code (which I pasted in the same location as the old, the handleUpload function) is still throwing an error no matter what I upload, so I wonder if it needs to be in a different place -- I'm just not sure where to put it.
$newIm = getimagesize($uploadDirectory . $filename . '.' . $ext);
if ($newIm === FALSE) {
return array('error' => 'File is not an image. Please try again');
}
Second Edit:
I believe the answer is here, still trying to implement it.
Just use getimagesize():
$newIm = getimagesize$uploadDirectory . $filename . '.' . $ext');
if ($newIm === FALSE) {
die("Hey! what are you trying to pull?");
}
The problem with your code is the 3 imagecreate calls and subsequent if() statement. It should have been written as an OR clause. "if any of the image load attempts fail, then complain". Yours is written as "if all image attempts fail", which is not possible if a gif/jpg/png actually was uploaded.
The answer detailed here works like a charm, I wish I had seen it before posting. I hope I implemented it correctly...as I have it, it works!
class qqUploadedFileXhr {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
// Store the file in tmp dir, to validate it before storing it in destination dir
$input = fopen('php://input', 'r');
$tmpPath = tempnam(sys_get_temp_dir(), 'upload'); // upl is 3-letter prefix for upload
$tmpStream = fopen($tmpPath, 'w'); // For writing it to tmp dir
$realSize = stream_copy_to_stream($input, $tmpStream);
fclose($input);
fclose($tmpStream);
if ($realSize != $this->getSize()){
return false;
}
$newIm = getimagesize($tmpPath);
if ($newIm === FALSE) {
return false;
}else{
// Store the file in destination dir, after validation
$pathToFile = $path . $filename;
$destination = fopen($pathToFile, 'w');
$tmpStream = fopen($tmpPath, 'r'); // For reading it from tmp dir
stream_copy_to_stream($tmpStream, $destination);
fclose($destination);
fclose($tmpStream);
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.');
}
}
}

Categories