Passing variables between php pages - php

I'm new to the Kohana Framework. I have a problem - How can I pass the variable $title from Layout.php to Head.php?
In controller:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Admin_Quanly extends Controller_Template {
public $template='admin/layout';
function _showWithTemplate($subview,$title)
{
$admin_path = 'admin/';
$this->template->head = View::Factory(''.$admin_path.'head');
$this->template->subview = View::Factory(''.$admin_path.''.$subview.'');
$this->template->title = $title;
}
public function action_index()
{
$this->_showWithTemplate('subview/home','Trang quản trị hệ thống');
}
}
In view Layout.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $head?>
</head>
<body>
</body>
</html>
In view Head.php:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?=$title?></title>
<base href="<?=URL::base()?>">
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="javascript/jquery.min.js"></script>
<script type="text/javascript" src="javascript/ddaccordion.js"></script>

You could do something like this:
$admin_path = 'admin/';
$this->template->head = View::Factory(''.$admin_path.'head');
$this->template->head->title = $title;
$this->template->subview = View::Factory(''.$admin_path.''.$subview.'');
$this->template->title = $title;
Note the $this->template->head->title = $title; you need to pass it along manually to the head view.

You can use set() or bind(). See example:
$view = View::factory('user/roadtrip')
->set('places', array('Rome', 'Paris', 'London', 'New York', 'Tokyo'));
->bind('user', $this->user);
Ref: http://kohanaframework.org/3.3/guide/kohana/mvc/views

What you are looking for is set_global
http://docs.kohanaphp.com/core/view#set_global
It will allow you to set a variable for all your views to be able to use. You won't be passing it per say but it will still do what you want.
Example fix
function _showWithTemplate($subview,$title)
{
$admin_path = 'admin/';
$this->template->head = View::Factory(''.$admin_path.'head');
$this->template->subview = View::Factory(''.$admin_path.''.$subview.'');
$this->template->set_global('title', $title);
}

Related

A random number (4) just appears in my php project

Im building a php project.
This is the structure
This is my init.php
<?php
use App\Core\Container;
require_once __DIR__."/../autoloader.php";
require_once __DIR__."/Core/Container.php";
$container = new Container();
which gets used within the index.php
<?php
require "./src/init.php";
$pathinfo = $_SERVER["PATH_INFO"];
$routes= [
"/team" => ['TeamController',
'showTeampage'],
];
if(isset($routes[$pathinfo])){
$controllername = $routes[$pathinfo][0];
$method = $routes[$pathinfo][1];
$controller = $container->make($controllername);
}
This is the container php where the problem occurs:
<?php
namespace App\Core;
use PDO;
use App\Team\TeamController;
use App\Team\TeamRepository;
class Container {
public $storage = [];
public $buildManuals = [];
public function __construct() {
$this->buildManuals = [
'pdo'=> function () {
$pdo = new PDO('mysql:host=localhost;dbname=vanillaPHP;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
return $pdo;
},
'TeamController'=> function() {
$controller = new TeamController();
},
'TeamRepository'=>function() {
return new TeamRepository($this->make("pdo"));
},
];
}
public function make(String $string) {
if(empty($this->storage[$string]) ) {
$this->storage[$string] = $this->buildManuals[$string]();
}
return $this->storage[$string];
}
When Im entering the following URI he makes a TeamController onject I have tested it.
But he prints out the number 4 in UI for what ever reason. Why is this happening?
This is my TeamController class btw
namespace App\Team;
use App\Core\AbstractController;
use App\Team\TeamRepository;
class TeamController {
public $name ="test";
// public function __construct(Teamrepository $teamRepo)
// {
// $this->teamRepo = $teamRepo;
// }
public function hi() {
echo "hi";
}
// public function showTeampage() {
// $teammembers = $this->teamRepo->fetchAll();
// $this->render($this->teamRepo->getTableName(),
// [
// 'params'=>$teammembers
// ]);
// }
}
This is the viewfield for the team:
<?php require __DIR__."../../../Components/Head.php"; ?>
<p>Hi im the team view</p>
<!-- TODO: display the team data in a beautiful way -->
<?php foreach($params as $teammember): ?>
<p>
<!-- <?php echo $teammember->firstname ?> -->
</p>
<?php
endforeach;
?>
<?php require __DIR__."../../../Components/Footer.php"; ?>
And this is the Components/Head.php:
<?php
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>The company</title>
</head>
<body>

display database result array in Codeigniter Controller and Also Pass in View

How Can We Fetch specific details from result array in controller and also pass result array to view. below i have written the code that i am using to get data from database in codeigniter model and then including it in controller and also able to pass it to view and echo results there, but i want to get some specific column results ( Metatitle, Metadesc, Metakeywrd ) in controller, so i can set meta_title, meta_description, meta_keywords values in controller only and pass it to view head dynamically,
This is My Controller
<?php
class India extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function memberview()
{
$data['meta_title'] = '';
$data['meta_description'] = '';
$data['meta_keywords'] = '';
$teamid = $this->uri->segment(6);
$data['view'] = 'region/india/team-member-view.php';
$this->load->model('region/India_model');
$data['team'] = $this->India_model->tmview($teamid);
$data['teamlist'] = $this->India_model->teamlist();
$this->load->view('region/layout', $data);
}
}
?>
This is My Model
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class India_model extends CI_Model{
public function tmview($teamid){
$this->db->select('*');
$this->db->from('ojiteam');
$this->db->where("id",$teamid);
$query = $this->db->get();
return $query->result_array();
}
}
?>
Here in View i am fetching data like this, this is working properly but head parts meta tags is getting set at controller, there are multiple static pages for that meta tags getting set in controller file and for some dynamic pages meta tags have been saved into database column.
<?php
foreach($team as $value){
};
?>
<!doctype html>
<html lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="content-language" content="en"/>
<title><?php echo $meta_title; ?></title>
<meta name="description" content="<?php echo $meta_description; ?>" />
<meta name="keywords" content="<?php echo $meta_keywords; ?>" />
i'm not sure if i understood what you want but if i did i guess this is what you want ?
$team = $this->India_model->tmview($teamid);
$data['meta_title'] = $team['meta_title'];
$data['meta_description'] = $team['meta_description'];
$data['meta_keywords'] = $team['meta_keywords'];

using custom template engine how do I replace content with php

So, I have a template engine I made and I want to replace {pageBody} with contents from a PHP file, when I do it using the template engine it does not execute the PHP, rather it displays it in view source option.
TEMPLATE.PHP
<?php
class TemplateLibrary {
public $output;
public $file;
public $values = array();
public function __construct($file) {
$this->file = $file;
$this->file .= '.tpl';
$this->output = file_get_contents('templates/'.$this->file);
}
public function replace($key, $value)
{
$this->values[$key] = $value;
}
public function output() {
foreach($this->values as $key => $value)
{
$ttr = "{$key}";
$this->output = str_replace($ttr, $value, $this->output);
}
return $this->output;
}
}
index.tpl
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>{page_title}</title>
{page_style}
</head>
<body>
{page_header}
{page_body}
{page_footer}
</body>
</html>
HTML replace works fine, but PHP does not. Any ideas?
You are rather scattered with your files and the list is incomplete. I've listed all the files you've provided so far below.
#Jonathon above is correct, that you will need to use output buffering to capture the output of the PHP file and include() the file (so it gets executed) instead of using file_get_contents() (which does not execute the file).
[edit] I re-created all these files in my local environment and confirmed that #Jonathon's suggestion worked perfectly. I've updated dev/replacements.php to include the suggested code.
Additionally, I added two more functions to your TemplateLibrary class : replaceFile($key, $filename) that does the file_get_contents($filename) so that you don't have to repeat it so often, and replacePhp($key, $filename) that performs an include() while capturing the output, so you can encapsulate the complexities of including a PHP file.
Good Luck!
main.php
<?php
require_once 'dev/dev.class.php';
require_once 'dev/templatelibrary.php';
$dev = new dev('netnoobz-billing');
$dev->loadLib('JS', 'js', 'jquery');
// template library and required files
$template = new TemplateLibrary('index');
require_once 'dev/replacements.php';
echo $template->output();
dev/templatelibrary.php
<?php
class TemplateLibrary {
public $output;
public $file;
public $values = array();
public function __construct($file) {
$this->file = $file;
$this->file .= '.tpl';
$this->output = file_get_contents('templates/'.$this->file);
}
public function replace($key, $value)
{
$this->values[$key] = $value;
}
public function replaceFile($key, $filename)
{
$this->values[$key] = file_get_contents($filename);
}
public function replacePhp($key, $filename)
{
ob_start();
include($filename);
$data = ob_get_clean();
$this->values[$key] = $data;
}
public function output() {
foreach($this->values as $key => $value)
{
$ttr = "{$key}";
$this->output = str_replace($ttr, $value, $this->output);
}
return $this->output;
}
}
index.tpl
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>{page_title}</title>
{page_style}
</head>
<body>
{page_header}
{page_body}
{page_footer}
</body>
</html>
replacements.php
<?php
$configStyleSheet = '<style type="text/css">'
. file_get_contents('styles/default/main.css')
. '</style>';
$pageHeader = file_get_contents('templates/header.tpl');
$pageFooter = file_get_contents('templates/footer.tpl');
#$pageBody = file_get_contents('loaders/pageBody.php');
ob_start();
include('loaders/pageBody.php');
$pageBody = ob_get_clean();
$template->replace('{page_style}' , $configStyleSheet);
$template->replace('{page_title}' , 'NetBilling');
$template->replace('{page_header}', $pageHeader);
$template->replace('{page_footer}', $pageFooter);
$template->replace('{page_body}' , $pageBody);
loaders/pageBody.php
<?php echo 'test'; ?>
[edit] added loaders/pageBody.php from OP's comment.
[edit] Updated dev/replacements.php to capture output buffer and use include on .php
You're using file_get_contents in your pastebin code but you should be using your template processor or PHP's include() instead. If you do $template->replace('{page_header}', $pageHeader), $pageHeader is just the source of the tpl and your template processor does not know that so it will just replace the tag with that source. Fix:
$pageHeader = new TemplateLibrary('header');
// ...
$template->replace('{page_header}', $pageHeader->output());
For the PHP files, you should call include() on the file, wrapped in output buffering, so you can pass the output of the PHP execution as the template variable, instead of the PHP source itself:
ob_start();
include('loaders/pageBody.php');
$pageBody = ob_get_clean();
/// ...
$template->replace('{page_body}', $pageBody);

Write into csv in php (class php)

I'm using php class to write data to CSV. Link to class: http://www.jongales.com/blog/2009/09/24/php-class-to-write-csv-files/
Class code:
<?php
/**
* Simple class to properly output CSV data to clients. PHP 5 has a built
* in method to do the same for writing to files (fputcsv()), but many times
* going right to the client is beneficial.
*
* #author Jon Gales
*/
class CSV_Writer {
public $data = array();
public $deliminator;
/**
* Loads data and optionally a deliminator. Data is assumed to be an array
* of associative arrays.
*
* #param array $data
* #param string $deliminator
*/
function __construct($data, $deliminator = ",")
{
if (!is_array($data))
{
throw new Exception('CSV_Writer only accepts data as arrays');
}
$this->data = $data;
$this->deliminator = $deliminator;
}
private function wrap_with_quotes($data)
{
$data = preg_replace('/"(.+)"/', '""$1""', $data);
return sprintf('"%s"', $data);
}
/**
* Echos the escaped CSV file with chosen delimeter
*
* #return void
*/
public function output()
{
foreach ($this->data as $row)
{
$quoted_data = array_map(array('CSV_Writer', 'wrap_with_quotes'), $row);
echo sprintf("%s\n", implode($this->deliminator, $quoted_data));
}
}
/**
* Sets proper Content-Type header and attachment for the CSV outpu
*
* #param string $name
* #return void
*/
public function headers($name)
{
header('Content-Type: application/csv');
header("Content-disposition: attachment; filename={$name}.csv");
}
}
?>
and php code:
if($_GET['action']=="csv") {
$data = array(array("one","two","three"), array(4,5,6));
$csv = new CSV_Writer($data);
$csv->headers('test');
$csv->output();
}
The problem is the resulting file. I have a CSV file instead of the array is only the HTML content page. Why is this happening?
The content of the CSV file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
<link href="../css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jscripts/picnet.table.filter.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript">
...
Thx for help.
You have two issues:
You're reinventing the wheel, as PHP already has fputcsv. Don't do that!
From what I can see, you didn't stop executing the script, so PHP is going to go ahead and render the rest of the HTML document. I can't tell exactly why you're not seeing the HTML preceded by CSV info, but maybe the output cache is being flushed somehow. The fix for this is to add an exit(); line at the end of that block:
if($_GET['action']=="csv") {
$data = array(array("one","two","three"), array(4,5,6));
$csv = new CSV_Writer($data);
$csv->headers('test');
$csv->output();
exit();
}

sometime SetCookie() not working

Hi I created two file to switch my forum (Language Chinese and English)
enForum.php
<?php
function foo() {
global $_COOKIES;
setcookie('ForumLangCookie', 'en', time()+3600, '/', '.mysite.com');
echo 'running<br>';
$_COOKIES['ForumLangCookie'] = 'en';
bar();
} // foo()
function bar() {
global $_COOKIES;
if (empty($_COOKIES['ForumLangCookie'])) {
die('cookie_name is empty');
}
echo 'Language =' . $_COOKIES['ForumLangCookie'];
echo "<br>";
} // bar()
foo();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>forum EN Version</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
please be patient ...
<script LANGUAGE='javascript'>
location.href='http://www.mysite.com/forum/index.php';
</script>
</body>
</html>
cnForum.php
<?php
function foo() {
global $_COOKIES;
setcookie('ForumLangCookie', 'cn', time()+3600, '/', '.mysite.com');
echo 'running<br>';
$_COOKIES['ForumLangCookie'] = 'cn';
bar();
} // foo()
function bar() {
global $_COOKIES;
if (empty($_COOKIES['ForumLangCookie'])) {
die('cookie_name is empty');
}
echo 'Language =' . $_COOKIES['ForumLangCookie'];
echo "<br>";
} // bar()
foo();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>forum CN Version</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
please be patient ...
<script LANGUAGE='javascript'>
location.href='http://www.mysite.com/forum/index.php';
</script>
</body>
</html>
There are some files including include template('logon');,include template('regist'); etc, I write some code to get the Cookie value and control the flow to load different template files.
$lang = $_COOKIE["ForumLangCookie"];
// for Debug
// echo '$lang is '.$lang;
// echo '<br/>';
if ($lang == "cn"){
include template('logon');
}
else if ($lang == "en"){
include en_template('logon');
}
But sometime the SetCookie() not working. Do I need add Sleep(someSeconds); for my code?
Cookies can be accessed with $_COOKIE,not $_COOKIES.
EDIT:Sorry for misunderstanding. I suggest you to change the variable $_COOKIES as another common one so people can understand your question correctly.
PHP array name is $_COOKIE, not $_COOKIES

Categories