So I decided to give codeigniter a chance and convert my existing site which is all custom php to the codeigniter framework. But trying to figure out how to do this best in codeigniter that I was doing from my original site. In the original site a person would visit a page such as index.php. In the index.php code its broken into sections like so (This is just a very simple example):
index.php:
<html>
<head></head>
<body>
<div id="top">{$SECTION1}</div>
<div id="main">{$SECTION2}</div>
<div id="bottom">{$SECTION3}</div>
</body>
</html>
Then in my main php file that is included in every single page I run a query that grabs all "modules" that are assigned to each section above for the index.php page. So give me all modules that are assigned to {$SECTION1}, {$SECTION2} and {$SECTION3} for index.php. A module in my original system is simply a php file that does a specific job so I might have a module called latest_story.php and in the script it gets the last 10 stories from the database and display the results.
latest_story.php
include('class/story/story_class.php');
$story = new Story($databaseconn);
$latest_story = $story->findLatestStory(10);
//If results back from $latest_story loop through it
//and display it however I want
Then using output buffering I execute each module then take the outputted information from each module assigned to each section and replace that section with the outputted data.
Can this be done in codeigniter? If so can someone point me in the right direction in doing this in codeigniter?
EDIT
To give a more clear view of what Im doing in the original system I run a query on every single page to determine what "modules" to grab for the current page the person is viewing then run this code
foreach($page_modules AS $curr_module)
{
$module_section = intval($curr_module->section);
$module_file = $global_function->cleanData($curr_module->modfile);
$module_path = MODS .$module_file;
if(is_file($module_path))
{
ob_start();
include($module_path);
${'global_pagemod' .$module_section} .= ob_get_contents();
ob_end_clean();
}
}
Then I simply take each variable created for each section and replace {$SECTION[n]} with that variable in the template.
ADDITIONAL EDIT
What Im trying to do is be able to create "modules" that do specific tasks and then in the backend be able to dynamically place these modules in different sections throughout the site. I guess you can say its like wordpress, but a more simplier approach. Wordpress you can add a module and then assign it to your pages either in the left column, middle or right column. Im trying to do pretty much the same thing.
Basically, Codeigniter is an MVC framework. To use it, you really want to embrace that rather than include files. You can rejig your code as:
In your controller:
function example()
{
$this->load->model('story_model','story');
$data['section1'] = $this->story->latest();
$data['section2'] = $this->story->top_stories(5);
$data['section3'] = $this->story->most_popular();
$this->load->view('example', $data );
}
In your model:
function latest()
{
return $this->db->limit(1)->get('stories');
}
etc.
In your view:
<html>
....
<div id="latest">
<h2><?php echo $section1->title; ?></h2>
<?php echo $section1->body; ?>
</div>
<div id="top">
<?php foreach $section2 as $popular { ?>
<h2><?php echo $popular->title; ?></h2>
<?php echo $popular->body; ?>
<?php foreach} ?>
</div>
</html>
If you wanted a second page, with different content but the same layout, you'd add this to your controller:
function second_page()
{
$this->load->model('tags_model','tag');
$this->load->model('authors_model','author');
$data['section1'] = $this->tag->latest();
$data['section2'] = $this->tag->top_tags(5);
$data['section3'] = $this->author->most_popular();
$this->load->view('example', $data );
}
and add in new models etc.
You can pass the retrieved data as an array to the main view and then access that data on the subviews.
For example:
Main View
$posts = $this->post_model->fetch_all();
$top_data = $this->more_data_model->fetch_more_data();
$data = array('posts'=>$posts,'top_data'=>$top_data);
$this->load->view('main_view',$data);
Then on the main view you load the subviews:
$data = array('data_name'=>$top_data);
$this->load->view('top_view',$data);
And then on the subview you just use the data however you want. There might be a more effective way to do this, but i believe this'll do the trick. :)
I do it like this:
Controller:
function about()
{
$user_session = $this->model_user_lite->Session_Check();
$data['auth'] = $user_session;
$user_id = $this->model_user_lite->Session_UserID();
$data['user_id'] = $user_id;
$this->load->view( 'main_about.php', $data );
}
View:
<? $this->load->view('header_base.php'); ?>
<? $this->load->view('include_standart.php'); ?>
<? $this->load->view('header_standart.php'); ?>
<div class="box">
<div class="box-top"></div>
<div class="box-center">
<div class="content">
<center>
<h2><?= lang('MAIN_ABOUT_CAPTION_TEAM'); ?></h2>
<div class="hr"></div>
...
Header Base:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="<?= base_url(); ?>/favicon.ico" type="image/x-icon">
<link rel="icon" href="<?= base_url(); ?>/favicon_animated.ico" type="image/x-icon">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta property="fb:admin_id" content="677920913" />
<meta property="fb:app_id" content="<?= FACEBOOK_APPID; ?>" />
<meta property="og:site_name" content="<?= SITE_NAME; ?>" />
<?php if ( empty( $og_title ) === FALSE ): ?>
<meta property="og:title" content="<?= $og_title; ?>" />
<?php endif ?>
...
This way you have a clean file system, seperate header, you can even have more headers just as you like, and can assign all the data from the controller to the view.
**Variables that are assigned from the controller, also go to views loaded by your "main view".
I'm using it in a major dating website and it works like a charm.
Related
there's something that's giving me a bit of a headache at the moment. I am querying a database retrieving some data after clicking a link from a previous page.
Easy enough I get to play about with some code in the 'echo'. Problem is in the ‘echo’ as I need to put in php includes and general html/design code for design purposes. Is there a way or a method where I can write the code but then call variables again later and have the ability to place other php code such as includes? Basically something which is going to let me have to have the code but then allow me to concentrate on the design aspect of my page.
Any help much appreciated.
<?php
if(!empty($_GET['book_url']))
{
$sql = "
SELECT articles.id, articles.order_ref, articles.art_title, articles.art_book, articles.art_url, book.id AS bookid, book.book_name AS book_name, book.book_url AS book_url
FROM articles
LEFT JOIN book ON articles.art_book = book.id
WHERE book_name = \"" .$_GET['book_url'] . "\"
ORDER BY id ASC
";
// then do the query, etc....
}
$results = $db->query($sql);
if($results->num_rows) {
While($row = $results->fetch_object()) {
echo "
////////Show Stuff
";
?>
You can separate the code and the HTML by putting the code in <?php ?>. Then, in your HTML you can have short code snippets that print the work you did in the code sections. Like this (there might be a syntax error or two, I don't have Apache to test):
<?php
$name = $_GET['name'];
function stuff() {
// this would normally be long and complicated
return "stuff";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>title</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<!-- try to keep these short so you can focus on design-->
<h1>The name is: <?php echo $name; ?></h1>
<h1>The stuff is: <?php echo stuff(); ?></h1>
</body>
</html>
Alternatively, you can use a framework like Laravel which will provide a templating system.
I have a webpage called search.php
I want it to have a title/tab tag that looks like this:
<head>
<title><?php echo $number_count; ?> items found - Mysearch </title>
<head>
But the variable $number_count is 0 until later php scripts are called to query the database and display the items one at a time. At the end of the HTML I can easily display <p> <?php echo $number_count; echo "items found" ?> </p> and it works with the correct count.
It must be defined first.
Best (and only in this case) approach to do it is to do calculations first, then generate website output.
EDIT:
You can do it like that:
<?php
$count = 125;
?><!DOCTYPE html>
....
<title>Title count: <?php echo $count ?></title>
....
So, I'm using a mix of PHP and HTML to display the results of a text file search query. On the previous page, there's a set of forms for a license plate number, start date, and end date. In theory, if the text file contains the license plate within the listed dates, it will show what time, date, and location all of them are shown in an unordered list. The code create the list without items initially, regardless of whether or not there's any matches. If there's matches, it creates a list item for each match. If not, it creates a single list item that says no matches were found.
Currently, however, it's trying to do both if there's no matches. If there's no number matching in the database, it'll create a mostly blank line for the "match," then display the message that there was no matches.
Here's an example of the current, wrong output:
Query results for :
, : .
There are no plates found matching the query.
Here's the code that's creating this. I've looked it over for an hour now and can't figure out why it's doing that.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<title>Query</title>
<link rel="Stylesheet" media="all" href="styles.css" />
</head>
<body>
<div class="match">
<h1>Query results for <?= $wantedplate ?>: </h1>
<ul>
<?php
$wantedplate = $_GET["plate"];
$data = fopen("stored.txt", "r");
$cline = fgets($data);
$match_check = 0;
list($cplate,$cdate,$ctime,$place) = explode(",",$cline);
while ( !feof($data) ) {
list($cplate,$csubject,$cdate,$ctime,$cplace) = explode(",",$cline);
if ($cplate == $wantedplate) {
$match_check += 1;
?>
<li> <?= $cdate ?>, <?= $ctime ?>: <?= $cplace ?>.</li>
<?php
;
$cline = fgets($data); }
else {$cline = fgets($data); }
}
if ( $match_check == 0 ) { ?>
<li> There are no plates found matching the query. </li>
<?php ; } ?>
</ul>
</div>
</body>
</html>
Any help that could be provided would be greatly appreciated. I've been staring at this for an hour now and still can't figured out why it's doing that. Thanks in advance for the assistance.
This question already has answers here:
How to dynamically change a web page's title?
(20 answers)
Closed 8 years ago.
I would like to change the title of the HTML page based on the content, but im including only the content below the header part, so i have to change the title from this included php. To explain:
<html>
<header><title>I would like to change</title></header>
<!--CONTENT-->
<?
include "pages/some_page.php";
?>
</html>
How could i do that? Anyone can help in this?
You cant do that without a nasty hack.
What you should do is perform all your logic BEFORE you output html. A simple example follows:
<?php
//index.php
//perform logic and set variables before any html
$page = isset($_GET['menu'])?$_GET['menu']:'home';
switch($page){
case 'home':
$title = ' welcome to myco.ltd';
$content = 'pages/home.php';
break;
case 'about':
$title = 'about us';
$content = 'pages/about.php';
break;
case 'contact':
$title = 'get in touch';
$content = 'pages/contact.php';
break;
}
//the following html could be in a separate file and included, eg layout.php
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<!--menu and other shared html here-->
<?php include $content;?>
<!-- shared footer stuff here-->
</body>
</html>
This is essentially a VERY barebones router script, an essential component of any framework. I would highly recommend you consider a lightweight framework rather than write everything from scratch. http://fatfreeframework.com/home would be a great start
The function below will let you change document title, meta keywords and meta description. You may use it anywhere in your application.
Just be sure to turn on output buffering using ob_start() before the function is called. I prefer including it at the top of application, just after all global settings are loaded.
function change_meta_tags($title, $keywords, $description){
$output = ob_get_contents();
if (ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/", "/<meta name=\"keywords\" content=\"(.*?)\" \/>/", "/<meta name=\"description\" content=\"(.*?)\" \/>/");
$replacements = array("<title>$title</title>", "<meta name=\"keywords\" content=\"$keywords\" />", "<meta name=\"description\" content=\"$description\" />");
$output = preg_replace($patterns, $replacements, $output);
echo $output;
}
Use javascript in some_page.php .
<?php echo "<script>document.title = '".$dynamicTitleVariable."';</script>"; ?>
Pending what you are trying to base the content off of, this could easily be done via an MVC-style setup. In your controller, you would generate the title based off of content that could be grabbed and pass this through to the view as a variable. Then, in your view have the title be dynamically set:
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
</html>
This should also work fine with SEO capability, as crawlers will be able to interpret this far better than they would JavaScript.
I'm building a website with wordpress and a bought template. I added some functionality to the options/page creation. One can set a general meta description in the options and a meta description for each page while creating it.
Although I'm entirely new to PHP, I managed to add everything necessary to my code. It wasn't all that hard and it works just fine. My questions are: Am I doing it right? How can I optimize my solution? What are the downsides of my approach?
HTML (header.php):
<?php
// Defining a global variable
global $page_meta_description;
// Initializing the variable with the set value from the page
$page_meta_description= get_post_meta($post->ID, MTHEME . '_page_meta_description', true);
// Add meta tag if the variable isn't empty
if ( $page_meta_description != "" ) { ?>
<meta name="description" content="<?php echo $page_meta_description; ?>" />
<?php }
// Otherwise add globally set meta description
else if ( of_get_option('main_meta_description') ) { ?>
<meta name="description" content="<?php echo of_get_option('main_meta_description'); ?>" />
<?php }
// Set global meta keywords
if ( of_get_option('main_meta_keywords') ) { ?>
<meta name="keywords" content="<?php echo of_get_option('main_meta_keywords'); ?>" />
<?php } ?>
You can use the wp_head hook.
// write this in your plugin
add_action('wp_head', 'myplugin_get_meta_tags');
function myplugin_get_meta_tags()
{
$content = '';
$content .= '<!-- add meta tags here -->';
return $content;
}
I think this is slightly more elegant that doing all the logic in the header.php file.
If you don't want to create a plugin for this, or it's needed for a single theme, you can add this code in the functions.php file in your theme (check the link for more info).
Note
The downside(s) to your solution are:
If you ever need to create a new template that uses a different header, you need to copy the meta code to each new file, and when you make changes, make them in all header files
The template files should have as little logic in them as possible, and having a bunch of ifs would clutter it unnecessarily.