I use laravel 5.3
My code to move image like this :
private function savePhoto($photos, $id)
{
foreach($photos as $key => $photo) {
$temp = storage_path() . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . $photo['name'];
$destinationPath = public_path() . DIRECTORY_SEPARATOR . 'img'. DIRECTORY_SEPARATOR .'products'.DIRECTORY_SEPARATOR.$id.DIRECTORY_SEPARATOR.$photo['name'];
if( rename( $temp , $destinationPath )){
echo 'moved!';
}
else {
echo 'failed';
}
}
}
When executed there exist error like this :
rename(C:\xampp\htdocs\myshop\storage\temp\NOTFCjMipXwFhBICo1tj6VXP5Qhv92Fg1kmawcUd.jpeg,C:\xampp\htdocs\myshop\public\img\products\77\NOTFCjMipXwFhBICo1tj6VXP5Qhv92Fg1kmawcUd.jpeg):
The system cannot find the path specified. (code: 3)
I think the error occurred because the $id folder is dynamically generated. The $id folder depends on the parameter id. If parameter id = 77, it will be formed like this:
C:\xampp\htdocs\myshop\public\img\products\77\NOTFCjMipXwFhBICo1tj6VXP5Qhv92Fg1kmawcUd.jpeg
So the error occurred because folder 77 does not exist yet
How to make folder 77(This is dynamically generated) first before moving the image?
Update
Sample array results from $photos like this :
Array
(
[0] => Array
(
[id] => 1
[name] => vYcHWLXpwhC9WfXd4XCB2emg83WMtWHphyUBq9MV.jpeg
)
[1] => Array
(
[id] => 2
[name] => 1STr51oF8cunSsNEJZyS9upI0hNHYMXjLCCSNonz.jpeg
)
)
Use mkdir()
private function savePhoto($photos, $id)
{
foreach ($photos as $key => $photo) {
$temp = storage_path() . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . $photo['name'];
$idDir = public_path() . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 'products' . DIRECTORY_SEPARATOR . $id;
$destinationPath = $idDir . DIRECTORY_SEPARATOR . $photo['name'];
if (!is_dir($idDir)) {
mkdir($idDir, 0777, TRUE);
}
if (rename($temp, $destinationPath)) {
echo 'moved!';
} else {
echo 'failed';
}
}
}
Related
I have an array of results and I want to create csv file for it. but if the result is valid I want to add the email in the valid csv file and if it is invalid then in the invalid csv file. but I am unable to do this. it adds all the emails to clean csv file and the invalid csv is empty. any suggestions
the results are looks like this:
Array
(
[0] => Array
(
[email] => tamas.szabo#millionverifier.com
[result] => valid
)
[1] => Array
(
[email] => support#millionverifier.com
[result] => valid
)
)
Here is my condition
// creating dirty and clean file
$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');
$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');
// adding headers to them
fputcsv($clean_emails, $headers);
fputcsv($dirty_emails, $headers);
if ($results[$i]['result'] === 'valid') {
// adding clean emails to csv
foreach ($results as $row) {
fputcsv($clean_emails, $row);
}
fclose($clean_emails);
} elseif ($results[$i]['result'] === 'invalid') {
// adding dirty emails to csv
foreach ($results as $row) {
fputcsv($dirty_emails, $row);
}
fclose($dirty_emails);
} else {
// if there are not any dirty or clean emails add them unknown to csv
$unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');
fputcsv($unknown_emails, $row);
fclose($unknown_emails);
}
May be you want line-by-line separation?
// creating dirty and clean file
$clean_emails = fopen(UPLOAD_DIRECTORY . '/clean/' . $file_name_new . '.' . $extension, 'w');
$dirty_emails = fopen(UPLOAD_DIRECTORY . '/dirty/' . $file_name_new . '.' . $extension, 'w');
$unknown_emails = null; // No file yet
// adding headers to them
fputcsv($clean_emails, $headers);
fputcsv($dirty_emails, $headers);
foreach ($results as $row) { // Scan each row
if ($row['result'] === 'valid') {
fputcsv($clean_emails, $row);
} elseif ($row['result'] === 'invalid') {
fputcsv($dirty_emails, $row);
} else { // found something else
if (!isset($unknown_emails)) { // Open file if it was not
$unknown_emails = fopen(UPLOAD_DIRECTORY . '/unknown/' . $file_name_new . '.' . $extension, 'w');
fputcsv($unknown_emails, $headers); // Add headers ?
}
fputcsv($unknown_emails, $row);
}
} // end loop
fclose($clean_emails);
fclose($dirty_emails);
if (isset($unknown_emails)) {
fclose($unknown_emails); // Close 'unknown' if it was opened
}
I have a image named Dark-Green.jpg but the output of function is DARK-GREEN.jpg so the image is not displaying due to case-sensitive.
So how can I fetch the image?
UPDATE
Below is my output of the array.
$output = Array
(
[WE05-5040*L] => Array
(
[qty] => 1
[stitching_category] => 2
[sku_image] => skuimages/WE05/DARK-GREEN.jpg
)
)
Then I am using this array in foreach loop like below.
foreach ($output as $ok => $op) {
$itemQty = $op['qty'];
$itemImagePath = $op['sku_image'];
echo "{$ok} has qty: {$itemQty} and the image as below.";
echo "<img src='{$itemImagePath}' width='50%' />"
}
Try this:
function getFile ($filename){
$files = glob($dir . '/*');
$filename = strtolower($filename);
foreach($files as $file) {
if (strtolower($file) == $filename){
return $file;
}
}
return false;
}
I have a folders/files tree inside admin folder (windows, localhost).
All files are .html.
Each of them (files and folders) is starting with some numbers and middle dash, for example
32-somefolder
624-somefile.html
I need to list all of them and remove all prefixes from their names.
So the result should be:
somefolder
somefile.html
foreach(glob("admin/*") as $el) {
echo $el . '.' . filetype($el) . '<br>';
}
First problem - only folders are listed:
admin/32-somefolder.dir
How to get files too, and how to rename i.e. remove prefixes from all the names?
You can use the second choice to list files : scandir, and recursive function :
function removePrefixFiles($dir, &$results = array()){
$files = scandir($dir);
foreach ($files as $key => $value){
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (! is_dir($path)) {
// treat the filename
$file = pathinfo($path);
$filename = explode('-', $file['filename']);
if (count($filename) > 0) {
// '-' is found, rename file
rename($path, $file['dirname'] .'/'. $filename[1] .'.'. $file['extension'];
}
$results[] = $path;
} else if ($value != '.' && $value != '..') {
removePrefixFiles($path, $results);
$results[] = $path;
}
}
// no real need to return something here, but can log the files
return $results;
}
$dir = '/admin';
removePrefixFiles($dir);
I have created two folder inside admin/ name as
1-files and 2-abc
then inside folder 1-files i have two files
11-java.html
11-text.html
then inside folder 2-abc i have two files
22-php.html
22-sql.html
<?php
$dir = "admin/";
// Sort in ascending order - this is default
$a = scandir($dir);
echo "<pre>";
if(count($a)>0){
$newArr = array();
for($i=2;$i<count($a);$i++){
$test = array();
$folderArr = array();
$folderName = explode('-',$a[$i]);
$test['folder'] = $folderName[1];
$b = scandir($dir.'/'.$a[$i]);
for($j=2;$j<count($b);$j++){
$fileName = explode('-',$b[$j]);
$folderArr[] = substr($fileName[1], 0, strpos($fileName[1], "."));;
}
$test['files'] = $folderArr;
$newArr[] = $test;
}
}
print_r($newArr);
?>
This will be the output
Array
(
[0] => Array
(
[folder] => files
[files] => Array
(
[0] => java
[1] => text
)
)
[1] => Array
(
[folder] => abc
[files] => Array
(
[0] => php
[1] => sql
)
)
)
Hope this willl hellp you.
I was trying to update my userprofile with the following controller but the problem is if i update only profile picture it shows the above error..But if i update every value it update successfully. How do i update the userProfile without updating every value :
public function updateUser(Request $request)
{
$this->validate($request, [
'profile_picture' => 'dimensions:width=400,height=400',
'cover_picture' => 'dimensions:width=800,height=400',
'avatar' => 'dimensions:width=80,height=80',
]);
if (\Auth::check())
{
$user= User::find(\Auth::id());
}
$files= [];
if($request->file('profile_picture')) $files[] = $request->file('profile_picture');
if($request->file('cover_picture')) $files[] = $request->file('cover_picture');
if($request->file('avatar')) $files[] = $request->file('avatar');
foreach($files as $file)
{
if(!empty($file))
{
$filename = time().str_random(20). '.' . $file->getClientOriginalExtension();
$file->move('users/',$filename);
$filenames[]=$filename;
}
}
$user->profile_picture = $filenames[0];
$user->cover_picture = $filenames[1];
$user->avatar = $filenames[2];
$user->save();
return redirect::back()->with('Warning',"Profile Updated Successfully");
}
I don't think it's wise using a positional array like this, As you've discovered, what if someone only wants to update their avatar. I feel your assignment into $files[] is redundant and you could go straight into your processing code.
Basically your current implementation means $files can be of a variable length, how do you know which is 0, 1 or 2 etc ?
With my approach, the code is now looping over each type of picture, and assigns it into the user with $user->$type directly by the same matching type property.
foreach( array( 'profile_picture', 'cover_picture', 'avatar' ) as $type)
{
if( $request->file( $type ) )
{
$filename = time() . str_random(20) . '.' . $request->file( $type )->getClientOriginalExtension();
$request->file( $type )->move( 'users/', $filename );
$user->$type = $filename;
}
}
If you find you need to map a different $source to the $type variable, you could do this with an additional array index...
foreach( array(
'profile_picture' => 'profile_picture',
'cover_picture' => 'cover_picture',
'avatar' => 'avatar'
) as $source => $type)
{
if( $request->file( $source ) )
{
$filename = time() . str_random(20) . '.' . $request->file( $source )->getClientOriginalExtension();
$request->file( $source )->move( 'users/', $filename );
$user->$type = $filename;
}
}
I finally came up with a solution mate.
You can try to Include a var_dump of $filenames. I suppose that $filenames[1] doesn't exist at all.
i make a template in which i select multiple files and i make php page in which i upload the files but when i upload the files it gives me error like
Warning: pathinfo() expects parameter 1 to be string, array given in C:\xampp\htdocs\jobboard\system\user-scripts\classifieds\apply_now.php on line 67
here is my code:
<input type="file" name="file_tmp[]" multiple />
and here is my apply_now.php:
if (!empty($_FILES['file_tmp']['name'])){
$fileFormats = explode(',',SJB_System::getSettingByName('file_valid_types'));
foreach ( $_FILES['file_tmp']['name'] as $file ) {
$fileInfo = pathinfo($file);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
}
}
The error is caused by the fact that you are giving an array as argument, instead of a string, just as the error message tells you.
This can be fixed by changing your foreach code to the following:
foreach ( $_FILES['file_tmp']['name'] as $key => $file ) {
$fileInfo = pathinfo($_FILES['file_tmp']['name'][$key]);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
}
Please also refer to my code in my answer on your previous question: https://stackoverflow.com/a/22355746/2539335
If you upload many files then $_FILES['file_tmp']['name'] will be an array.
You should make foreach loop
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
In you code replace:
$fileInfo = pathinfo($_FILES['file_tmp']['name']);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
With:
foreach ( $_FILES['file_tmp']['name'] as $file ) {
$fileInfo = pathinfo($file);
if ( !in_array(strtolower($fileInfo['extension']), $fileFormats) ) {
$errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
}
}