I would like to know if we can edit dynamically the config file.
Here is my example.
<?php
// config/system.php
return array(
'data'=>"content",
'data1' => "content2",
);
?>
I know that we can edit it by using the set() methode, but this methode doesn't edit the file.
example :
<?php
// get config file array
$config = Kohana::$config->load('system');
// set the new config .. but this function doesn't edit the file !
$config->set("data","MyContent");
?>
Any idea ?
Finally i did it myself, maybe this can help someone else too.
1 - Create APPPATH.'config/Group.php' and put this script.
<?php defined('SYSPATH') OR die('No direct script access.');
// Save this file at APPPATH.'config/Group.php'
// Extend the original Config_group
class Config_Group extends Kohana_Config_Group {
// This function allow us to save on the config file
public function save()
{
$filename = APPPATH.'config'.DIRECTORY_SEPARATOR.$this->group_name().".php";
// test if the config file is writable or not.
if (is_writable($filename))
{
// save the array into the config file and return true/false
return (file_put_contents($filename, "<?php defined('SYSPATH') or die('No direct script access.');".PHP_EOL
."return " . var_export($this->as_array(), true) . ";",LOCK_EX));
}
return FALSE;
}
}
How to use :
<?php
// get config file array
$config = Kohana::$config->load('system');
// set the new config .. but this function doesn't edit the file !
$config->set("data","MyContent");
// Save the new file config.
$config->save();
?>
Related
I want to write a class and save it into application/models/ folder.
The code is as below:-
function writeANewFile()
{
$path = "/LMSV1/application/models/";
$classname = "firstidgenerator";
$this->load->helper('file');
$data = "<?php class ".$classname." extends CI_Model {
function generateId(\$db)
{
\$data['orders'] = 'orders';
\$this->\$db->trans_start();
\$this->\$db->insert('$classname', \$data);
\$insert_id = \$this->\$db->insert_id();
\$this->\$db->trans_complete();
return \$insert_id;
}
} ";
$result = write_file(''.$path.''.$classname.'.php', $data);
echo json_encode($result);
} //end fucntion
If i give the $path = "c:/xampp/htdocs/FrameWorks/LMSV1/application/models/"; then it successfully saves a file in desired folder.
But if if i give $path = "/LMSV1/application/models/"; then it returns false and does not create a file.
The problem lies in setting path and i could not successfully figure out what should be the path to be given as parameter?
Codeigniter has a few path constants that are useful in this case. The constant APPPATH is what you need.
$path = APPPATH . "models/";
This is how I include files in the index.php now:
<?php include('class.register.php');?>
<!--additional files starts-->
<?php include('register/register-form.php');?>
<?php include('register/browse.php');?>
<?php include('register/alldone.php');?>
<?php include('search/browse.php');?>
<?php include('search/mobile-left-column.php');?>
<?php include('profile/mygloopal.php');?>
<?php include('profile/profile.php');?>
<?php include('profile/details.php');?>
<?php include('profile/posts.php');?>
<?php include('profile/create_post.php');?>
<?php include('profile/browse-search.php');?>
<?php include('profile/review.php');?>
<?php include('how.php');?>
<?php include('search/more-options.php');?>
I'm referring to this tutorial to study autoload with namespaces:
http://www.zainabed.com/2014/11/php-tutorials-autoload-php-classes.html
But it uses classname to define a page. For my case above, no class required to include the files. How do I go about it, please?
The question is a bit unclear, so I will answer it as I understand it. If the files you have labelled as <!--additional files starts--> are not classes, or are classes but are not named whereby spl_autoload_register() is an option, I generally make a function or class to auto-include files for me. Here is just an example. It is indiscriminate, meaning it will load everything in the folder but you could pass a second param that is an array that tells it specifically what to load:
class AutoloadFiles
{
public function fInclude($dir = false)
{
// If the directory does not exist, just skip it
if(!is_dir($dir))
return $this;
// Scan the folder you want to include files from
$files = scandir($dir);
// If there are no files, just return
if(empty($files))
return false;
// Loop through the files found
foreach($files as $file) {
// Include the directory
$include = str_replace("//","/","{$dir}/{$file}");
// If the file is a php document, include it
if(is_file($include) && preg_match('/.*\.php$/',$include))
include_once($include);
}
// Return the method just so you can chain it.
return $this;
}
}
To use:
$iEngine = new AutoloadFiles();
$iEngine ->fInclude(__DIR__)
->fInclude(__DIR__.'/classes/')
->fInclude(__DIR__.'/functions/');
I'm currently making a PHP script and I need some help. Firstly it allows the user to enter database information on a file called install.html which presents a form to the user. The form uses GET to then send that information to a second install file which creates the relevant tables, enters the information into the tables and then allows the user to carry on with the script.
However I was wondering. In the second install file I used:
$databaseServer = $_GET["databaseServer"];
in order to get the information that was entered into the form. Is there anyway I can then send these variables ($databaseServer, $databaseName, $databaseUser, $databasePassword) to another file called db.php that I will include on top of every file I write that requires an SQL connection. I have looked at GLOBAL variables but they didn't work properly. I could have been doing something wrong however.
You could save a configuration array to a file:
<?php
class Config
{
public $path;
public function __construct($path)
{
$this->path = $path;
}
public function store($config)
{
$dump = var_export($config, true);
$dump = '<?php return ' . $dump . ';';
file_put_contents($this->path, $dump);
}
public function retrieve()
{
return include $this->path;
}
}
// Build your config array
$config['database'] = $_GET['database'];
$config['username'] = $_GET['username'];
// Make sure your server can write to this path
$configurator = new Config(__DIR__ . '/config/config.php');
// Save your config
$configurator->store($config);
// Get your config later
$read_config = $configurator->retrieve();
// Check our config against the saved version
assert($config == $read_config);
var_dump($read_config);
I have almost successfully setup a Cron job on my server, but I cannot call the correct controller.
When I remove the CLI only if statement I can successfully run the script from my browser.
// Make sure the request is being made by a CRON Job
if ( ! $this->input->is_cli_request()) exit('Only CLI access allowed');
I am having the output being emailed by the Cron Daemon. I have tried this command and following is my results.
job :
/usr/bin/php /home/dlp/public_html/abc.org/index.php birthday
Result :
I get the 2 emails in 1st email HTML output of the default controller index.php and in 2nd email output of birthdady controller.
code of my controller is.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Birthday extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->library('email');
}
/**** function for sending news letter on birthday ****/
function index()
{
error_log("birthday function call",1,"abc#gmail.com");
exit;
}
}
?>
I am not sure what I am doing wrong.
Thanks in advance for the help.
You are writing only controller name in cronjob but you should write method name also when the method is index. So in your case you write birthday/index in your cronjob.
OR
Create cron.php config file in application/config with data as:
$config['CRON_TIME_LIMIT']=0;
$config['argv'] =array(1 => 'birthday');
$config['CRON_BETA_MODE']=false;
Create cron.php at root parrallel to application folder containing data as
//!/usr/bin/php
<?php
define('CRON', TRUE);
// Load CRON config
require('/home/dlp/public_html/abc.org/application/config/cron.php');
// Set CRON mode ( live or beta )
define('CRON_BETA_MODE', $config['CRON_BETA_MODE']);
// Set index.php location
if (isset($config['CRON_CI_INDEX']) && $config['CRON_CI_INDEX'])
define('CRON_CI_INDEX', $config['CRON_CI_INDEX']);
else
define('CRON_CI_INDEX', '/home/dlp/public_html/abc.org/index.php');
if (count($argv) < 2)
if (count($config['argv'])) {
$argv = array_merge($argv, $config['argv']);
$_SERVER['argv'] = $argv;
} else
die('Use: php cron.php controller/method');
// Simulate an HTTP request
$_SERVER['PATH_INFO'] = $argv[1];
$_SERVER['REQUEST_URI'] = $argv[1];
//$_SERVER['SERVER_NAME'] = $config['SERVER_NAME'];
// Set run time limit
set_time_limit($config['CRON_TIME_LIMIT']);
// Run CI and capture the output
ob_start();
chdir(dirname(CRON_CI_INDEX));
// echo "== ".CRON_CI_INDEX; die;
require( CRON_CI_INDEX ); // main CI index.php file
$output = ob_get_contents();
if (CRON_FLUSH_BUFFERS === TRUE)
while (#ob_end_flush()); // display buffer contents
else
ob_end_clean();
echo "\n";
?>
Run cron the file as php
/home/dlp/public_html/abc.org/cron.php
I am using Zend Framework 1.9.6. I think I've got it pretty much figured out except for the end. This is what I have so far:
Form:
<?php
class Default_Form_UploadFile extends Zend_Form
{
public function init()
{
$this->setAttrib('enctype', 'multipart/form-data');
$this->setMethod('post');
$description = new Zend_Form_Element_Text('description');
$description->setLabel('Description')
->setRequired(true)
->addValidator('NotEmpty');
$this->addElement($description);
$file = new Zend_Form_Element_File('file');
$file->setLabel('File to upload:')
->setRequired(true)
->addValidator('NotEmpty')
->addValidator('Count', false, 1);
$this->addElement($file);
$this->addElement('submit', 'submit', array(
'label' => 'Upload',
'ignore' => true
));
}
}
Controller:
public function uploadfileAction()
{
$form = new Default_Form_UploadFile();
$form->setAction($this->view->url());
$request = $this->getRequest();
if (!$request->isPost()) {
$this->view->form = $form;
return;
}
if (!$form->isValid($request->getPost())) {
$this->view->form = $form;
return;
}
try {
$form->file->receive();
//upload complete!
//...what now?
$location = $form->file->getFileName();
var_dump($form->file->getFileInfo());
} catch (Exception $exception) {
//error uploading file
$this->view->form = $form;
}
}
Now what do I do with the file? It has been uploaded to my /tmp directory by default. Obviously that's not where I want to keep it. I want users of my application to be able to download it. So, I'm thinking that means I need to move the uploaded file to the public directory of my application and store the file name in the database so I can display it as a url.
Or set this as the upload directory in the first place (though I was running into errors while trying to do that earlier).
Have you worked with uploaded files before? What is the next step I should take?
Solution:
I decided to put the uploaded files into data/uploads (which is a sym link to a directory outside of my application, in order to make it accessible to all versions of my application).
# /public/index.php
# Define path to uploads directory
defined('APPLICATION_UPLOADS_DIR')
|| define('APPLICATION_UPLOADS_DIR', realpath(dirname(__FILE__) . '/../data/uploads'));
# /application/forms/UploadFile.php
# Set the file destination on the element in the form
$file = new Zend_Form_Element_File('file');
$file->setDestination(APPLICATION_UPLOADS_DIR);
# /application/controllers/MyController.php
# After the form has been validated...
# Rename the file to something unique so it cannot be overwritten with a file of the same name
$originalFilename = pathinfo($form->file->getFileName());
$newFilename = 'file-' . uniqid() . '.' . $originalFilename['extension'];
$form->file->addFilter('Rename', $newFilename);
try {
$form->file->receive();
//upload complete!
# Save a display filename (the original) and the actual filename, so it can be retrieved later
$file = new Default_Model_File();
$file->setDisplayFilename($originalFilename['basename'])
->setActualFilename($newFilename)
->setMimeType($form->file->getMimeType())
->setDescription($form->description->getValue());
$file->save();
} catch (Exception $e) {
//error
}
By default, files are uploaded to the system temporary directory, which means you'll to either :
use move_uploaded_file to move the files somewhere else,
or configure the directory to which Zend Framework should move the files ; your form element should have a setDestination method that can be used for that.
For the second point, there is an example in the manual :
$element = new Zend_Form_Element_File('foo');
$element->setLabel('Upload an image:')
->setDestination('/var/www/upload')
->setValueDisabled(true);
(But read that page : there are other usefull informations)
If you were to move the file to a public directory, anyone would be able to send a link to that file to anyone else and you have no control over who has access to the file.
Instead, you could store the file in the DB as a longblob and then use the Zend Framework to provide users access the file through a controller/action. This would let you wrap your own authentication and user permission logic around access to the files.
You'll need to get the file from the /tmp directory in order to save it to the db:
// I think you get the file name and path like this:
$data = $form->getValues(); // this makes it so you don't have to call receive()
$fileName = $data->file->tmp_name; // includes path
$file = file_get_contents($fileName);
// now save it to the database. you can get the mime type and other
// data about the file from $data->file. Debug or dump $data to see
// what else is in there
Your action in the controller for viewing would have your authorization logic and then load the row from the db:
// is user allowed to continue?
if (!AuthenticationUtil::isAllowed()) {
$this->_redirect("/error");
}
// load from db
$fileRow = FileUtil::getFileFromDb($id); // don't know what your db implementation is
$this->view->fileName = $fileRow->name;
$this->view->fileNameSuffix = $fileRow->suffix;
$this->view->fileMimeType = $fileRow->mime_type;
$this->view->file = $fileRow->file;
Then in the view:
<?php
header("Content-Disposition: attachment; filename=".$this->fileName.".".$this->fileNameSuffix);
header('Content-type: ".$this->fileMimeType."');
echo $this->file;
?>
$this->setAction('/example/upload')->setEnctype('multipart/form-data');
$photo = new Zend_Form_Element_File('photo');
$photo->setLabel('Photo:')->setDestination(APPLICATION_PATH ."/../public/tmp/upload");
$this->addElement($photo);