I'm rather new to PHP programming but I thought I'd do it right from the beginning, so I came across this fine pdf Web Performance Boot Camp where he suggests:
All sites should always prepare for CDNized static content
and this is how:
<img src=”<?php echo CDN(‘/i/left-menu-background.gif’) ?>”
etc., he also gave an example of how the CDN function? should look like:
sub CDN { return #_[1]; }
or (when you finally have your static content on a CDN)
sub CDN { return ‘http://s.company.net’ . #_[1]; }
(but that's not valid php, right? it looks more like perl...)
Anyway, this goes on with how to rewrite the header like:
<link type="text/css" rel="stylesheet" href="<?php echo $this->CDN("c/".$this->css_file) ?>" />
But honestly, I have no idea how to do it right. So, my question is, how to I prepare my (php) site for a CDN? Where do I put the sub CDN function? How should it look in valid php? How/Where do I include it? Do I have to put a
<?php require('../cdn.php'); ?>
at the beginning of every html/php file I create (that uses scripts/css/static images/etc.)? Thanks for reading this.
If you're expecting to use a CDN in the future, this is not a stupid idea.
A simple function would look like this:
function getURL($url) // Name it whatever you want
{
// Choose one of the following:
return $url; // If you're local
return "http://s.company.net/".$url; // If you're on a CDN or static server
}
and the markup:
<link type="text/css" rel="stylesheet" href="<?php echo getURL("c/".$this->css_file) ?>" />
Do I have to put... at the
beginning of every html/php file I
create (that uses scripts/css/static
images/etc.)?
Yes. It might be wise to include some sort of central bootstrap file (some frameworks call it bootstrap.php) for future shared PHP settings that you may need to introduce. That bootstrap file would then, in turn, include the cdn.php.
Related
I'm recently doing a website for a school project. In order to organize my work, I create a tree folder that keeps all the work organized. It is similar like this:
Back-Office
Pages
Home
home_test1.php
home_test2.php
home_test3.php
Login
Folder_Login
login.php
logout.php
Resources
CSS
style_home.css
style_navbar.css
style_footer.css
JS
script_home.css
script_navbar.css
Sections
navbar.php
footer.php
After all, with the require() method available in PHP, I want to call the "navbar.php" file to the "home_test1.php", "home_test2.php" and "home_test3.php", but the CSS style that is connected with the file "navbar.php" ("style_navbar.php"), doesn't display.
I've tried to change the path of the CSS style in the file "navbar.php" when I require() to the other file ("home_test1.php") and the CSS style shows up, but wont display in other file with a different path. How can I make this work dynamically? Sorry for long post and bad English grammar.
Thank you in advance.
You need to set your css and js files with absolute path instead of relative path
$dir = realpath($_SERVER["DOCUMENT_ROOT"]);
<link rel="stylesheet" href="<?php echo $dir.'/resources/css/style_home.css'; ?>" >
Without physically seeing you code it is quite hard to debug however there is an "obvious" answer that I'll suggest as a starting point.
The important thing to remember is that PHP and HTML are processed in completely different places. PHP executes on the server and should be used to build a full HTML "document" which it gives to the client/browser. The client/browser then reads the document provided and renders it according to HTML standards.
Calling require() will tell PHP to get the file and slot its contents directly where it was called and as it is a CSS file it will need to sit within the style tags. With a lot of modern browsers, if you use require on a file outside of the html tags, the content will be dumped at the top of the screen or simply ignored due to invalid syntax.
Alternatively if you would like to simply use tell the browser to include the CSS file, you could use the good old method of using <link rel="stylesheet" href="/path/to/file">. It's good to know when and when not to use PHP.
PS: You have .css files in your JS directory.
In PHP, there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:-
$_SERVER['DOCUMENT_ROOT']
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
<link rel="stylesheet" href="<?php echo $path.= '/Resources/CSS/style_navbar.css';?>" />
?>
I'm a novice php learner, I was experimenting how to link different php files dynamically. While experimenting, I realize I can create variables in my php files and make my template files echoes out the html I need without editing my template files......
for example:
Within about-me.php page, I have included my header.php and footer.php using
<?php include ('includes/header.html'); ?>
<?php include ('includes/footer.html'); ?>
then I create a variable
$page_title = 'CompanyABC';
and echo out in the header.php
$page_title = 'South Asia Exact';
Now my question is can I do this to my inline css also?
for example, I have create a variable, that store all my inline css:
$page_inlinecss = "#SAEcontentR div#certification_certificate {
margin:0 auto 0 auto;
width:580px;
height:464px;
}\n";
then I echo out in my header.php like so:
<style type="text/css">
<?php echo $page_inlinecss; ?>
</style>
I have tried it and it works, but I want to know is it the right way to do it?
There isn't a right way to do inline CSS
Your code will work, it will produce a valid page, and it will look absolutely fine to the user. BUT you shouldn't do it that way.
So, why shouldn't you do it that way?
Maintainability is the main reason that you shouldn't handle CSS this way. It is far easier to manage a separate CSS file than to pick through PHP code looking for CSS rules to change.
It looks like the data you're storing is static, the point of a variable is to store data that can change. Things like the name of the website (Company ABC) are unlikely to change during the execution of the script, so you should include them in the static HTML template.
On top of this are issues like caching (most browsers cache .css files, saving you bandwidth) and accessibility (screen readers may not know how to deal with inline styles & js).
How should you handle dynamic styles?
One way to handle dynamic styles (that is -- styles based on information which will be different on different page loads) with a combination of PHP and CSS is to define class styles in your external document and then use PHP to apply them.
For example, put this in styles.css:
span.greentext { color: #0f0; }
And this in your PHP file:
<span class='<?php echo ($someCondition) ? "greentext" : null; ?>'>Some text</span>
Or, if you have more styles to handle:
Alternatively, you could load a specific stylesheet upon a condition:
<?php if($someCondition): ?>
<link rel="stylesheet" href="styles/conditional.css" type="text/css" media="screen">
<?php endif; ?>
Hope this helps, and please don't use inline CSS, or variables, unless necessary. You'll thank yourself for it when you have to change the site 5 months down the line.
Can you do this? Yes.
Should you do this? Ehh. (No. was a bit harsh...)
Better to store the CSS filename in a php variable, then in the header add:
<link rel="stylesheet" href="<?php echo $this_page_style_sheet; ?>" />
There is no right or wrong in this case.
You may store the CSS in a string and echo it as you see fit. Or you may even embed it in your includes/header.html file. It's up to you.
Personally, if it is a collection of CSS rules, I would keep it in its own CSS file, and just echo the filename when needed.
$css_filename = "/path/to/rules.css";
// ... etc etc
<link rel="stylesheet" href="<?php echo $css_filename; ?>">
This is a beauty and a pitfall of the way the system works. You can do that, it works and it doesn't seem to present any immediate and glaring security issues. I don't know if that was an intended use of PHP, but it works so if it fits your situation you can use it. The pitfall comes when enough of these little workarounds are used that eventually a security issue could arise somewhere, but I don't recall CSS ever being used as a vector for an attack.
You can do this to generate dynamic css
file css.php
<?php
header("Content-Type: text/css");
echo 'p {color:red}';
?>
html (not complete but it should work cross browser)
<link rel="stylesheet" href="css.php" type="text/css" />
<p>This should be red</p>
Some more strict/uptight folks might say that proper CSS doesn't need variables, yadda yadda.
Personally I think if this works, then it's a clever way to add some ease-of-use to CSS. I'm all for it.
I think this should be a fairly simple question for anyone who knows PHP. I am more of a designer and still in the process of learning PHP.
I have a site I built which includes a PHP header and footer include. In the header file (which is used by ALL pages in the site) I have links to CSS files, JavaScript files, etc.
Right now I am using this solution for the links and includes in the header...
http://<?php echo $_SERVER['SERVER_NAME']; ?>/css/style.css
The issue with that is that some of the pages in the site are SSL pages and need to use a HTTPS prefix, not HTTP. That being said, I'm wondering if there is a simple way to link to CSS files, JavaScripts, images, etc. within the header file other than what I'm currently using?
<link rel="stylesheet" href="/css/style.css">
If that won't work for you, write a PHP function.
function base_url()
{
if($_SERVER['HTTPS'])
return "https://mysite.com";
else
return "http://mysite.com";
}
and in your html code.
<a href="<?php echo base_url(); ?>/css/ssl_stylesheet.css">
Or you can use a relative protocol: //<?php echo $_SERVER['SERVER_NAME']; ?>/css/style.css
I use CodeIgniter and i love it, but i don't know whether it's really worth it to do like this:
<link rel="stylesheet" href="<?php echo base_url(); ?>css/main.css" />
<script src="<?php echo base_url(); ?>js/jquery.js"></script>
<script src="<?php echo base_url(); ?>js/functions.js"></script>
...
<img src="<?php echo base_url(); ?>images/dolphin.png" />
Rather than just:
<link rel="stylesheet" href="/css/main.css" />
<script src="/js/jquery.js"></script>
<script src="/js/functions.js"></script>
...
<img src="/images/dolphin.png" />
The first method adds a lot of weight to the page but it's reliable when you decide to use the same app in a subfolder and such.
Which one should i go with?
If you think you might need to move the app to other subfolders (and not other sub domains), it probably is worth using <?php echo base_url(); ?>, however if you can assume that the app will always be installed on it's own domain or sub domain definitely do away with the function call, it adds unnecessary clutter and sends more to the users browser.
It's down to what you think your application will need to do.
In my opinion you should always use base_url() for defining your path because like that you will make sure that your path will always be the right one. If you think that echo function is too dirty, you can always use Template engines like Code igniter built in template parser class or some external like Smarty.
Just thought I'd add some things that has been relevant for me.
As you've mentioned, if you ever need to install Codeigniter in a subdirectory, the / leading forward slash will of course not work. You would have to include the subdirectory name in the path. Personally, this comes up a lot because we'll install redesigns or prototypes in sub-directories. However, this can be nice (if it's applicable) for switching to SSL if you aren't already letting CI auto-detect your base url (as of v2.0.2).
Changing your $config['base_url'] to not include the full domain can be a bad idea. Off the top of my head, this would break links and references in emails sent by your application that use the base_url() function, and in general is likely to cause unexpected results.
Almost every HTML tag you need to use your base url in, like <link> <img> and <a>, is covered by a Codeigniter function. (link_tag(), anchor(), img()). These will take care of the base url for you. (Why they left out <script> is beyond me...)
However, I agree - using the full base url adds a lot of unnecessary page weight, especially in your navigation. Here's what I do to grab the path (in case of sub-directory installs):
// constants.php
$base_uri = $_SERVER['SCRIPT_NAME']; // Always index.php (bootstrap), right?
$base_uri = str_replace('index.php', '', $base_uri);
define('BASE_URI', $base_uri);
You can change this to a function or config item or whatever, I prefer a constant. Then you can use:
<script src="<?php echo BASE_URI; ?>js/functions.js"></script>
This will usually be a long-winded way to say /, but handles the sub-directory issue.
This might seem like a waste of time, but when you have lots of installations using the same codebase, less configuration is better.
As a compromise between readability and flexibility I would do the following:
<link rel="stylesheet" href="<?= site_url('css/main.css') ?>" />
<script src="<?= site_url('js/jquery.js); ?>"></script>
<script src="<?= site_url('js/functions.js); ?>"></script>
...
<img src="<?= site_url('images/dolphin.png'); ?>" />
I'm new to PHP and I'm having a problem when trying to link my CSS files using include.
Basically I need my files to link back to a certain directory no matter how far down the file is. I have tried using
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/sysprogs/required/header.html';
?>
But header.html contains the links to my css files so the directory it ends up looking for the css files in is
http://localhost/SysProgs/software/CSS/style.css
instead of where I want it to go to which is
http://localhost/SysProgs/required/CSS/style.css
I hope that made sense and I hope you can help me
Thankyou for all your help everyone!
I would definitely not use <base>. I've run into many problems with this before. If you use <base>, ALL of your links will become relative to that base value.
Instead, I would recommend setting PHP constants for common directories. For example:
PHP Code:
<?php
define('CSS_DIR', '/SysProgs/required/CSS/');
?>
HTML Code:
<link href="<?php echo CSS_DIR ?>style.css" rel="stylesheet" type="text/css" />
One Idea
Use the full URL in header.html. This will be unambiguous and robust.
<head>
<link href="/FULL_BASE_URL/style/style.css" rel="stylesheet" type="text/css" />
</head>
Another Idea
Use the <base> header tag. This allows you to specify a base URL for links, including CSS, and may require the least work in the short term (see note below).
<head>
<base href="FULL_BASE_URL" />
<link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
More at w3schools
Note: As is noted in the comments below base may ultimately cause more confusion than it is worth.
I like to define both an absolute path and a webroot in a central place in your application:
<?php
define("APP_WEBROOT", "/myapp");
define("APP_ROOTDIR", "/home/www/example.com/htdocs/myapp");
?>
you can then "absolutize" the correct links like so:
<?php echo APP_WEBROOT; ?>/software/CSS/style.css
I prefer this
over <base> because that tag creates confusion and makes code harder to maintain in the long run
over using absolute paths /software/CSS/style.css because those make you unable to install your application in a subdirectory of your choice: You will always be bound to the root directory.
I run into this problem a lot when designing sites. When I have custom CMS, I use the following:
$basedir = "root_directory/";
$basedirPHP = $_SERVER['DOCUMENT_ROOT'].$basedir;
$basedirHTML = "http://".$_SERVER['SERVER_NAME'].$basedir;
I define $basedir so I can move the site to different subdirectories in the server without any effort. The $basedirPHP and $basedirHTML are so I can call on files either with php, or like you mentioned, when linking CSS, JS, etc.
If you're on wordpress, just use the good ol' bloginfo('template_directory'); to do the same in template files.
The first thing for you to understand, is your question has nothing PHP related. It is as simple as just filenames in your HTML questuon. Without PHP it will remain the same. Just use absolute path to your CSS file
And another thing to think of: consider to accept some questions.