I am a newbie in codeigniter and I am not the first web developer of the project however I discovered in views folder it has template.php which loads in all pages. how can i override the metadata of the header inside views folder which loads the header of the template.php? I wan it to have different metadata.
Here's the code of Template.php
<title>I Sold My Business - Your one-stop shop for online business brokerage</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="description" content="Whether you’re an entrepreneur trying to buy a business online or a broker who wants to sell businesses, I Sold My Business is here to help you. Visit us today!">
<meta name="keywords" content="sold business online, buy business online, sell business online">
<?php echo #$template['framework']; ?>
<?php echo #$template['bootstrap']; ?>
<?php echo #$template['head']; ?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('templates/site/reconvert_style.css'); ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url('templates/site/stylesheet.css'); ?>" />
<script type='text/javascript'>
(function (d, t) {
var bh = d.createElement(t), s = d.getElementsByTagName(t)[0];
bh.type = 'text/javascript';
bh.src = '//www.bugherd.com/sidebarv2.js?apikey=rkdoxsrzmxvrsrt6ailjsa';
s.parentNode.insertBefore(bh, s);
})(document, 'script');
</script>
Here's the code inside controllers folder home.php
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('business_category_model');
$this->load->model('franchise_category_model');
$this->load->model('account_model');
$this->load->model('country_model');
}
public function index()
{
$template = array();
$template['title'] = "Home";
$this->load->model(array('business_listing_model', 'featured_business_model', 'franchise_model'));
$this->load->helper('text');
$page = array();
$page['countries'] = $this->country_model->get_all();
$featured_businesses = $this->featured_business_model->random(3);
$featured_count = 0;
foreach($featured_businesses->result() as $index => $featured_business)
{
if($featured_business->type == 'business' || $featured_business->type == 'video')
{
$page['featured_businesses'][$featured_count] = (array) $this->business_listing_model->get_one($featured_business->business_id);
}
else
{
$page['featured_businesses'][$featured_count] = (array) $this->franchise_model->get_one($featured_business->business_id);
}
$page['featured_businesses'][$featured_count]['f_type'] = $featured_business->type;
$featured_count++;
}
if($featured_businesses->num_rows() < 3)
{
$limit = 3 - $featured_businesses->num_rows();
$random_business = $this->business_listing_model->get_random($limit);
foreach($random_business->result() as $index => $featured_business)
{
$page['featured_businesses'][$featured_count] = (array) (array) $this->business_listing_model->get_one($featured_business->business_listing_id);
$page['featured_businesses'][$featured_count]['f_type'] = 'business';
$featured_count++;
}
}
$page['business_categories'] = $this->business_category_model->get_all('', array('business_category_title' => 'asc'));
$page['franchise_categories'] = $this->franchise_category_model->get_all();
$template['content'] = $this->template->get_view('home', $page, 'site');
$this->template->render($template, 'site');
}
public function sell_your_biz()
{
$username = $this->session->userdata('username');
$account_type = $this->session->userdata('account_type');
$account = $this->account_model->get_by_username($username);
if(strlen($username)==0)
{
$this->template->notification('Please login or create an account to post a listing', 'error');
redirect('/login/');
}
$template = array();
$template['title'] = "Sell Your Biz";
$page = array();
$template['content'] = $this->template->get_view('sell_your_biz', $page, 'site');
$this->template->render($template, 'site');
}
public function view_reconvert()
{
$template = array();
$template['title'] = "Home";
$page = array();
$page['countries'] = $this->country_model->get_all();
$page['business_categories'] = $this->business_category_model->get_all();
$page['franchise_categories'] = $this->franchise_category_model->get_all();
$template['content'] = $this->template->get_view('home2', $page, 'site');
$this->template->render($template, 'site' , 'template_rconvert');
}
}
This is just one way of doing it, but you can eg set/define your meta data in your controller as such:
public function index()
{
$template = array();
$template['title'] = "Home";
$page['meta_desc'] = "Description here";
$page['meta_key'] = "Keywords here";
Then change the view file to correspond to the same variables:
<meta name="description" content="<?= $meta_desc?>" />
<meta name="keywords" content="<?=$meta_key" />
Related
Can anybody help me figuring out this cause I don't know where's the problem.
I've tried many times and even search for lots of tutorials still couldn't work at all. Please help me to solve my problems thanks alot.
This is my controllers saved as Home.php
<?php
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('HomeModel');
// Your own constructor code
}
}
function index(){
$query = $this->HomeModel->getEmployees();
$data['EMPLOYEES'] = null;
if($query){
$data['EMPLOYEES'] = $query;
}
$this->load->view('index.php', $data);
}
?>
This is model saved as HomeModel.php
<?php
class HomeModel extends Model {
function HomeModel(){
parent::Model();
}
function getEmployees(){
$this->db->select("jantina,bangsa,agama");
$this->db->from('pesakit');
$query = $this->db->get();
return $query->result();
}
}
?>
This is views saved as index.php
<?php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Display Records From Database Using Codeigniter</title>
<link href="<?= base_url();?>css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="row">
<div style="width:500px;margin:50px;">
<h4>Display Records From Database Using Codeigniter</h4>
<table class="table table-striped table-bordered">
<tr><td><strong>Jantina</strong></td><td><strong>Bangsa</strong></td><td><strong>Agama</strong></td></tr>
<?php foreach($EMPLOYEES as $employee){?>
<tr><td><?=$employee->jantina;?></td><td><?=$employee->bangsa;?></td><td><?=$employee->agam;?></td></tr>
<?php }?>
</table>
</div>
</div>
</body>
</html>
config.php
$config['base_url'] = 'http://localhost/project/';
$config['index_page'] = 'index.php';
$config['uri_protocol'] = 'AUTO';
routes.php
$route['default_controller'] = 'home';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
database.php
$active_group = 'main';
$active_record = TRUE;
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => '',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
$db['main']['hostname']='xx.x.xxx.xx';
$db['main']['username']='this server's username';
$db['main']['password'] ='this server's password';
$db['main']['database'] = 'database name';
$db['main']['dbdriver'] = 'mysql';
$db['main']['dbprefix'] = '';
$db['main']['pconnect'] = TRUE;
$db['main']['db_debug'] = TRUE;
$db['main']['cache_on'] = FALSE;
$db['main']['cachedir'] = '';
$db['main']['char_set'] = 'utf8';
$db['main']['dbcollat'] = 'utf8_general_ci';
$db['main']['swap_pre'] = '';
$db['main']['autoinit'] = TRUE;
$db['main']['stricton'] = FALSE;
);
Help me please, I'm totally a newbie for CI. Thanks alot.
Unless this is a typo in the controller, you have an extra closing brace above the index() function.
<?php
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('HomeModel');
// Your own constructor code
}
} <--- THIS IS CLOSING YOUR CONTROLLER CLASS.
function index(){
$query = $this->HomeModel->getEmployees();
$data['EMPLOYEES'] = null;
if($query){
$data['EMPLOYEES'] = $query;
}
$this->load->view('index.php', $data);
}
} <--- IT NEEDS TO BE DOWN HERE.
?>
There's a lot wrong here. Let's start with your Home controller.
Don't put a ?> at the end of your files.
Move your index function into the Home controller class as a method.
I simplified the code a little, if the getEmployees() method returns null anyway on failure.
I'd use the compact($employees) function here. It's the same as writing ['employees' => $employees].
Be consistent with naming, don't use all caps. Save all caps for global constants.
You don't need the .php in the $this->load->view() first parameter.
...
<?php
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('HomeModel');
}
public function index()
{
$employees = $this->HomeModel->getEmployees();
$this->load->view('index', compact('employees'));
}
}
A lot of the same for the Home Model.
<?php
class HomeModel extends CI_Model
{
public function getEmployees()
{
$this->db->select('jantina, bangsa, agama');
$this->db->from('pesakit');
return $this->db->get()->result();
}
}
For the index.php page.
Remove the <?php opening tag from the first line of your file.
I wouldn't recommend using short tags like <?=.
In view files, its better to be explicit with your foreach, if, while, etc blocks by using foreach (...) : endforeach;
...
<!DOCTYPE html>
<html lang="en">
<head>
<title>Display Records From Database Using Codeigniter</title>
<link href="<?php echo base_url();?>css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="row">
<div style="width:500px;margin:50px;">
<h4>Display Records From Database Using Codeigniter</h4>
<table class="table table-striped table-bordered">
<tr><td><strong>Jantina</strong></td><td><strong>Bangsa</strong></td><td><strong>Agama</strong></td></tr>
<?php foreach ($employees as $employee) : ?>
<tr><td><?php echo $employee->jantina; ?></td><td><?php echo $employee->bangsa; ?></td><td><?php echo $employee->agam; ?></td></tr>
<?php endforeach; ?>
</table>
</div>
</div>
</body>
</html>
I think config.php and routes.php look fine.
You've got a syntax error in your database.php array formatting. I'd just keep it in the same format as it was originally.
<?php
$active_group = 'main';
$active_record = true;
$query_builder = true;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = false;
$db['default']['db_debug'] = ENVIRONMENT !== 'production';
$db['default']['cache_on'] = false;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = true;
$db['default']['stricton'] = false;
$db['main']['hostname'] = 'xx.x.xxx.xx';
$db['main']['username'] = 'this server\'s username';
$db['main']['password'] = 'this server\'s password';
$db['main']['database'] = 'database name';
$db['main']['dbdriver'] = 'mysqli';
$db['main']['dbprefix'] = '';
$db['main']['pconnect'] = true;
$db['main']['db_debug'] = true;
$db['main']['cache_on'] = false;
$db['main']['cachedir'] = '';
$db['main']['char_set'] = 'utf8';
$db['main']['dbcollat'] = 'utf8_general_ci';
$db['main']['swap_pre'] = '';
$db['main']['autoinit'] = true;
$db['main']['stricton'] = false;
As a side note, read up on PSR-1 and PSR-2 coding standards. Also, please take a look at PHP The Right Way.
REplace(If index is your view page name)
$this->load->view('index.php', $data);
To
$this->load->view('index', $data);
My problem is this:
I have a masterpage:
<head>
<meta charset="utf-8" />
<title><?php echo isset($title)? $title: NULL; ?></title>
<?php $this->load->view('layout/header'); ?>
</head>
<body>
<!-- BEGIN PAGE BASE CONTENT -->
<?php $this->load->view($content);?>
<!-- END PAGE BASE CONTENT -->
</body>
and my dashboard controller:
class Dashboard extends CI_Controller {
public function index()
{
if($this->session->userdata('login') == true){
$data['title'] = 'Dashboard';
$data['content'] = 'pages/dashboard';
$this->load->view('layout/master', $data);
}
else{
redirect('auth');
}
}
and my add controller:
if($this->session->userdata('login') == true){
$data['title'] = 'افزودن مشتری';
$data['content'] = 'pages/add_customer';
$this->load->view('layout/master', $data);
}
else{
redirect('auth');
}
My problem is that at first when i call dashboard, everything is OK. but when i call add, everything mess up like there is no CSS attached or something.
Should i do something before set value to $content?
I cant understand what the problem is.
When in a function you can't do anything with it. But can't do anything outside. Like your else statement.
public function add(){
$data['title'] = 'افزودن مشتری';
$data['content'] = 'pages/add_customer';
$this->load->view('layout/master', $data);
}
else{
redirect('auth');
}
This is completely wrong practices. Just use
public function add(){
$data['title'] = 'افزودن مشتری';
$data['content'] = 'pages/add_customer';
$this->load->view('layout/master', $data);
}
Load Codeigniter for the Arabic Letters
Codeigniter by default is set to use UTF-8 for much of its internal functionality, so just make sure the charset is set to UTF-8 in your application/config/config.php file.
$config['charset'] = "UTF-8";
And set the header too
header('Content-Type: text/html; charset=utf-8');
I have certain questions since I'm doing a web app, and I feel kinda confused about keeping the mvc structure in a web application without using any frameworks.
Here is the structure of my app.
index:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<!--<link rel="stylesheet" type="text/css" href="index.css" />-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="js/functions.js"></script>
<script>
$(document).ready(function() {
loginSend();
});
</script>
<title></title>
</head>
<body>
<div id="login">
Username: <input type="text" id="username" name="username"><br>
Password: <input type="password" id="password" name="password"><br>
<input id="send" type="button" value="Enviar">
</div>
</body>
</html>
The loginsend function sends the data to service.php
<?php
include('server/main.php');
$action = $_POST['action'];
switch($action){
case "loginCheck":
$username=$_POST['username'];
$password=$_POST['password'];
$users = new users();
echo $users->loginCheck($username,$password);
break;
}
?>
And the service uses some classes I defined in main.php
<?php
class db{
public function conn() {
try{
$dbhost = "localhost";
$dbname = "eout";
$dbuser = "root";
$dbpass = "";
if($conn = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, $dbuser, $dbpass)){
return($conn);
}
}
catch (Exception $e){
echo "Se ha presentado un error al conectar con la base de datos".$e;
}
}
}
class users{
function loginCheck($username, $password) {
try{
$db = new db();
$conn = $db->conn();
$pass_encriptada = md5 ($password);
$SQL_LOGIN_CHECK = "SELECT * FROM users where username='".$username."' and password='".$pass_encriptada."' and deleted='0'";
$conn->prepare($SQL_LOGIN_CHECK);
foreach($check = $conn->query($SQL_LOGIN_CHECK) as $row) {
$username_check = $row['username'];
if ($username_check == $username){
session_start();
$_SESSION['logged'] = 1;
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['namelastname'] = $row['name'] ." ".$row['lastname'];
$usertype_id = $row['usertype_id'];
if ($usertype_id == 1 ){ //problema
$_SESSION['teacher'] = 1;
$response = "teacher";
$json = json_encode($response);
echo $json;
}
if ($usertype_id != 1 ){ //problema
$response = "user";
$json = json_encode($response);
echo $json;
}
}
}
}
catch(Exception $e){
echo "Se ha presentado un error en loginCheck".$e;
}
}
}
?>
In this case, I understand that index.php its my view, however I have certain doubts about the model/controller part. I understand in my example that the main file is the one that interacts with data, so it must be the model... in my case... its service.php my controller? Since is the one that interacts with the model? I feel kinda confused about this. In case I am wrong. How can I make a controller?
Thanks in advance.
I am using Facebook PHP SDK with Codeigniter to do login and registration using Facebook. For this I am using This tutorial
my controller 'facebooktest.php' code is:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Facebooktest extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('input');
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
}
function Facebooktest() {
parent::Controller();
$cookies = $this->load->model('facebook_model');
}
function index() {
$this->load->view('facebooktest/test2');
}
function test1() {
$data = array();
$data['user'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test1', $data);
}
function test2() {
$data['friends'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test2', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
view 'test2.php' has code as:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Kent is Learning CodeIgniter - Test 2</title>
</head>
<body>
<fb:login-button autologoutlink="true"
onlogin="window.location.reload(true);"></fb:login-button>
<div style="width:600px;">
<?
if(isset($friends)){
foreach($friends as $friend){
?>
<img src="http://graph.facebook.com/<?=$friend['id'];?>/picture" title="<?=$friend['name'];?>" />
<?
}
}
?>
</div>
<p><?=anchor('facebook_connect/page4','Go back to page 4 of the tutorial');?></p>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '457228377680583', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
// A user has logged in, and a new cookie has been saved
window.location.reload(true);
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
</body>
</html>
And model 'facebook_model.php' has code:
<?php
class Facebook_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_facebook_cookie() {
$app_id = '457228377680583';
$application_secret = '01f660b73bc085f0b78cd22322556495';
if (isset($_COOKIE['fbs_' . $app_id])) {
echo "dfgdsf";exit;
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
} else {
return null;
}
}
function getUser() {
$cookie = $this->get_facebook_cookie();
$user = #json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']), true);
return $user;
}
function getFriendIds($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friend_ids = array();
foreach ($friends['data'] as $friend) {
$friend_ids[] = $friend['id'];
}
if ($include_self == TRUE) {
$friend_ids[] = $cookie['uid'];
}
return $friend_ids;
}
function getFriends($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
print_r($cookie);
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
if ($include_self == TRUE) {
$friends['data'][] = array(
'name' => 'You',
'id' => $cookie['uid']
);
}
return $friends['data'];
}
function getFriendArray($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friendlist = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friends = array();
foreach ($friendlist['data'] as $friend) {
$friends[$friend['id']] = array(
'name' => $friend['name'],
'picture' => 'http://graph.facebook.com/'.$friend['id'].'/picture'
);
}
if ($include_self == TRUE) {
$friends[$cookie['uid']] = 'You';
}
return $friends;
}
}
?>
The problem is that, in model, it is coming inside 'getFriends()'. From there it is going inside 'get_facebook_cookie()'. But it is not going inside if(isset($_COOKIE['fbs_' . $app_id])))
and hence, it is nor displaying data that I want.
So, if possible, please let me know whats wrong with my code.
Thanks in advance....
using This Template Library
When I try and use the add_js() function it errors out. I add the regions $_scripts to the template header file but when I load the page it says undefined variable _scripts.
any thoughts?
changed <?= $_scripts ?> to <?= (isset($_scripts)) ? $_scripts : “”; ?>
and obviously I lose the error but the js file still isn't loading.
I did an echo at each step though the add_js() method and the output is correct. I also did an output of $this->js and they both had the correct output. So it gets through the get_js method fine and sets the class variable fine but I don't get anything added to the actual page.
sorry different computer now.
here is the controller method:
function registrationForm(){
$this->template->set_template('single');
$this->template->write_view('header', 'templates/header_template');
$this->template->write_view('footer', 'templates/footer_template');
$this->template->write_view('center', 'user/registration_form');
$this->template->add_js('js/jquery.min.js');
$this->template->add_js('js/validate.jquery.js');
$this->template->render();
}
here is the head section:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?= base_url() ?>css/style.css" type="text/css" rel="stylesheet" />
<?= (isset($_scripts)) ? $_scripts : ""; ?>
<?= (isset($_styles)) ? $_styles : ""; ?>
</head>
and the add_js() method:
function add_js($script, $type = 'import', $defer = FALSE)
{
$success = TRUE;
$js = NULL;
$this->CI->load->helper('url');
switch ($type)
{
case 'import':
$filepath = base_url() . $script;
$js = '<script type="text/javascript" src="'. $filepath .'"';
if ($defer)
{
$js .= ' defer="defer"';
}
$js .= "></script>";
break;
case 'embed':
$js = '<script type="text/javascript"';
if ($defer)
{
$js .= ' defer="defer"';
}
$js .= ">";
$js .= $script;
$js .= '</script>';
break;
default:
$success = FALSE;
break;
}
// Add to js array if it doesn't already exist
if ($js != NULL && !in_array($js, $this->js))
{
$this->js[] = $js;
$this->write('_scripts', $js);
}
return $success;
}
template.php config file
/*
|--------------------------------------------------------------------------
| Default Template Configuration (adjust this or create your own)
|--------------------------------------------------------------------------
*/
$template['default']['template'] = 'templates/default_template';
$template['default']['regions'] = array(
'header',
'left',
'right',
'footer',
);
$template['default']['parser'] = 'parser';
$template['default']['parser_method'] = 'parse';
$template['default']['parse_template'] = FALSE;
/*
|--------------------------------------------------------------------------
| Default Template Configuration (adjust this or create your own)
|--------------------------------------------------------------------------
*/
$template['single']['template'] = 'templates/single_template';
$template['single']['regions'] = array(
'header',
'center',
'footer',
);
$template['single']['parser'] = 'parser';
$template['single']['parser_method'] = 'parse';
$template['single']['parse_template'] = FALSE;
/* End of file template.php */
/* Location: ./system/application/config/template.php */