I have code I'm using to create a file using the name of one field, then opening that file and writing the contents from another. That works fine.
However when users attempt to pull up this file and change information and save it it doesn't overwrite the information.
If a user deletes the file (which works) then recreates it using the same name, but attempts to input new data, it creates the new file (with the same name as the old file) however it retains the old information and doesn't update. I can't find out what's causing that.
I was originally using file_put_contents and I've attempted to use different parameters for the fopen() but it doesn't seem to work. They can create and save just fine, however the main issues are they can't edit as it doesn't overwrite data and they can't delete the file (even as a workaround) and recreate it using the same name.
edited to add: Also when they try and save information, instead of opening the file and overwriting it, it creates a second and NEW file filename.html.html
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.html';
$CODE = $_POST['Code'];
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
$fp = fopen($FILENAME, "w+") or die("Couldn't open $FILENAME for
writing!");
fwrite($fp, $CODE) or die("Couldn't write values to file!");
endif;
header('Location: mywebsite.comsaved=1&file='.$FILENAME);
}
?>
A quick hack might be to try this:
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.html';
$CODE = $_POST['Code'];
//Delete file if exists.
if(is_file( $FILENAME)) {
unlink($FILENAME);
}
// Open the text file, write the contents, and close it.
$fp = fopen($FILENAME, "w+") or die("Couldn't open $FILENAME for
writing!");
fwrite($fp, $CODE) or die("Couldn't write values to file!");
header('Location: mywebsite.comsaved=1&file='.$FILENAME);
}
I'm very new to php and so far in everything I have wanted to do I have been able to search the web for a solution. And after hours of reading what I could find and still not being able to figure it out I come to you..
Here is what I'm doing I'm creating a form where someone can upload some information and then that information populates in to an inventory page as long as well as there own page, and create a more in depth full page for each submission based on a template. All form information is stored in a mysql database.
I have gotten all if to work except the last piece. I'm trying to use fwrite to do this. I'll post what I have for that section. I do know that I'm missing some major steps here. Any guidance or a point in the right direction would be nice.
Thanks!
<?php
// For use in creating individual page
$tpl_file = "properties.php"; // template
$tpl_path = "pages/"; // where template is stored
$submissions_path = "new-pages/"; // where new file will be stored
$fp = fopen($submissions_path, "w");
fwrite($fp, $tpl_file);
fclose($fp);
?>
You're opening a directory using a file operation, which will not work. fopen() works on FILES, not directories.
Most likely what you're after is
$path = $submissions_path . $tpl_path . $tpl_file;
$fp = fopen($path, 'w') or die("Failed open $path for writing");
Note the added or die() business - it is always a good idea to verify that a file system operation succeeded (or failed) before you proceed. Assuming success will bite you in the rump at some point.
I need to read a list of CSV files from an FTP and delete them after I successfully read them.
Until now, i opened the csv file using fopen into a resource and then used fgetcsv to read the csv lines from it.
$res = fopen($url);
while ($csv_row = fgetcsv($res, null, self::DELIMITER)) {
.....
}
The problem is that I need to read a list of csv files and delete them too. the ftp_get function save the file into a local file. I rather avoid that. any way I can keep using the fgetcsv function with the ftp_nlist & ftp_connect functions? ?
You can save the csv file to a temporary file stream using ftp_fget(). This allows you to avoid the "create-read-delete" cycle. Once you close the file stream it's like it magically never existed :)
$ftp_handle = ftp_connect($ftp_server);
$remote_path = "/path/to/file.csv";
$tmp_handle = fopen('php://temp', 'r+');
if (ftp_fget($ftp_handle, $tmp_handle, $remote_path, FTP_ASCII)) {
rewind($tmp_handle);
while ($csv_row = fgetcsv($tmp_handle)) {
// do stuff
}
}
fclose($tmp_handle);
If you wanted to loop over a directory of files just get the list of files and then put the above code in a loop.
When i upload a excel file, i have used COM() to open and automate converting it to xml.
It works fine, But when i run it, it always shows the message from Microsoft Excel:
A file named ''' already exists in this location. Do you want to replace it?
I can choose between Yes No and Cancel.
normally i would choose Yes. But i dont want users to click on Yes each time.
Can i disable this?
Please inform me if any relevant codes need to be posted.
Thanks
UPDATE Here's part of my code using unlink().
$workbook = $_FILES['file']['tmp_name']
$sheet = "Sheet1";
$ext = substr($workbook, strrpos($workbook, '.') + 1);
$ex = new COM("Excel.sheet") or die("Did not connect");
//Open the workbook that we want to use.
$wkb = $ex->application->Workbooks->Open($workbook) or die("Did not open");
$path = "D:\b2\\test1.xml";
$format = 46;
unlink($path);
$path = "D:\b2\\test1.xml";
//Create a copy of the workbook, so the original workbook will be preserved.
$ex->Application->ActiveWorkbook->SaveAs($path, $format);
Is it the right way to use it? Because it does not seem to work
If you're always going to overwrite, the simplest way is probably just to delete the file first before you get Excel to open it. The PHP function to delete a file is unlink()
I solved it by adding this line.
$ex->application->displayAlerts = 0;
I have a config.inc file in a web application that I am building. It contains an array with configuration values for things like the MySQL database, etc. I would like these to be entered by using a simple form, that asks for the server, login/password for the database, etc, then these get written to the configuration file.
Is there a preferred method of doing this? I am not sure how to write to a file, and update an array.
You just want writing, correct? Is it a serialized array or is it parsed?
One way to read a config file is parse_ini_file(). I wouldn't necessarily call it preferred, but it's a method. You'd still need to write the file.
Another way would to write a "config.inc.php" and just include it in, to write it you'd just output actual PHP code (e.g. $var = "myval";).
This is a way you could write a simple "output" function that took an array of configuration values and output them as name=value, assuming $config was an associative array.
foreach ($config as $name => $value) {
$output .= $name . '=' . $value . "\n";
}
if (!file_put_contents($filename, $output)) {
die("Error writing config file.");
}
There's a lot of decent ways to do it. It's really based on your requirements. Does it need to be in a specific format or do you have leeway?
It is not recommended to modify PHP configuration files via your application, you should use CSV files or a database table.
In case you want to save it in a CSV file then I suggest you keep a CSV file for each configuration type (e.g CSV file for database configurations) and always overwrite the previous one using file_put_contents
Save data example:
$csvStructure = array("dbUser","dbPassword","dbHostname","dbPort"); // array used for both loading data and saving it
$csvData = array();
foreach ($csvStructure as $field) {
$csvData[] = $_POST[$field]; // so it'd get $_POST["dbUser"],$_POST["dbPasword"], etc..
}
file_put_contents("filename",implode("\t",$csvData));
Load data example:
$csvStructure = array("dbUser","dbPassword","dbHostname","dbPort"); // array used for both loading data and saving it
$dbConfig = array();
$csvData = explode("\t",file_get_contents("filename"));
foreach ($csvStructure as $key => $field) { // $key would have the location of the requested field in our CSV data (0,1,2, etc..).
$dbConfig[$field] = $csvData[$key]; // populate $dbConfig["dbUser"],$dbConfig["dbPasword"], etc..
}
I believe using an ini file is a wise option, because user, password, schema, paths, etc. are things that usually will be modified by hand, so using var_export isn't because modifying it by hand it's not so clean and may crash your application if you make a mistake in the PHP syntax.
But parsing big ini files can be expensive, so it would be OK to cache the ini with var_export() or serlialize(). It's a better choice, I think, and read the ini only when the cache file doesn't exists.
PHP has a dedicated function for this, its called var_export();
Just do:
file_put_contents("config.php",var_export($config,true));
Well, to write a file, fwrite() php function does exactly what you want. From its PHP.NET documentation page (see example below).
Now, on the question as to what to output to that file - I'm assuming that file will have to be included as a configuration .php file into the rest of the project. I'm imagining you'll do something like this - where you're creating strings with PHP code on the fly, based on the submitted form:
$strDatabaseConfig = "\$databaseConfig = array('" . $_POST['login'] . "," . $_POST['password'] . "');";
And here's the snippet for fwrite:
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
Here's one way: wp-admin/setup-config.php from WordPress.
I prefer to have a file with a bunch of define statements.
These are constants globally available (and of course immutable) which is what you need for configuration settings.
Constants offer better memory management and efficiency in reading as they don't need the extra memory required by a variable so that it can be changed.
Let's say your config.inc file looks like this:
$config = array(
'blah' => 'mmm',
'blah2' => 'www',
//...
);
You want to update it, so you create a simple form, fill text fields with current values. PHP script that overwrites current configuration could looks like this:
$newConfig = ...; // data from form - of course validate it first
$config = ...; // data from config.inc
$config = array_merge($config, $newConfig);
file_put_contents('config.inc', '<?php $config = ' . var_export($config, true));
And you're done.