I am just wondering what will be the best way to import multiple css files into php header. Currently four css files are linked to different pages which are being converted into 4 different php header and then being called like require_once DIR . '/../templates/header1.inc.php'; is there anyway i can merge them in to one file with function as i am only at beginner level i am definetly getting something wrong here is what i have tried.
function aboutAction()
{
$pageTitle = 'About Us';
}
if ($pageTitle== About Us)
{
require_once __DIR__ . '/../public/css/style4.css';
}
Thanks
I ususualy do something like this:
<?php if(condition) { ?>
<link rel="stylesheet" href="..
/* or any other html code */
<?php } ?>
The CSS will be included only if the condtition is true.
Related
Currently I am building a website in which I am trying to have one location (e.g. header.html or header.txt) to edit content on multiple pages (e.g. each page has the header). I assumed I could easily do this using PHP, importing the html code into the pages using
<?php
echo file_get_contents("header.txt");
// or echo file_get_html("header.html");
?>
Does not seem to be working. Any suggestions on how to do this? I want to be able to edit the header across all pages from one location.
Take care!
EDIT: Okay so I think I am making a simple mistake that prevents the php to run. Just to lay out what I have and what I want to do:
1: I have a piece of code that represents the header that I want to include on multiple pages. This is currently saved in a header.html file.
2: I have a webpage saved as trial.html where I am trying to place that piece of code using php.
Am I forgetting something?
You are making it too complicated:
<?php
require_once('header.php');
It does not matter if header.php contains just html, just php, or some mix of both.
Use PHP files, no plain html or txt because PHP can be protected to prevent directly access, include more parameters and your project can be more modular.
When you include(or require) php files, those are included in the main file before page loads (server side), so you can have more variables in it.
header.php
<?php
echo '<title>Welcome</title>';
body.php
<?php
echo '<h1>Hellow world!</h1>';
$custom_page = 'page 01';
footer.php
<?php
echo '<p>My site footer for ' . $custom_page . '</p>';
index.php
<?php
// debug errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Note: __DIR__ is absolute path for current file (index.php)
// if you have to go up one dir:
// include_once __DIR__ . '/../your_file.php';
// if you have to go down one dir:
// include_once __DIR__ . '/subdir/your_file.php';
/* more code */
?>
<html>
<header>
<?php include_once __DIR__ . '/header.php'; ?>
</header>
<body>
<?php include_once __DIR__ . '/body.php'; ?>
<?php include_once __DIR__ . '/footer.php'; ?>
</body>
</html>
Rendered HTML for index.php
<html>
<header>
<title>Welcome</title>
</header>
<body>
<h1>Hellow world!</h1>
<p>My site footer for page 01</p>
</body>
</html>
Recommended reading first page on google result:
PHP Getting Started
How To Start Programming
Getting Started With PHP: Basic Scripts
Problem ended up being in the path towards the file I wanted to include, as well as a multitude of other issues:
header.html -> header.php
index.html (page) -> index.php
get_contents -> include
include('/path/file') -> include 'path/file'
add set_include_path($_SERVER['DOCUMENT_ROOT']);
Thanks everybody for you input!
Currently I am working on a site CMS using Yii Framework, where the user can edit the main background color used in the site. When I load the page, I need to query the CSS value (background colors) from the database, put the result to Cookies, and then use those values in my CSS file.
To use PHP variables and Cookies in the CSS file, I renamed the CSS file from main.css to main.php and add: header("Content-type: text/css; charset: UTF-8"); on the top.
The problem is, when I opened the page for the first time, the colors I get from the database are not loaded. I use inspect element and checked the CSS file, and the background color definition is not there. It only appears after I refreshed the page once.
Please tell me what did I do wrong? Any help is appreciated. The relevant code is provided below.
Query and Cookies insertion in protected/components/Controller.php:
public function beforeControllerAction($controller, $action)
{
if(parent::beforeControllerAction($controller, $action))
{
$prog = Programs::model()->find(array(
'condition'=>'id_program = :program',
'params'=>array(
':program'=>Yii::app()->params->programCode,
),
));
Yii::app()->request->cookies['color1'] = new CHttpCookie('color1', $prog->main_color1);
}
}
The CSS file:
<?php
header("Content-type: text/css; charset: UTF-8");
$color1 = $_COOKIE['color1'];
?>
#header
{
background-color: <?php echo $color1; ?>;
}
Based on what you have stated, there re two probabilities
1. Your cookie value is set after your main.php is requested
You should have your css file, main.php loaded AFTER you have set the cookie.
In order to do that you can use the Controller::beforeRender. In your protected/components/Controller.php you can have this
public function beforeRender($action)
{
$color = Yii::app()->request->cookies['color1'];
$prog = Programs::model()->find(array(
'condition'=>'id_program = :program',
'params'=>array(
':program'=>Yii::app()->params->programCode,
),
));
Yii::app()->request->cookies['color1'] = new CHttpCookie('color1', $prog->main_color1);
return true;
}
Just be sure that nothing bad (like loading the css) happens at that find. In case of overwrite.
2. Your css is cached
In order to have your css loaded dynamically in the place you load main.php (probably your layout) you should add something like this:
<link rel="stylesheet" type="text/css"
href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.php?q=<?php echo microtime(1);?>">
This way you can be sure that your css is loaded dynamically. However this way is just like having inline <style>s . Your code is a bit more organized and a bit more time consuming.
I have several files with a header and a footer, let's say file1.php, file2.php and file3.php
These files include() the files header.php and footer.php.
Now the concern is this... Each page has to load a general header content with certain css styles, but also a -specific- style for such page. This also happens on the footer: it loads a bunch of scripts for all pages, but a specific script for a specific page.
How can I achieve this?
I certainly don't want to put the specific script on the specific page because it might not only be attached to one, but several ones, the js script or the css style can be attached to five or ten pages...
I was thinking a switch() for each case in the header or footer page, then any conditional (such as $_SERVER['PHP_SELF']) in the other pages, but how can I do the include thing? is it include() what I'm looking for?
Thank you.
This is pretty much beyond the scope of Stackoverflow but why not.
Switch inside the template
I see you added that you were thinking of using a switch. Here is an example of something simple you could do.
header.php
<html>
<head>
<title>...</title>
<?php switch(basename($_SERVER["SCRIPT_FILENAME"], '.php')) {
case 'file1': ?>
<script src="file1.js"></script>
<?php break;
case 'file2': ?>
<script src="file2.js"></script>
<?php break;
}
?>
</head>
<body>
Just sample code in-between the case and break. This code initiates a switch on the file name, file1.php would be 'file1'.
Output Buffering
What else you could do is output buffering. Let's say you have a template at file1.tpl.php, then you have header.php. Inside file1.php, you could do this:
ob_start();
include "file1.tpl.php";
$content = ob_get_clean();
include "header.php";
Everything processed from file1.tpl.php will be stored in $content. Then inside header.php, you load $content where you see fit:
<html><head><?= $content ?></head><body>
A simple implementation might go like so:
Define a global styles array (say, in a config.php file that gets included on every page), which holds an array of CSS files that can be load:
global $styles = array(
"foo" => "/styles/foo.css",
"bar" => "/styles/bar.css",
);
with the value holding the path to the relevant CSS file.
At the top of the page in question, setup a variable to determine which CSS files to include:
$activeStyles = array('foo');
Then, in your header.php, check for the existence of the variable, and whether or not it contains any values:
<?php
if(isset($activeStyles) && count($activeStyles) > 0) {
# iterate through the array, generating the appropriate <link /> tags
foreach($activeStyles as $styleKey) {
?>
<link rel="stylesheet" type="text/css" href="<?php echo $styles[$styleKey] ?>" />
<?php
}
}
?>
You would use the same concept for scripts.
In my file index.php I have included this text from another file.
<title>
<?php
$title = "";
if (basename(__FILE__, ".php") == "index") {
$title = "Home";
} else {
$title = ucfirst(basename(__FILE__, ".php"));
}
echo $title;
?>
</title>
And I guess you can see what i does, and if not, then it's supposed to set the title to the basename of the file. So say you have a file called downloads.php, then the title with this script would be Downloads. But I have this problem which I don't know how to get past. When I include the text via.
<head>
include "filename.php";
</head>
And my problems is when I include the text, the 'script' runs before it includes. Say if the name of the file you included is filename.php and the main page where you have included the text is main.php, the header would be Filename and not Main. And the reason why I want to include the text, and not just paste directly into main.php is because it's much easier to edit if you have multiple files where you need the exact same code.
I hope you understand what I'm asking, and that you are able to help me.
Try $_SERVER['SCRIPT_NAME']:
if (basename($_SERVER['SCRIPT_NAME'], ".php") == "index") {
$title = "Home";
} else {
$title = ucfirst(basename($_SERVER['SCRIPT_NAME'], ".php"));
}
It looks like you're trying to set up a simple system for breaking your pages up into "subpages". Good idea. But rather than relying on the filename, why don't you set a variable? For example:
In page_title.php:
<?php
echo "<title>" . $title . "</title>";
In index.php:
<?php $title = "Home"; ?>
<head>
<?php include "page_title.php"; ?>
</head>
In some_other_page.php:
<?php $title = "Some Other Page"; ?>
<head>
<?php include "page_title.php"; ?>
</head>
And the same for any other pages you want...
In fact, you probably want to encapsulate the whole <head></head> section of your page.
Finally, rather than reinventing the wheel, you might want to look at some of the templating engines out there for PHP. I like Smarty, but there are others. These templating engines make it possible to write template files (including other template if necessary) and make it easy to simply pass variables to the template & render your HTML.
Here is what I have. I have an index php page sitting on my /root/ folder with the following code:
index.php
require_once("access/$template/head.php");
My functions page has the following configuration for the $template code:
funcs.php
function getTemplateFiles() {
$directory = "models/site-templates/";
$languages = glob($directory . "*");
return $languages;
}
My head php page has the following code:
head.php
<link rel='stylesheet' href='$template/css/style.css'>
My question is what code can I add to my index page that will communicate with my head page, a code before my $template that will include the file location of my php page.
Example 1
$include_dir/$template/css/style.css'>
My question being is how can I include the path of my index page so that my head page will read as html like so?
default, does not work $template/css/style.css
need it like this only for the index page access/$template/css/style.css
Replace your code
<link rel='stylesheet' href='$template/css/style.css'>
Use this
<link rel='stylesheet' href='<?php echo $template; ?>/css/style.css'>
I'm not quite sure whether I understand your problem correctly, but these two methods might help:
$currentDir = dirname(__FILE__);
$currentDir will be the path on your server to the file you're currently in. So if you have a structure like this:
/access/functions/myFunction.php
and you're calling this method from myFunction.php, $currentDir will return '/access/functions'. If the file to be included is in the same directory-path, you can include it like this:
$includePath = $currentDir."/myFile.php";
Another way of determining a target directory is using:
$docRoot = realpath($_SERVER["DOCUMENT_ROOT"]);
$docRoot will be the top-directory of your website (usually something like /usr/www/username/public_html/)
Using this, you always know what your top-directory is and then you can include files like this:
$includePath = $docRoot."/models/site-templates/myTemplate.css";