I have a folder that I am fetching xml file contents from and inserting them into a database. The challenge that I have is to move files from original destination to another destination which in this case works as a backup storage.
I am getting an error that says
Call to undefined method Symfony\Component\Finder\SplFileInfo::getClientOriginalName()
In my controller I have used
use Symfony\Component\Finder\SplFileInfo;
Below is my code I am using to fetch file contents and inserting them into database.
public function store(Request $request)
{
$directory = storage_path('app/xmlentries/uploads'); //Folder I am getting file contents from
$files = File::allFiles($directory);
foreach($files as $file) {
$contents = $file->getContents();
foreach((array) $contents as $content)
{
$simpleXml = simplexml_load_string($content);
$data = [
'experience' => $simpleXml->ExportData->Requisition->EssentialFunction,
'job_requirements' => $simpleXml->ExportData->Requisition->EssentialFunction,
];
Vacancy::insert($data);
}
}
$destinationPath = storage_path('app/xmlentries/processed');
$request->file($file->getClientOriginalName())->move($destinationPath);
Please note that the inserting of file contents to database works fine. How would i get the filename of the files that I can use to move the files around to the new destination
From Laravel recipes:
if (!File::move($oldfile, $newfile))
{
die("Couldn't rename file");
}
Related
first of all to explain what I mean by my question, when I upload my files to the local storage I save them the following way:
$files = $request->file('files');
if ($request->hasFile('files')) {
foreach ($files as $file) {
//Get filename with the extension
$fileNameWithExt = $file->getClientOriginalName();
//Filename to store example: lead_4_document.pdf
$fileNameToStore = 'lead_' . $lead->id . '_' . $fileNameWithExt;
//Upload image
$path = $file->storeAs('/user_uploads', $fileNameToStore);
$lead->uploadFile()->create(array('filename' => $fileNameToStore, 'file_url' => $path, 'lead_id' => $lead->id));
}
}
So essentially I prepend lead_ the lead id and another _ to whatever the file is originally called during upload. The problem I face now is that I need to retrieve the associated files according to my lead ids. Here is my attempt so far:
$searchParam = 'lead_'.$lead->id.'_';
//$fileNames = File::glob('storage/user_uploads/'.$searchParam.'*');
//$files = File::get($fileNames);
$allFiles = Storage::files('user_uploads');
dd($allFiles);
Just to clarify, the 'File::glob' way seems to work, though it only outputs the names of the files not the actual files as object, which is what I need.
Okay, so I took a step back and went about this whole associated uploaded file to lead relationship a different way. Here is how I did it, just in case anyone stumbles across this and find themselves in the same boat as me.
The file upload now does a couple of things:
//check if file(s) is present in the request
if ($request->hasFile('files')) {
//checks if a directory already exists for a given lead (by id)
if (Storage::exists('/leads/'.$request->lead_id)) {
//if yes set the directory path to the existing folder
$directory = '/leads/'.$request->lead_id;
}
else {
//if not create a new directory with the lead id
Storage::makeDirectory('/leads/'.$request->lead_id);
$directory = '/leads/'.$request->lead_id;
}
foreach ($files as $file) {
//Get filename with the extension
$fileNameWithExt = $file->getClientOriginalName();
//Filename to store example: lead_4_document.pdf
$fileNameToStore = 'lead_' . $lead->id . '_' . $fileNameWithExt;
//Upload image
//'/user_uploads'
$file->storeAs($directory, $fileNameToStore);
//$lead->uploadFile()->create(array('filename' => $fileNameToStore, 'file_url' => $path, 'lead_id' => $lead->id));
}
}
So essentially, instead of trying to put all files into a single folder then checking the individual files for the 'lead_##' prepend, I instead create a folder with the id of the lead, this I then use the following way in my view function:
$directory = '/leads/'.$lead->id;
if (Storage::exists($directory)) {
$files = File::files('storage/'.$directory);
}
else {
$files = '';
}
Simply checking if the directory exists with the given lead ID, then if there are files uploaded either assign it the content, or set it blank (this is used for displaying an 'attachments' section on my page if not empty).
I have below code to upload excel file provided by API in base64_encode format.
I would like to download that file and save in to file system.
public function import(Request $request) {
if ($request->getMethod() === 'POST') {
$data = json_decode($request->getContent(), TRUE);
$directory = 'public://import/';
// create directory if it does not exist
file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$uri = $directory. $data['name'];
$files_data = preg_replace('#^data:application/\w+;base64,#i', '', $data['data']);
$file_data = base64_decode($files_data);
$file = file_save_data($file_data, $uri, FILE_EXISTS_RENAME);
echo $file->id();
}
}
It goes to below function and gives error, although I have created tmp folder on project root and given needed 777 permission.
/drupal/web/core/includes/file.inc
function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
// Write the data to a temporary file.
$temp_name = drupal_tempnam('temporary://', 'file');
if (file_put_contents($temp_name, $data) === FALSE) {
\Drupal::messenger()->addError(t('The file could not be created.'));
return FALSE;
}
// Move the file to its final destination.
return file_unmanaged_move($temp_name, $destination, $replace);
}
What I am missing? It is not converting and saving file.
Usually this happen because of wrong temporary location and permission, what I suggest you is go to /admin/config/media/file-system and make sure you set Temporary Directory correctly. if its fine. check the permission of it. you need to set it writeable by webservice.
Fixed
On URL : domain.com/admin/config/media/file-system
Temporary directory -> Folder location and permission issue.
I want to edit a .ini using codeigniter.
For Now i can open file edit that file but when i save it the file is saved as a POINTER : RESOURCE ID #5.
I want to create a new file and i am setting a custom name to that file.
But my code create the file but the file is empty and data i want to write is written in POINTER : RESOURCE ID #5.
What should i be doing?
This is my code:
$this->data['parameters'] = parse_ini_file($path.$filename,true);
while (current($this->data['parameters']) )
{
$param_set = current($this->data['parameters']);
$param_type = key($this->data['parameters']);
foreach ($param_set as $key =>$value)
{
$this->data['parameters'][$param_type][$key] = $this->input->post($key);
}
next($this->data['parameters']);
}
$this->load->helper('file');
$this->load->library('ini');
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
/*Want to create a new file*/
$custom_file = fopen('uploads/'.$name.'_'.$ext.'.ini', 'w');
/* $file returns a file pointer which instead should be the file i just created above*/
$file = $path.$custom_file;
$ini = new INI($file);
$ini->write($file, $this->data['parameters']);
So how to write in the file i created instead of pointer file?
My goal is to connect to an FTP account, read the files in a particular folder, grab the content and list out to my screen.
This is what I have:
// set up basic connection
$conn_id = ftp_connect('HOST_ADDRESS');
// login with username and password
$login_result = ftp_login($conn_id, 'USERNAME', 'PASSWORD');
if (!$login_result)
{
exit();
}
// get contents of the current directory
$contents = ftp_nlist($conn_id, "DirectoryName");
$files = [];
foreach ($contents AS $content)
{
$ignoreArray = ['.','..'];
if ( ! in_array( $content , $ignoreArray) )
{
$files[] = $content;
}
}
The above works well to get the file names I need to grab the content from. Next I want to recurse through the filename array and store the content into a variable for further processing.
I am not sure how to do this, I would imagine it would need to be something like this though:
foreach ($files AS $file )
{
$handle = fopen($filename, "r");
$contents = fread($conn_id, filesize($file));
$content[$file] = $contents;
}
The above idea comes from here:
PHP: How do I read a .txt file from FTP server into a variable?
Although I don't like the idea of having to connect each time to grab the file contents, would prefer to do it on the initial instance.
To avoid having to connect/login for every file, use the ftp_get and reuse your connection ID ($conn_id):
foreach ($files as $file)
{
// Full path to a remote file
$remote_path = "DirectoryName/$file";
// Path to a temporary local copy of the remote file
$temp_path = tempnam(sys_get_temp_dir(), "ftp");
// Temporarily download the file
ftp_get($conn_id, $temp_path, $remote_path, FTP_BINARY);
// Read the contents of temporary copy
$contents = file_get_contents($temp_path);
$content[$file] = $contents;
// Discard the temporary copy
unlink($temp_path);
}
(You should add some error checking.)
In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}