How to check file extension in laravel post request? mycodetest - php

Here is my code it is working but I want the best practice
if(Input::hasFile('note_thumb')) {
$file = Input::file('note_thumb');
$fileName = substr($file->getClientOriginalName(), -4);
if ($fileName == '.jpg' || $fileName == 'jpeg' || $fileName == '.png') {
//is image
//return 'maaz';
$finalpath = "";
$file = Input::file('note_thumb');
$tmpFilePath = '/notes/thumnail/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$tmpFileName = preg_replace('/\s+/', '', $tmpFileName);
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFileName;
$finalpath .= $path;
/*if ($i != $count_file - 1) {
$finalpath .= ',';
}*/
$newNote->note_thumb = $finalpath;
}

Try this:
$extension = $request->note_thumb->getClientOriginalExtension();
From the documentation:
https://laravel.com/docs/5.6/requests

Related

Strict Standards: "Only variables should be passed by reference"

In the php function below I have on line 31 the error "Strict Standards: Only variables should be passed by reference"
As I read the answers on the forum I must change the explode(..). But I don’t have any idea how..
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'png'))
{
if (substr($directory, -1) == 'uploads/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path) && in_array(end(explode('.', end(explode('/', $path)))), $exts) // Line 31
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
According to the PHP Manual for end:
This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.
Parameter should be sent as an array variable only.
ToDo:
Break this statement inside if:
is_file($path) && in_array(end(explode('.', end(explode('/', $path)))), $exts)
to something like this:
$path1 = explode('/', $path);
$path2 = end($path1);
$path3 = explode('.', $path1);
$path4 = end($path3);
is_file($path) && in_array($path4, $exts)
Alternatively,
Since you are getting extension from the path, you can use pathinfo:
pathinfo($path)['extension']
You can try this code:
<?php
<?php
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'png'))
{
if (substr($directory, -1) == 'uploads/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
$path_info = pathinfo($path);
$ext = strtolower($path_info['extension']);
if (is_file($path) && in_array($ext, $exts)) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
try to separate your code in the if statement like this, this should work :
// other code
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
$explode_1 = explode('/', $path);
$explode_2 = explode('.', end($explode_1));
if (is_file($path) && in_array(end($explode_2), $exts)) {
// the rest of the code

auto increment file names when uploading them in laravel

I wrote a controller to upload files to a Directory. and I want if a file exists already in that Directory ,before moving , file name To be changed by increment one unit from last similar existent file name like this:
test.jpg
test(1).jpg
test(2).jpg
This is body of my Controller
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$destinationFolder = public_path('upload/userfiles/');
$num = 1;
$newName = $fileName;
while (file_exists($destinationFolder . $newName )) {
$newName = $fileName. '(' . $num . ')';
$num ++;
}
$file->move($destinationFolder, $newName . '.' . $fileExt);
But this does not work correctly and create file name like this :
test.jpg
test(1).jpg
test(1)(2).jpg
your problem is this:
$newName = $fileName;
at first is test.jpg
then you append the ($num++) so it becomes test(1).jpg
the next time its still test(1).jpg
and you append the ($num++) then it becomes test(1)(2).jpg
Thats it
This will work:
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$destinationFolder = public_path('upload/userfiles/');
$num = 1;
$newName = $fileName;
$appendNum = false;
while (file_exists($destinationFolder . $newName )) {
$appendNum = true;
$num ++;
}
if ($appendNum) $newName = $fileName. '(' . $num . ')';
$file->move($destinationFolder, $newName . '.' . $fileExt);
this work for me :
$current_name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$only_name = explode('.', $current_name)[0];
$new_name = $current_name;
$destination = Storage::disk($link_directory)->path($folder);
$all_files = Storage::disk($link_directory)->listContents($folder);
$searchword = $only_name;
$matches = array_filter($all_files, function($var) use ($searchword) {
if(strpos($var['filename'], $searchword) !== FALSE) {
return $var;
}
});
if( is_array($matches) ){
$new_name = $only_name. '_' . count($matches).'.'.$extension;
}
$filename = Storage::disk($link_directory)->putFileAs($folder, $file, $new_name);
I have created a simple helper function that generates file name:
if (!function_exists('generateFilename')) {
/**
* Generate filename
*
* #param string $disk
* #param string $path
* #param UploadedFile $file
* #param integer $count
* #return string $filename
*/
function generateFilename(string $disk, string $path, UploadedFile $file, int $count = 0)
{
$extension = $file->getClientOriginalExtension();
$filename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . ($count == 0 ? "." . $extension : "-{$count}." . $extension);
$filePath = Str::of($path)->finish(DIRECTORY_SEPARATOR)->finish($filename)->toString();
if (Storage::disk($disk)->exists($filePath)) {
$count++;
return generateFilename($disk, $path, $file, $count);
}
return $filename;
}
}

PHP: How to pass "current $_FILE" to another function after iterate $_FILES global variable?

If I submit a form with multiple files in it, how can I upload each of them after some kind of execution one by one?
Add something like this to your PHP page
//upload image 1
if ($filename1<>"") {
$filename = $filename1;
$file = 'file1';
$temp = explode(".", $_FILES["file1"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image1 = '$newfilename' where yachtid = '$yachtid'");
}
//upload image 2
if ($filename2<>"") {
$filename = $filename2;
$file = 'file2';
$temp = explode(".", $_FILES["file2"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image2 = '$newfilename' where yachtid = '$yachtid'");
}
And then the file called "upload_file.php should look something like this (change the validation sections if you want it to validate on different file names). Also, this renames the file to a random name before saving it to your location);
<?php
$length = 30;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$code = "";
for ($p = 0; $p < $length; $p++) {
$pos = mt_rand(0, strlen($characters)-1);
$code .= $characters{$pos};
}
$parts = explode('.',$filename);
$extension= end($parts);
$newfilename=$code .".".$extension;
$success = 0;
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end($temp);
if ((($_FILES[$file]["type"] == "image/gif") || ($_FILES[$file]["type"] == "image/jpeg") || ($_FILES[$file]["type"] == "image/jpg")
|| ($_FILES[$file]["type"] == "image/pjpeg") || ($_FILES[$file]["type"] == "image/x-png") || ($_FILES[$file]["type"] == "image/png"))
&& ($_FILES[$file]["size"] < 1000000) && in_array($extension, $allowedExts)) {
$filenamepng = "./images/yacht/".$code.".png";
$filenamegif = "./images/yacht/".$code.".gif";
$filenamejpeg = "./images/yacht/".$code.".jpeg";
$filenamejpg = "./images/yacht/".$code.".jpg";
$filenamepjpeg = "./images/yacht/".$code.".pjpeg";
$filenamexpng = "./images/yacht/".$code.".x-png";
if (file_exists($filenamepng)||file_exists($filenamegif)||file_exists($filenamejpeg)||file_exists($filenamejpg)||file_exists($filenamepjpeg)||file_exists($filenamexpng)) {
if (file_exists($filenamepng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.png';
unlink($filename);
}
if (file_exists($filenamegif)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.gif';
unlink($filename);
}
if (file_exists($filenamejpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpeg';
unlink($filename);
}
if (file_exists($filenamejpg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpg';
unlink($filename);
}
if (file_exists($filenamepjpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.pjpeg';
unlink($filename);
}
if (file_exists($filenamexpng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.x-png';
unlink($filename);
}
}
move_uploaded_file($_FILES[$file]["tmp_name"],
"images/yacht/" . $newfilename);
//echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
unset($code);
$success = 1;
}
else
{
$error = "Your image is over 1mb OR is not in an accepted format; gif, jpeg, jpg, pjpeg, x-png, or png. Please try again.";
}
?>
www.clubtray.com
www.clubtray-clubmembershipsoftware.com

PHP extracting files from zip issues with copy

I am trying to extract file from a zip via PHP, I have some working code, but when I move it from one server to another it all of sudden stopped working :( In this code, it creates folders, I can see its doing that, but the files in the zip are not being extracted :(
Here is my code:
if($_FILES['url']['error'] == 0){
system('rm -rf ../images/galleries/' . $galleryName);
$filename = $_FILES["url"]["name"];
$source = $_FILES["url"]["tmp_name"];
$type = $_FILES["url"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if (!file_exists('../images/galleries/' . $galleryName)) {
mkdir('../images/galleries/' . $galleryName, 0777, true);
}
$target_path = '../images/galleries/' . $galleryName . '/' . $filename;
$image = $filename;
if(move_uploaded_file($source, $target_path)) {
$path = $target_path;
$zip = new ZipArchive();
if ($zip->open($path) === true) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_")) . '_';
copy("zip://".$path."#".$filename, '../images/galleries/' . $galleryName . '/' . $fileinfo['basename']);
chmod('../images/galleries/' . $galleryName . '/' . $fileinfo['basename'], 0777);
}
$zip->close();
}
}
unlink($path);
$galleryClass->insertImage($connection, $_POST['galleryId'], $image, $_POST['link'], $_POST['order']);
}
I think the issue is with this:
copy("zip://".$path."#".$filename, '../images/galleries/' . $galleryName . '/' . $fileinfo['basename']);
is there another way to do this or is this a server problem?
Try using the extractTo() method instead of copy():
$zip->extractTo('../images/galleries/' . $galleryName . '/' . $fileinfo['basename'], $filename);

PHP Rename file if exists

I've been working with image uploading and am wondering why this isn't working correctly? It doesn't move/upload the file with the new name if it already exists.
if(isset($_REQUEST['submit'])){
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)){
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
}
else{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");
}
}
else{
echo "invalid file.";
}
}
You've included the folder path in $loc, then you attempt to move a file to userpics/$loc, which is probably incorrect. See the comments:
$filename = "example.jpg";
$loc = "userpics/$filename";
if(file_exists($loc)){
$increment = 0;
list($name, $ext) = explode('.', $loc);
while(file_exists($loc)) {
$increment++;
// $loc is now "userpics/example1.jpg"
$loc = $name. $increment . '.' . $ext;
$filename = $name. $increment . '.' . $ext;
}
// Now you're trying to move the uploaded file to "userpics/$loc"
// which expands to "userpics/userpics/example1.jpg"
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
} else {
// ...
As a general debugging tip, always check a function's return value to see if it was successful. Secondly, display the function's input values if it's failing. It will make debugging things a lot easier.
Try this:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
Thanks to here:Clickie!!

Categories