PHP session is not read in css file - php

I have two files, one is a php file where a session is set, the source is included below.
An .htaccess file is in place to make sure css will be parsed like a php file,
I have verified that this works, but no session data can be read from style2.css
index.php:
<?php
session_start();
$_SESSION['bgimg'] = 'picture.jpg';
?>
<head>
<meta charset="utf-8">
<title>Index</title>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
....
the other is style2.css:
<?php
session_start();
header("Content-type: text/css; charset: UTF-8");
print_r($_SESSION);
?>
body {
background: #fff;
background-image: url("<?php echo $_SESSION['bgimg']; ?>");
}
....

I think your session cookie might not be sent along with .css requests, so the session cannot be fetched.

css will be parsed like a php file,
This is a terrible idea!
Instead use mod_rewrite to rewrite style2.css to a PHP script
RewriteRule ^style2\.css$ generate_style.php
Other than that your session code looks fine, maybe PHP is just confused about the .css file.

In general, passing css files though the php interpreter is not the best idea.
Css is meant to be static, cached data with styling information.
As it seems that you want to dynamically set a background image of one specific element, I suggest using the style attribute in html like so:
<body style="background-image:url(<?= /* php code here */ ?>);"></body>
If, on the other hand, you want to change styling based for example on your login status, I suggest using html class attributes as flags and using the class selector in css:
Example CSS:
p {
/* formatting without login */
}
.login p {
/* formatting with login */
}
Example php
<!-- snip -->
<body <? if(/* check login here */) { echo 'class="login"'}?> >
<!-- snip -->

Related

How can I add style effect for elements inside of echo using classes?

I have a problem with adding style effect for div elements inside of echo, here's my code:
<?php
$db= new PDO('mysql:host=localhost;dbname=myDataBase;charset=utf8','user','password');
$response=$db->query('select * from users order by ID desc limit 10');
while($line=$reponse->fetch())
{
echo
'<div class="elements" ><h1>'.$line['pseudo'].'</h1></div>
<div class="elements">'.$line['message'].'</div>
</div>';
} ?>
and the stylesheet:
.elements{
display: inline-block;
padding: 10px;
}
when I execute it, it doesn't work.
This is pretty easy. Just inline your php as needed into the html code to display on the page. For Example:
<?php
Inlcude your php and queries here in this block
?>
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<?php echo '<div class="elements">the rest of your php code goes here</div> '; ?>
</body>
</html>
This is just bare bones basic code to show you what I am talking about. So your custom css would live in the styles.css file. Once you echo out what it is you want in php, then it will inherit those styles. You can inline php as much as you want throughout the file. Just name it file.php or whatever you want.
This will allow you to do what it is you are asking. Of course you could reverse this and echo out the html from start to finish if you really wanted too, but it would be easier to just add the relevant connection info for php and query at the top of the page before any html and then echo out the specific information you wish inside the html below the main php code.
Also I noticed you have one too many closing div tags at the bottom of your echo statement. As others have already commented, you have some other errors as well.

Using a PHP variable in included file evaluates to NULL in included file

I am trying to process some CSS using PHP. The CSS I want to process is page-specific and so I want to set a variable in my index.php to only echo the CSS when the variable is set.
index.php
<?php
$name = 'index';
?>
<?php
include 'inc/header.php';
?>
header.php
<head>
<meta charset="utf-8">
<title></title>
<?php include 'import.php'; ?>
</head>
import.php
<link rel="stylesheet" href="css/styles.css.php" type="text/css" />
The header is properly set for this file. and the CSS is interpreted.
styles.css.php
.jumbotron {
background-image: url(../img/jumbotron.jpg);
<?php
if ($name === "index") {
echo("height: 50VH;"); /* Does not echo anything*/
}
var_dump($name); // Evaluates to NULL
?>
}
How can I make sure $name is set to it's value, as set in index.php?
EDIT: My final solution was to make an object from the stdClass and add the variables I needed as attributes to the object. putting a GET request in the link to the CSS file which was the Base64 of the JSON string of the object.
The <link> tag makes an HTTP request for a file totally independent of the PHP pages that are including each other, so $name is not available in styles.css.php.
To do it this way you need to link the style sheet something like this to pass $name as a get variable:
<link rel="stylesheet" href="css/styles.css.php?name=<?php echo $name; ?>" type="text/css" />
Then in the style sheet styles.css.php use $_GET['name']:
if ($_GET['name'] === "index") {
echo("height: 50VH;");
}
The problem is that you are linking to that styles.css.php from inside the rendered html. This means that page will be fetched in a separate request (as you can se when you inspect the page). This request never passes trough your index.php, and so the $name variable will not be set.
I would advise you to include the css in the rendered HTML inside a style block. It should be as easy as changing your import.php to this:
<style>
<?php include 'css/styles.css.php' ?>
</style>
This also has the added benefit of reducing the number of requests the browser has to make, and should therefore speed up the page.
This is btw not a very standard method of using css. I believe it would be better to add some sort of id (or data attribute) on your body tag that indicates the name of the page you are on. In the css file (that does not run trough php, just a standard css file), you could then do something like this:
.jumbotron {
background-image: url(../img/jumbotron.jpg);
}
#index .jumbotron {
height: 50vh;
}
The file styles.css.php does not know about the $name variable - that's why it is null when doing the var_dump($name). With your <link> you just output the content of your style.css.php as plain html/css. You need to do either an include_once('styles.css.php') or a require_once('styles.css.php') so that you can properly evaluate the $name variable.
You are having an HTML page generated by index.php. This tells the browser to load the external style sheet at the line <link rel="stylesheet" href="css/styles.css.php" type="text/css" />. Loading external data by the browser is a completely new request. Thus the PHP file generating the style sheet does not know anything about the variables declared in the script serving the HTML page.
Actually the variable $name is unset. Since it is given as argument by reference to var_dump (the builtin function is declared to take arguments by reference), the reference results in null.
If you want to distinguish between different style sheets in only one PHP script, append a GET parameter to the URL as query:
<link rel="stylesheet" href="css/styles.css.php?name=<?PHP echo $name;?>" type="text/css" />
Take that parameter in syles.css.php:
<?php $name = isset($_GET['name']) ? $_GET['name'] : ''; ?>

PHP Variables in CSS not working

I have the following code for my html file:
<html>
<head>
<link rel='stylesheet' href='css/style.php' media = "screen"/>
</head>
<body>
<h1 id="foo">My h1 foo element</h1>
</body>
<html>
And for my php file:
<?php
header("Content-type: text/css; charset: UTF-8");
$asd = '#0000ff';
?>
h1#foo {
color: <?php echo $asd;?>;
}
I've followed some tutorials and this is the simplest one i could make but somehow the output is not working the way it should be. Did i miss anything?
P.S. if i was gonna use php variables in css, can it be sort of dynamic? i mean inside the php body, can i overwrite the value of the php variable used in css and the output would change?
Help would be much appreciated ty!
Works fine for me ^^
Use this syntax:
cssman.php
<?php
ob_clean();
header('Content-Type: text/css');
header('Cache-Control: no-cache, must-revalidate');
error_reporting( 0 );
// These are just to show you can use dynamic values and such:
$type = isset($_GET['type']) ? $_GET['type'] : '';
$theme = isset($_GET['theme']) ? $_GET['theme'] : '';
/** Simply print or echo your css here **/
ob_end_flush();
?>
Try your output first, by navigating to the .php file manually. If there is no content at all, there is most likely a mistake in the PHP code, for debugging you could add error repporting (don't forget to also ini_set('display_errors',1), else errors will only be logged).
Then add it to your view:
your view
<style type="text/css">
#import "/Library/Stylesheets/cssman.php?type=cms" screen;
/* any aditional files here aswell */
</style>
you can do it like
echo"
<style>
h1#foo {
color: ".$asd.";
}
</style>
";
Firstly, to include a php file this syntax is absolutely wrong:
<link rel='stylesheet' href='css/style.php' media = "screen"/>
To include a Css file we use following syntax:
<link rel='stylesheet' href='css/style.css' media = "screen"/>
and include a php file we use:
<?php
include_once "a.php"; // this will include a.php
?>
Instead of using PHP to manage the CSS, you may want to consider one of the CSS preprocessors which are specifically intended for that purpose. It also dissociates your client side code from the server side technology.
http://lesscss.org/
https://learnboost.github.io/stylus/
http://sass-lang.com/
Another approach worth considering is to break up the CSS into several files. You can have a common file that applied to all pages on all devices, one that contains the colors, another that manages the layout, perhaps some device specific ones.
The code you post works as expected. The title with id=foo goes blu. The only problem is that it doesn't use the .css extension for a css file. To solve this you could put in css folder a .htaccess with instructions to Apache Web Server to use Php interpreter also for the css files (look this link).
However probably for dynamic-ly change it from php, you mean change the value (e.g after a user input or some other events).
BUT If I understand well your question the answer is no.
Php can only preprocess your page, it can't modify dynamicly your page after it is loaded by the browser from the user. In addiction, using the code above your variable $asd can only be changed in the style.php AND before that it is used in the code.
I suggest you to use javascript instead, it's a lot easier. Use some javascript library like jQuery, to that kind of job.

Store CSS in PHP variable?

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 need insert some PHP code in style sheet

In my css
div.image {
width:<?php echo get_image_size( $size[1] ); ?>px;
}
The size is stored in an array so i called $size[1] to here...
I am beginner in php...
any one pls help?
Better solution is to set a header for the css / php file in my example cssfile.php:
<?php header("Content-type: text/css"); ?>
Then you can use the php file as style.
<link rel="stylesheet" type="text/css" href="cssfile.php?param=1" />
Then you should get the output on your site. But with that solution you should be very careful if you have a lot of traffic. On every site call your PHP interpreter is used to deliver that file.
Yes for this particular instance if you just need php on this one line it is best to insert in the head of your html instead of having php make a whole css file for you.
<style type="text/css">
div.image {
width:<?php echo get_image_size( $size[1] ); ?>px;
}
</style>
PHP should NOT be creating your static assets unless absolutely necessary. You will notice performance hit if traffic gets high.
Change the extension to .php and then in your stylesheet put:
<?php header("Content-type: text/css"); ?>
Then you can use PHP inside your stylesheet.
Maybe you should use this:
<div class="image">
<img src="image.gif" />
</div>
CSS:
div.image img{
width: 100%
}
The problem with putting style inside html is that everything get messed. You should try to separate html from css and js as much as possible.
Also, from my expirience, this is not a good practice to use php in css or js files.
Consider reviewing your html layout to optimize this.
One way is to move that particular piece out of the .css file, and insert it in a PHP document that has access to the get_image_size() function. For example, you may have a template that is parsed as the header. You could then surround this piece in <style> tags.
For that you need to use like this
change your css file as css.php, and use stylesheet include like this
<link rel="stylesheet" type="text/css" href="css.php?opt1=<?php echo get_image_size($size[1] ); ?>" />
In css.php file
div.image {
width:<?php echo $_GET['opt1']; ?>px;
}
try this

Categories