Write on YAML file using php in codeigniter Framework - php

I'm using YAML library with codeIgniter and I was adding data manually but now I decided I need to add it automatically and I'm asking how to add a line at the end of a .YML file?
Clarification:
when I insert some data in the database in the same time I need to store some of it in the YML file ( for other use )
no the data is inserted successfully in the database but it doesn't in the YML file (it always return Unable to write the file) after I tried to use this method which I thought it's gonna work:
$title = $title-en.' :'.$title-fr;
$this->load->helper('file');
$msg = "non";
if (!write_file(base_url().'assets/data/data.yml',$title, 'a+')){
$msg = 'Unable to write the file';
}else{
$msg = 'File written!';
}
echo $msg;

You cannot write to a file using a URL ie http://www.domainname.com/assets/data/data.yml
You need to use a PATH. ie
if (!write_file('.assets/data/data.yml', $title, 'a+')) {
...
}
So if you use the correct path and the file has it's permissions set to writeable, that should help.

Related

Where am I doing wrong in downloading a file with '.CSV' format in CodeIgniter's controller?

I am new to CodeIgniter and was working on downloading a file. However, I want to download a file that resides on my local machine, I am able to locate the file by providing the path, also the file gets downloaded with a File type, However, I want my file to be in .csv format
Here goes my Controller's download function:
public function download()
{
$state_id=$this->input->post('state'); // gets me the state-id from viw's dropdown
$this->load->helper('download'); // Load download helper
$file="C:\\Users\usernew\\Desktop\\New folder\\".$state_id.".csv";
$filename=$state_id.'.csv';
if (file_exists($file))
{
$data = file_get_contents($file); //check file exists
force_download($fileName,$data);
}
else{
echo"not working!";
}
}
Where am I going wrong?
As the force_download() function accepts the file name to be set and the data to insert into that file, as you have the data in that file already, you just need to download it. so, You should use the for_download() function like this:
force_download($file,NULL);
This will solve your problem :)

Laravel 5.5 read a file from the local disk

I am trying to import a csv file with Laravel 5.5 from the local file location. For some reason it can't find the file on my computer however the path is correct.
$fileLocation = $request->file('file')->store('csv');
$importFile = File::file(storage_path('app/' . $fileLocation));
You can use the Storage facade for this. Here is an example:
if (Storage::disk($disk)->exists($filename)) {
return Storage::disk($disk)->get($filename);
}
throw new FileNotFoundException(sprintf('File not found: %s', $filename), 404);
If you don't wanna use Storage facade, you can use below code to get the file
$importFile = Illuminate\Support\Facades\File::get(storage_path('app/' . $fileLocation));
but when you store a file with csv as store argument, it will save in storage/csv folder, and you just need call storage_path($fileLocation).
be sure that your storage path is correct and for more information read here

saving a file in php without saving in a folder in yii php

Am saving a file as a long blob in php by first saving it in a folder then to a db, the problem is that the server has write permissions so i would like to save it directly
This is what i have tried (This works perfectly):
if(isset($_POST['image'])){
$id = 0;
$image = $_POST['image'];
$tmp_image = date('YmdHisu').'.jpg';
file_put_contents($tmp_image, base64_decode($image));
$sql = "INSERT INTO fingerprint(template)
VALUES ('".addslashes(file_get_contents($tmp_image))."')";
try
{
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$rowCount=$command->execute(); // execute the non-query SQL
echo "saved successifully";
unlink($tmp_image);
}
catch(Exception $ex)
{
echo 'Query failed' , $ex->getMessage();
unlink($tmp_image);
}
}
How can i save this in a blob field in mysql without first having to save it in a folder then saving to db
Let's assume you've sent the file via Android using POST method to your server running Yii1.
First of all the physical file is contained in the $_FILES variable and in the $_POST variable, as you said, contains a string of the file encoded in base 64 format (i write this for a clear answer).
$_FILE DOCUMENTATION
Now this is how you can try to upload the file with the standard MVC yii way using yii code:
It's true that you're uploading your file from an external device but Yii came in your help with CUploadedFile Class:
Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name, tempName, type, size and error.
In particular you should use the function getInstancesByName that returns an array of instances starting with specified array name.
$temp = CUploadedFile::getInstanceByName("image"); // $_FILES['image']
and with this you can access to the file data:
$temp->name; // Name of the file
$temp->type; // Type of the file
$temp->size; // Size of the file
// etc etc..
$temp->saveAs("/your/path/" . $tmp_image . $temp->type); // Save your file
for final you can check if the file was saved and execute your query:
if($temp->saveAs("/your/path/" . $tmp_image . $temp->type)) {
// File is saved you can execute the query for save the record in your db
} else {
// Something went wrong.
}
You can also transfer this logic in a model.
check this link for more infos
Hope this will help you.

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

PHP: Is there a correct method for saving configuration data?

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.

Categories