CodeIgniter loading doctypes config - php

When I try to load the application/config/doctype.php config file in codeigniter
it gives me the next error
Your application/config/doctypes.php file does not appear to contain a valid configuration array.
My code is (taken from an example at CI docs)
$this->config->load('doctypes', FALSE, TRUE);
$x = $this->config->item('html5','doctypes');
echo "<pre>";var_dump($x);die;//
Anyone knows why?

Regarding to system/helpers/html_helper.php, you can juste use :
include(APPPATH.'config/doctypes.php');
And if you want to understand, look in Config.php core file, row 132 :
include($file_path);
if ( ! isset($config) OR ! is_array($config))
{
if ($fail_gracefully === TRUE)
{
return FALSE;
}
show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.');
}
If you use $this->load->config($file), you must have a $config variable in your file.

The proper way is to load the HTML helper in your controller:
$this->load->helper('html');
Once loaded, one can access the doctypes like so:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<?=doctype('html5');?>
<html lang="en">
<head>
...
From the documentation: http://www-scf.usc.edu/~adportno/apache/htdocs/adportno/hw5/user_guide/helpers/html_helper.html#doctype

Related

How to access the class using include/require using php?

I set up all the basic setup for Codeigniter Framework.
My Code:
controllers/index.php:
include "file_name.php"; //In my case APPPATH . "controllers/user/user_data.php"
controllers/user/file_name.php: //In my case controllers/user/user_data.php
<?php
echo "Welcome";
class File_name
{
function index()
{
echo "this is index";
# code...
}
}
Output:
What I getting:
welcome
What I need:
welcome this is index
My problem is I have file_path instead of file_name in include, so I am unable to create Object for the file.?
In your index.php file:
include "file_name.php";
$file_name_obj = new File_Name();
$file_name_obj->index();
In your file_name.php file change:
function index()
to:
public function index ()
echo "Welcome ";
$fileName = new File_name();
$fileName->index();
if your trying to include a file, be sure to remember that your using a framework, CI. the proper way of including a file using codeigniter is using the "$this->load->view('name of file');" method, because , there are instance that using the include cause an error because it use preferably for pure php style not framework style.

Kohana edit config file dynamically

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();
?>

How to call a function inside yii framework controller from core php file?

I am working in yii framework.I am getting stuck at a point where I have to call a function inside controller in yii framework from core php file. Actually I am going to create html
snapshot.
my folder structure is
seoPravin--
--protected
--modules
--kp
--Dnycontentcategoriescontroller.php
--DnycontentvisitstatController.php
--themes
--start.php (This is my customized file)
--index.php
1) Code of start.php file :--
<!DOCTYPE HTML>
<html>
<head>
<?php
if (!empty($_REQUEST['_escaped_fragment_']))
{
$yii=dirname(__FILE__).'/yii_1.8/framework/yii.php';
require_once($yii);
$escapeFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapeFragment);
include 'protected/components/Controller.php';
include 'protected/modules/'.$arr[0].'/controllers/'.$arr[1].'Controller.php';
echo DnycontentcategoriesController::actiongetDnyContent(); //gettting error at this point
?>
</head>
<body>
<?php
//echo "<br> ".$obj->actiongetDnyContent();
}
?>
</body>
</html>
2) yii side controller function : This function work for normal but when I am calling using escaped_fragment it gives error
public static function actiongetDnyContent()
{
if (!empty($_REQUEST['_escaped_fragment_']))//code inside if statement not working
{
$escapedFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapedFragment);
$contentTitleId=end($arr);
$model = new Dnycontentvisitstat(); //Error got at this line
}
else //Below code is working properly
{
$dependency = new CDbCacheDependency('SELECT MAX(createDateTime) FROM dnycontent');
$content = new Dnycontent();
$content->contentTitleId = $_GET['contentTitleId'];
$content = $content->cache(2592000,$dependency)->getContent();
$userId=105;
$ipAddress=Yii::app()->request->userHostAddress;
echo "{\"contents\":[".CJSON::encode($content)."]} ";
$model = new Dnycontentvisitstat();
$model->save($_GET['contentTitleId'], $userId, $ipAddress);
}
}
error:
Fatal error: Class 'Dnycontentvisitstat' not found in
C:\wamp\www\seoPravin\protected\modules\KnowledgePortal\controllers\DnycontentcategoriesController.php
on line 289
code is working for normal url but not working for _esaped_fragment
It is a very bad practice but you can do a HTTP self request, like this:
include("http://{$_SERVER['HTTP_HOST']}/path/?r=controller/action&_param={$_GET['param']}");
Check http://www.php.net/manual/en/function.include.php to see how to enable HTTP includes.

Best way for scripts in codeigniter

In CodeIgniter I often have many scripts inherent to my project, for instance:
<?php
// Load many things
$this->load->model('news_model');
$this->load->helper('utility_helper');
$news = $this->news_model->get_basic_news();
// For moment no news
$view_datas['news']['check'] = false;
if ($news) {
$view_datas['news'] = array(
'check' => true,
'news' => _humanize_news($news)
);
}
?>
This script is used in different controllers, at the moment I create a scripts folder and I import it like that: include(APPPATH . 'scripts/last_news.php'); I'm quite sure it's not the best way to handle this problem. Any thoughts on that?
Update:
A solution given in the answers is to use a helper or a library.
Let's imagine a rewrite of my previous code:
class Scripts {
public function last_news() {
// Load many things to use
$CI =& get_instance();
$CI->load->model('news_model');
$CI->load->model('utility_helper');
$news = $CI->news_model->get_basic_news();
// Avoid the rest of code
}
}
Just create a new library and load that library whereever you require?
e.g.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Newclass {
public function get_news($limit)
{
//return news
}
}
/* End of file Newsclass.php */
In your controllers
$this->load->library('newsclass');
$this->newsclass->get_news($limit);
Or another idea is to create helper functions.

CodeIgniter, including code from one view into another?

I have an interesting problem. I currently have a basic template library that renders out a bunch of modules for header and footer templates, then sandwiches a view I specify in between them.
Example:
$this->load->view('header.php', $headerstuff);
$this->load->view($contentView);
$this->load->view('footer.php', $footerstuff);
The problem is that I need to put some javascript (that is specific to each content view) into the header. I have been doing this with a switch statement containing the js inside the template library. But that makes no sense in the mvc model.
Example (of what I've been doing), (in template library, above previous code):
$headerstuff['js'] = '';
switch ($contentView)
{
case 'main':
$headerstuff['js'] = 'JAVASCRIPT INCLUDE CODE 1';
break;
case 'product':
$headerstuff['js'] = 'JAVASCRIPT INCLUDE CODE 2';
break;
}
I can't think of another way to do this though. I would like to (ideally) store the js in a variable inside the content view file, and (somehow) load that into the header view. To be honest though, I don't even think that is possible.
Does anybody have a better way of doing this then my current solution?
Thanks,
Max
I created a helper file to do this for my sites and I think we have a similar MVC template layout:
Asset Helper:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('css'))
{
function css($array) {
// If the object passed is a string, convert it into an array
if ( is_string($array) ) {
$array = explode(" ", $array);
}
// Add additional CSS Files
if ( isset($array) ) {
foreach ( $array as $i => $file ) {
// If it's not the first one add a tab character.
if ( $i > 0 ) echo "\t";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"". $file ."\">\n";
}
}
}
}
if ( ! function_exists('js'))
{
function js($array) {
// If the object passed is a string, convert it into an array
if ( is_string($array) ) {
$array = explode(" ", $array);
}
// Add additional JavaScript Files
if ( isset($array) ) {
foreach ( $array as $i => $file ) {
// If it's not the first one add a tab character.
if ( $i > 0 ) echo "\t";
echo "<script src=\"". $file ."\"></script>\n";
}
}
}
}
This does one of two things. I will allow you to add files in the controller file which is nice. I do this by creating a data object:
$data['css'] = array('/path/to/styles.css', '/path/to/otherstuff.css');
$data['js'] = array('/path/to/javascript.js');
Then in your header include do the following:
<?
$defaultCSS = array("/assets/css/global.css");
$css = (isset($css)) ? array_merge($defaultCSS, $css) : $defaultCSS;
css($css);
$defaultJS = array("/assets/js/global.js");
$js = (isset($js)) ? array_merge($defaultJS, $js) : $defaultJS;
js($js);
?>
I'm settings some defaults that will load on each page and then I can add in different files based on which controller I'm loading.
Hope this helps.
How about having a scripts controller which acts as a small proxy:
/**
* A basic controller which allows for the display of basic views.
*/
class Scripts extends CI_Controller
{
public function _remap( $meth, array $params )
{
// ensure that parent directory contents can't be revealed.
if( !$meth || strpos( $meth, '.' ) !== FALSE ) show_404();
foreach( $params as $arg )
// I put all css in a folder called css all js goes into
// a folder called js. It can be overly simple, but it works
// (if you need these files to be php files, just add '.php'
// to the end of the FILE's name. No need to worry about that
// here, CodeIgniter's got your back...)
$this->load->view( "$meth/${params}.$meth" );
}
}
How to use:
For each controller (or, you could easily modify this to be for every method), have an appropriate js file in your views/js folder. Name each after the respective controller. Then, point to each of them from the view:
Then, in the header view:
<script type="text/javascript" src="
<?php
// honestly, I normally use a helper function here, but this is the
// short... short version.
echo base_url() . '/scripts/js/' . load_class('Router')->fetch_class();
// You can also replace the controller name with the view name by using the
// variable $_ci_view, you can get the full path with $_ci_path
?>" ></script>
Best part? Your controller is agnostic about the contents of the view. The view is more or less agnostic of the controller (it is a variable populated ahead of time from an external source and just... there). In fact, the only things which "need to know" are the JS/CSS files and they were on a case by case configuration anyway.

Categories