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);
Related
I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.
I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices.
The renaming of the old invoice.xml is done with the following code
// rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
rename('invoice.xml','invoice_'.$nowshort.'.xml');
}
The saving is done with the following code:
if($xml1 !='') {
$File = "invoice.xml";
$Handle = fopen($File, 'w');
fwrite($Handle, $xml1);
print "Data Written - ".$nowMysql;
fclose($Handle);
#print $xml;
die();
} else {
print "No new orders - ".$nowMysql;
$File = "no_orders_".$nowshort.".txt";
$Handle = fopen($File, 'w');
fclose($Handle);
die();
}
Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.
Thank you
Just give the path of file 'invoice.xml' to $File.
Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly
Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .
Example if path to your script php something like this:
/var/www/path/to/script.php
$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';
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?
I am trying to upload Excel file using PHP. I am using WAMP server and written PHP code to upload Excel file in the same folder.
I have saved an Excel file so if I upload the saved file then it works fine but if I try to upload another Excel file from different location i.e. from desktop it is showing that abc.xls is not readable.
My code is as follows:
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
require_once 'db.php';
if(isset($_POST["btnImport"]))
{
if(!empty($_FILES["excelFile"]["tmp_name"]))
{
$fileupload = $_FILES["excelFile"]["name"];
$fileName = explode(".",$_FILES["excelFile"]["name"]);
if($fileName[1]=="xls"||$fileName[1]=="xlsx")
{
$data = new Spreadsheet_Excel_Reader($fileupload);
//echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count(#$data->sheets[$i]['cells'])>0) // checking sheet not empty
{
// echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
#$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
#$data->sheets[$i]['cells'][$j][1];
#$ques = mysql_real_escape_string($data->sheets[$i]['cells'][$j][1]);
$opt1 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][2]);
$opt2 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][3]);
$opt3 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][4]);
#$opt4 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][5]);
#$correct = mysql_real_escape_string($data->sheets[$i]['cells'][$j][6]);
#$Level = mysql_real_escape_string($data->sheets[$i]['cells'][$j][7]);
#$Category = mysql_real_escape_string($data->sheets[$i]['cells'][$j][8]);
#$explain = mysql_real_escape_string($data->sheets[$i]['cells'][$j][9]);
$nithi = "INSERT INTO `question` VALUES (NULL,'".$ques."','".$opt1."','".$opt2."','".$opt3."','".$opt4."','".$correct."','".$Level."','".$Category."','".$explain."')";
if (!mysql_query($nithi,$connection))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
}
}
}}}}
if(#$result){
echo "Questions uploaded successfully";
}
?>
How can I upload Excel file from different location?
When a file is uploaded in PHP, it is put into temp folders.
In your code, there is no call for moving the uploaded file from temporary location into the desired one. Instead you are only checking $_FILES["excelFile"]["tmp_name"] and then directly using $_FILES["excelFile"]["name"] which is obviously incorrect.
Use move_uploaded_file() function to move the file, see the docs: http://php.net/move_uploaded_file
I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php
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");
}
?>