Make a self-aware menubar - php

So, In the website I'm currently designing (HTML5, PHP, JS/JQuery and Bootstrap), I've got a basic menubar at the top of the page. Just your normal
<ul>
<li>Home</li>
<li class="active">About</li>
<li>Players</li>
<li>Rules</li>
</ul>
Now, there's a lot more to this, such as a login button, etc, but basically it's adding a LOT of clutter to the top of my pages, and I was wondering if there would be any way to put it in a header.php file.
My issue is how I can use it in multiple webpages and still have the class="active" part. The only thing I thought of was making a function where it takes the page name as a string and go through each line and does if (the page is the same as the link) { echo the element with the class="active" } else { echo the element without the class }
Thanks!

You probably want to extract your header to header.php as you said, and then use the PHP include method.
<?php
include 'header.php';
?>
As far as selecting the 'active' class, you could pass and set an '$active' variable on each page. And then, since the included file inherits the scope from the page where it's included, you can get the variable and preform your logic in the header.php page.

http://php.net/manual/en/function.include.php
You can include another php file located anywhere on your server, and have the menu html in there, in a function as you said.
As for keeping the class="active", since you already have it working somewhere, presumably in your main php file, you can just move it to the new header php file that will be included and re-factor if necessary.
I don't know what your code looks like at all, if you post part of it that does the menu, me or someone else will probably be able to help more.

Related

Execute the Code in a PHP Page And Echo the HTML Output

I absolutely don't post a question here in SO unless I really can't find a way to solve my problem myself. I did a lot of googling and was not able to find a solution for this one problem I am about to describe.
Here is the problem. I am creating a templated php website. With templated I mean something like below:
<?php include("header.php");?>
<div id="content">
<div id="main">
<h2><?php echo($page_title);?></h2>
<?php
echo ($page_content);
?>
</div>
<?php include("sidebar.php");?>
</div>
<?php include("footer.php");?>
As you can see here page template ECHOES the content of the $page_content variable between header and footer sections to build the page.
To keep the code clean and separated (in my own way) I have been placing the html content in .txt files (let's say page1_content.txt) and assigning the txt content to this variable ($page_content) as below:
$page_content = file_get_contents("page1_content.txt");
My problem starts when I place some php code in page1_content.txt, lets' call this file page2_content.php (yes, I change the file from .txt to .php). Then I assign the content of this file to $page_content variable as below as usual:
$page_content = file_get_contents("page2_content.php");
Now, when the page template ECHOES page2_content.php contents the php code in it is also echoed as string and not executed, but I am trying to query a database and do some stuff in this file with some php code. I mean, I want the php code inside page2_content.php to be executed and the cumulative html code to be echoed by the "echo" line inside the template file.
How can I achieve this?
Please ask me any questions if you need more info/clarification.
Thanks
EDİT:
As many people here suggested the solution was including the file. Actually, I tried including the file before but it didn't look like it was working, it broke my template, so I though I was on the wrong track and quit the "include" way of doing this. Since everybody here is advising to use include I tried that again. I replaced the php code in "page2_content.php" with a basic 1-line code just to see if it gets executed before adding generated html code without breaking the template and it worked. Apparently my php code had a problem at first place and hence broke my template execution.
Now I have changed the template structure slightly and pages using the template, and it seems to work nicely. Thanks a lot everybody. I have up-voted every answer suggesting that I use include :)
As #Ali suggested, you could include the files. The other option which I highly suggest you do not use is the eval() function.
I think what you want to do is to include your content PHP file, not echo it (as you are doing with header.php and footer.php).
echo($page_content);
Would become as below:
include("page2_content.php");
You've already done this in your footer and sidebar, just use include()

Making an header.php [Bootstrap3]

I am trying to do some basic HTML and PHP.
What I would like to do is, take this template:
http://startbootstrap.com/template-overviews/scrolling-nav/
And cut the menubar out of the index.html, and make that into a seperate header.php, so I can use it on my other pages as well.
I tried just cutting the code out of it, then pasting it in the header.php and including this. However it does not show up.
Could anyone explain to me how I should do this, I read about it on W3Schools that it could be something with the CSS.
I tried copying this over, to it with no success.
(The code: http://pastebin.com/6XKNaw98)
If someone could explain me how I can make the menubar of this template into a seperate header.php file, I'd love to hear.
You only want the navbar from this template, get the source code and copy paste only the html declaration which provide this navbar into a header.php.
Next, You have to echo the html like
echo "<nav class='some-bootstrap-class'>
<ul>
<li>Some item</li>
....
</ul>
</nav>";
Finally, include it into your html with the include function like on your pastebin.
Please note that echoing (don't know how to say it) html like this in PHP is pretty ugly (for me and other web developpers)

Including files in codeigniter

I am creating a website using codeigniter and I want to include the menu (options) file so that I could save all my time from independently pasting the code on every view I need.
Or even if there is a common file for custom functions where I could place the code and call the function.
ANy help. My menu option is as follows.
<h5>Admin Options</h5>
<ul>
<li>Portfolio
<ul>
<li> Add a Category</li>
<li> Edit/Delete Category</li>
<li> Add a Link</li>
<li> Edit/Delete Link</li>
</ul>
</li>
<li>First</li>
<li>First</li>
<li>First</li>
<li>First</li>
</ul>
Just put your HTML in a view file "options_view.php" and anywhere you want to include this HTML snippet just load that view:
<?php $this->load->view('options_view') ?>
As you can see by the answers there are a number of ways of doing this but honestly I don't see the point in a templating library as it's relatively easy to do on your own. I use templates for my entire site since it means I don't have to keep rewriting code. Below is how I do it.
Template.php This file loads the other parts of the template, it loads the header dependent on whether the user is logged in so I can add the user menus easily.
<?php
if($this->session->userdata('is_logged_in'))
{
$this->load->view('templates/header-admin', $title);
} else {
$this->load->view('templates/header', $title);
}
$this->load->view('templates/sidebar',$sidebar_content);
$this->load->view('pages/'.$main_content);
$this->load->view('templates/footer');
?>
Each of those pages is a static html file or as in the case of the main content and sidebar_content they're variables. So then from a controller I load my views like this (this is a basic page)
public function welcome()
{
$data['main_content'] = 'welcome';
$this->load->model('someModel');
$data['someArray'] = $this->someModel->someFunction();
$data['title']='Welcome to example.com';
$data['sidebar_content'] = 'sidebar/no_sidebar';
$data['additionalHeadInfo'] ='';
$this->load->view('templates/template',$data);
}
So what's happening above is the first line is the actual view getting loaded to main content this is a php page with nothing but the middle content of the site in it. Title fills in the title tags in the header. sidebar content loads the appropriate sidebar.php page (in this case it's an empty file). Additional head info is so I can load libraries or css pages specific to a single view. The final line brings it all together.
Edit - I added two lines for adding variable data. So you would do a call to your model like normal and return the data, but return it to an array inside the $data array. Then in your view you would access it like this (variables are obviously for example, you'd use whatever variables your model returns:
echo $someArray['userName'];
For the record normal PHP include statements work just fine in CI, it just makes a lot less sense than creating a template.
See CodeIgniter's documentation and the PHP documentation.
There is something to be said for self-directed learning.
Templating is going to be the answer for this. Since out of the box CI treats any view as essentially its own page, it is up to the user to either load other views progressively or to wrap all views except those loaded as strings into a common template.
Here is just one library to implement this:
http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html
Personally I would not load all views progressively as Wolf states. Nothing wrong with this except that it can lead to maintainability problems. I would create as many templates as necessary - some may not need the options view, for example - and load the correct one with each method.

Dynamic site, using include to get content in specific div , how?

I want to use php to easily maintain my website, but I simply can't figure out the language - I've found some tuts online, and some other questions here, but none help me.
I've divided my site into some .php files, header/footer and such - And using
works fine..
Now I want the content of my site, to update according to which menu I click on at my site.
http://dawtano.com/pp/
If I click on "about" I want the "Hello World" to open inside my content div, but I can't get the right php code to do it.
I think you should do this---
Note: This will only work if the CSS styling are on the current directory! ()
<div>
<?php
$html_page = implode('', file('http://dawtano.com/pp/'));
echo $html;
?>
</div>
Hope this helps!
well currently your links are taking you to a separate page entirely. So why not just code it so that your include file is specific to the page. i.e, on about.php, use something like
include 'about_content.php
in your contetnt div.
If you're looking for your content to load dynamically into the content div you'll need to look into using ajax to fetch the content pages.
One popular way to construct the site is to have a single php script which displays content based upon a $_GET variable like 'page' or 'content', and then make the link as:
'http://dawtano.com/pp/index.php?page=helloworldcontent'
Using this method, you would need to check if the variable ($_GET['page']) is set using isset(), and then make sure the string is safe... as anybody with a browser could just type in some mumbo-magic script and hijack your site:
'http://dawtano.com/pp/index.php?page=somecleaverlycraftedhax'
Once it exists and is safe, add the '.php' to the file name and include that file... if it exists! If it doesn't exist, then you will need some code to handle that, probably by displaying a 'File not Found' message, or redirecting home, or something.
I prefer not to do this because it is a pain to make safe, and I feel like it is pretty ugly. What I do instead is put all the header/footer/navbar/title bar scripts into seperate 'display' functions, and put them in another file.
Then include this file with the function definitions, and call all the 'display' functions to set up the page. So every php script in your site might look like:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION, etc... */
print_html_pre_content();
print '<p>Hello, world!</p>';
print_html_post_content();
?>
Since every script will have this structure, you can just create a template file once. When you want to create a new page for your site, copy the template, rename the copy to the php filename you want, and add content between the two print functions.
You also keep the ability to modify the header/footer/navbar/title bar for the whole site in a central location, namely the included file with the functions.
You might be looking for some sort of Template Engine which allows you to create your pages out of variable parts. You could have a look at TBS, which is more or less what is suggested by the name. But there is a whole lot more engines out there which could do the job.
If that's already too much over the top, maybe Apache SSI (Server Side Includes) are a try for you.
A little suggestion from my side, I am often using Apaches mod_rewrite in connection with a single controller.php file. Apaches mod_rewrite will then send all request to the controller.php which will fetch the appropriate page parts for the requested page using TBS and return the respective page. So you have the controll of the page in one location only.
To your original question about.php could look like:
<?php
include('header.php');
?>
// original page content as html for about.php
// assuming header ends with the starting div <div> where you like the content to appear
// and footer starts with the closing div </div>
// if you need variable content here, simply use <?php echo $your_variable ?>
<?php
include('footer.php');
?>
The best way would be to use a switch statement:
http://php.net/manual/en/control-structures.switch.php
Something like this:
<?php
include("header.php");
$page = $_GET['page'];
switch($page)
{
case "about":
include "about.php";
break;
case "faq":
include "faq.php";
break;
case "help":
include "help.php";
break;
default:
include "home.php";
}
include("footer.php);
?>
Then just make all of your links look like this:
http://www.example.com/index.php?page=home
Just replace home with the correct page.

Code to detect current page

Is there a php or javascript code that can detect the current user's page and then add <a class="active"> to an item in a ul (my menu). I include my menu in my pages with PHP include so making change is easy; I only have to edit it once. But, with that method, I can't individually set each page to have a class="active". How can I do this?
You several options, e.g.,
The part that handles navigations can read the request URI directly. This can be done by reading $_SERVER['REQUEST_URI'] (don't forget this may include the query string).
At some point, you must know what page you're on, because you decide which content you display based on that. You can define a function that handles the navigation markup and pass it the name of the current page so that it knows which one it is.
If I'm understanding your question correctly, what I usually do is set a variable before I include the header, like
$current = "home";
And then in the header I'd have an if statement in each link
<a href="/home" <?php if ( $current == "home" ) { echo "class='active'" } ?>>Home</a>
Could be ways to improve it, but it's simple if your menu isn't too big.
In PHP, you can look at the value of $_SERVER['REQUEST_URI'].
In JavaScript, you can examine window.location.

Categories