Open a file then edit and save file using codeigniter - php

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?

Related

PHPExcel xlsx file into array ....Reader_Exception: Could not open

1.8.0"
the goal of my web application is to have a button that the user clicks on.
The code behind will start to scan all the folders that are in the main rdv folder.
in the rdv folder it contains three folders named 1000, 1001, 1002 these contain .xlsx files.
retrieves the last file .xlsx saved in each of the folders
but after that it doesn't work.
Fatal error: Uncaught PHPExcel_Reader_Exception: Could not open 2.xlsx
for reading!
so how i can fix the fatal error and how is possible to read the file to continue the code, i want to get 3 values in the .xlsx file and insert into my database.
thank you for your time.
include 'database.php';
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
// receives the 'someAction' value from the index page button.
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
//calcul the nomber of folder in folder rdv
$howManyFolder = count(glob('rdv/*', GLOB_ONLYDIR));
//retrieves the last file saved in each of the folders and insert into database
for ($i = 0; $i < $howManyFolder; $i++) {
$files = scandir("rdv/100$i", SCANDIR_SORT_DESCENDING);
echo "Recover all files in the folder 100" . $i . "<br>";
print_r($files ); echo "<br>";
echo "get the last file inserted in the folder at index 0 <br>";
$newest_file = $files[0]; print_r($newest_file); echo "<br>";
//load the file .xlsx (but the code bug here -_-)
$objExcel=PHPExcel_IOFactory::load($newest_file);
//get all value insinde the .xlsx file
$dossier = $objExcel->getActiveSheet()->getCell('A3')->getValue();
$facture = $objExcel->getActiveSheet()->getCell('B21')->getValue();
$date = $objExcel->getActiveSheet()->getCell('Q1')->getValue();
//call function to insert these values inside dataBase.
insertInto($dossier, $facture, $date );
}
}
XML Parser:
https://www.php.net/manual/en/book.xml.php
Parsing an XML document: https://www.php.net/manual/en/function.xml-parse.php
<?PHP
$stream = fopen('large.xml', 'r');
$parser = xml_parser_create();
// set up the handlers here
while (($data = fread($stream, 16384))) {
xml_parse($parser, $data); // parse the current chunk
}
xml_parse($parser, '', true); // finalize parsing
xml_parser_free($parser);
fclose($stream);

Moving files after inserting them into Database

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");
}

Cakephp how to browse file?

my question is how to get the content of a file from a input file
becausethe only thing im getting is the name of the file not the
full path of the file.
$handle = file_get_contents($this->data['btnBrowse']);
$absolute = basename($this->data['btnBrowse']);
var_dump($handle);
var_dump($absolute);
This should work:
$file = new File($dir);
$contents = $file->read();
$file->close();

Drupal: Save a file from filesystem

I want to save a file, that I have created in the temp directory, into drupal. But file_save requests a file object but I have just the real path.
$imageId =file_save('/tmp/proj/media/cover.jpg']);
I think you're looking for the file_save_data function, or possibly file_unmanaged_save_data, instead of file_save().
file_save(stdClass $file) save a file object. You are trying to download a file.
You can do as
$file = '/tmp/proj/media/cover.jpg';
// Get the file size
$details = stat($file);
$filesize = $details['size'];
// Get the path to your Drupal site's files directory
$dest = file_directory_path();
// Copy the file to the Drupal files directory
if(!file_copy($file, $dest)) {
echo "Failed to move file: $file.\n";
return;
} else {
// file_move might change the name of the file
$name = basename($file);
}
// Build the file object
$file_obj = new stdClass();
$file_obj->filename = $name;
$file_obj->filepath = $file;
$file_obj->filemime = file_get_mimetype($name);
$file_obj->filesize = $filesize;
$file_obj->filesource = $name;
// You can change this to the UID you want
$file_obj->uid = 1;
$file_obj->status = FILE_STATUS_TEMPORARY;
$file_obj->timestamp = time();
$file_obj->list = 1;
$file_obj->new = true;
// Save file to files table
drupal_write_record('files', $file_obj);
I hope this will help you.

For loop over named folder to read each .txt filename and contents

The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>

Categories