PHP File renaming gone wrong - php

I have 12 css files in my system, and I rename them whenever users want to change style. I store current style in the database, and rename style.css to style$Color.css, renaming Style$Requestedcolor.css to style.css right after that. Here's the code:
if ($_POST['blue'] == "Blue")
{
if(file_exists('./css/styleblue.css'))
{
$old = './css/style.css';
$new = './css/style'.$Color.'.css';
$old1 = './css/styleblue.css';
$new1 = './css/style.css';
rename($old, $new);
rename($old1, $new1);
$newcolor = "blue";
$idnum = "1";
mysql_query("UPDATE company SET Color = '$newcolor' WHERE ID = '$idnum'");
}
}
Problem is, I sometimes (not always, finding it very hard to diagnose when and why) end up loosing a file, while system grabs a completely random .css file, renames it to style.css and writes the correct $newcolor to the database. Maybe the renaming goes too fast? Or should I grab for each of these ifs (there's 12) info for $Color value?

I have a sneaking suspicion that $Color occasionally doesn't get set before you start renaming files, are you verifying that your query completes and returns a result before running the block of code you've posted?
A better idea would be instead of constantly renaming the files you just change the filename in the <link> tag that you output on the page? That way you don't have to worry about the renaming process going sideways, or the new style.css not overwriting the old style.css in the client's cache.
I have a second sneaking suspicion that you're not making full use of CSS inheritance either, given that you're using a generic filename of 'style.css'. A somewhat better approach would be:
PHP/HTML
<? $color = 'blue'; ?>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="theme.<?= $color ?>.css">
</head>
style.css
Contains layout-related directives and default colors, eg:
body {
font-family: Sans;
background-color: grey;
}
#container {
width: 900px;
margin: 0px 20px;
background-color: white;
}
theme.blue.css
Contains just color-related directives to override those previously defined, eg:
body {
background-color: blue;
}
#container {
background-color: purple;
}

Related

PHP How to Echo Across the Whole Page

I have created a skin switcher and it is working great, but the code is messy.
I save a cookie and then for some defined css classes, I append '-userDelectedColourFromTheCookie' to the end of the css class to apply it on the page.
So far, I am adding a short php line to the end of every instance of these classes in the html code and as I have said, it is working.
I would prefer to run the php code just once across the whole page and update all occurrences of an array containing the required classes to append the class as above.
I have this at the top of my page:
<?php
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], array("Blue","Red","Grey","Ochre","Mauve"))) echo $classList."-".strtolower($_COOKIE["Theme"]);
?>
<!DOCTYPE html>
... etc
I am defining an array of css classes, then reading the user colour from the cookie and appending it to the css class.
As and example, the default class might be 'theme-3' but of the user selects the blue skin, then this class becomes 'theme-3-blue' and so on.
But it's not working.
Any help would be appreciated.
Don't mess with the element class lists. Use CSS files to apply the colours you want.
Start with a basic CSS design file:
p {
margin-left:10px
font-size: 12pt;
}
h1 {
font-size: 24pt;
}
div {
margin: 10px;
padding 20px;
}
Then create CSS colour files with different colour selections:
blue.css
p {
color:blue;
}
h1 {
color: darkblue;
background-color: lightblue;
}
red.css
p {
color:red;
}
h1 {
color: maroon;
background-color: pink;
}
default.css
p {
color:black;
}
h1 {
color:white;
background-color:black;
}
Then load the colour theme you want
<?php
if (isset($_COOKIE['theme'] && in_array($_COOKIE['theme'], ['red','blue'])) {
$themeCSS = '<link rel="stylesheet" href="'.$_COOKIE['theme'].'.css">';
} else {
$themeCSS = '<link rel="stylesheet" href="default.css">';
}
Then echo $themeCSS in your <head> just like any other <head> element
** I've used standard HTML elements here to illustrate, but any CSS selectors should work.
I believe you want to change the class names inside the $classList variable by appending the selected color theme from the cookies.
You may use the array_map function to modify all elements of your $classList array.
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
$themeColor = $_COOKIE["Theme"]; // blue
$classList = array_map(function($val) use ($themeColor) { return $val.'-'.$themeColor; }, $classList);
Once you use the array_map function, all elements of the $classList array will be appended with the "-blue".
You can execute and see the output here
http://sandbox.onlinephpfunctions.com/code/6051282e00be1eb7bb7e6a086de20bbcfe9bcc9f
Several good ways to do it. It's a little more complicated with the array of classes but you should be able to adjust this if you need it (not sure why the syntax highlighting is wonky).
Use output buffering and replace at the end:
<?php
ob_start();
?>
<html>
<head></head>
<body>
<div class="theme-1"></div>
</body>
</html>
<?php
$themes = array("Blue","Red","Grey","Ochre","Mauve");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], $themes)) {
echo preg_replace('/class="(theme-[^"]+)"/', 'class="$1-' . $_COOKIE['Theme'] . '"', ob_get_clean());
}
With the array of classes, just do it the same way with output buffering but replace like so:
$replace = array_map(function($v) { return "{$v}-{$_COOKIE['Theme']}"; }, $classList);
echo str_replace($classList, $replace, ob_get_clean());

PHP Check filenames

I've created a simple PHP script which reads .txt files (1.txt, 2.txt etc which each contain dummy text: "Test~Test test test test test test") and produces a html output of each file's content with a little html formatting.
<html>
<head>
<style type="text/css">
body {background-color: #80B2FF; font-family: arial,sans-serif;}
.content {background-color: #ffffff; margin: 35px auto; max-width: 75%; padding: 35px;}
</style>
</head>
<body>
<?php
for ($number = 3; $number>=1; $number--){
$article = $number.".txt";
$data = file_get_contents($article); //read the file
$convert = explode("~", $data); //create array separate by new line
echo '<div class="content">'.$convert[0].'<br/><br/>'; //write value by index 0
echo $convert[1].'<br/><br/>'.'</div>'; //write value by index 0
}
?>
</body>
</html>
This currently works just fine. The problem is that if I was to create the file 4.txt, I would have to hard code the $number variable to 4.
I have tried to automatically initialise $number to the highest number.txt. I need help creating a loop which would use the file_exists() function to test if a file x.txt exists, if it does then increment x and test again. If it doesn't exist, the loop should instead break out and hence I could just say $number=x.
I hope this explanation is clear enough, thank you for your time.
Use glob(), your method is pretty bad:
http://php.net/glob or http://www.w3schools.com/Php/func_filesystem_glob.asp
What you want to do is $arr = glob("*.txt"); and then loop through that array.

PHP Variables in the CSS Stylesheet

I am looking to introduce PHP variables to stylesheets (ie. CSS).
I have worked out that I can print a PHP page as a stylesheet by declaring:
header('Content-Type: text/css');
At the top of the CSS page.
However the variable I am passing is not displaying in the stylesheet.
In this case the PHP variable $css will be '-webkit-', '-moz-', '-ms-', or '-o-'.
And in the stylesheet I want to echo it in front of CSS3.
Originally I was achieving this by having a separate CSS file for each however this would be more efficient and allow me to pass genuine styling from the database, such as background-color and font.
Possible? How?
EXAMPLE PHP File called as a CSS link.
<?php
global $css;
header('Content-Type: text/css');
?>
.wheel {
position:absolute; top:50%; left:50%; height:32px; width:32px; margin:-16px; <?php echo $css;?>transition:opacity 0.3s;
}
.wheel li {
width:3px; height:9px; border-radius:2px; background:#555; <?php echo $css;?>animation:loading 1.2s infinite; position:absolute; <?php echo $css;?>transform-origin:2px 16px; left:16px; opacity:0; box-shadow:inset 0 0 2px rgba(255,255,255,0.4);
}
#<?php echo $css;?>keyframes loading { 0% {opacity:0.2;} 50% {opacity:0.9;} 100% {opacity:0.2;} }
If you just want to be able to use variables in your css (not necessarily php), you could consider using less
You do this the same way you would with HTML:
<?php
header('Content-Type: text/css');
$css = $_GET['css']; // or wherever your're initializing the variable from...
?>
body {
<?= $css ?>border-radius: 3px
}
But, I don't think this is necessary for your use case. It's actually not uncommon to just statically include all the various -*- options in a css file:
body {
-moz-border-radius: 3px;
border-radius: 3px;
}
Just add all effective options, and the browser will determine which are most effective for it. This also means you get to avoid the dull and error prone task of browser sniffing.
SASS CSS extension would allow you to use variables without actually needing to use PHP and the downsides that come with it. Mixins would simplify the generation of vendor-specific style rules.
#mixin vendor-prefix($name, $argument) {
-webkit-#{$name}: #{$argument};
-ms-#{$name}: #{$argument};
-moz-#{$name}: #{$argument};
-o-#{$name}: #{$argument};
#{$name}: #{$argument};
}
p {
#include vendor-prefix(hyphens, auto)
}

PHP in CSS - "If page is in this directory, echo this"

I have several sites on the same hosting package. They’re all in different directories. ( i.e. “htdocs/site1”). I want to be able to have them all share one CSS file.
I was wondering if there is a way to change the color of certain elements based on which directory the site is in.
Ideally I would like to be able to define what directory the page is in and what color to use for each directory. Then in my CSS do something like:
.button { color: <?php echo $color ?> ;}
to each element that gets a color change.
Is this possible and if so, how do I go about setting this up?
thank you
You could add different classes to your body tag depending on the directory:
<body class="<?php echo $dir; ?>">
where the $dir variable is given a different value (let's say $dir = 'site1',...) for each directory...
... And then have something like:
.site1 #button { /*styles*/ }
.site2 #button { /*styles*/ }
.site3 #button { /*styles*/ }
in your CSS file.
You could add a CSS class to the body tag of the HTML document to determine the site. In PHP you would have to find a way to write the correct site into to the document. Do you use some kind of global template?
Just to give you an idea:
PHP:
<?php
// some code
// some logic to determine which site you are on - let's say ...
$site = 'SITE1';
?><body class="<?php echo $site; ?>"><?php
// more code
?>
CSS:
body.SITE1 #button { color: #ff0000; }
body.SITE2 #button { color: #0000ff; }
body.SITE2 #button { color: #123456; }
You could dynamically generate the css file using php, where you'd have
<?php
switch ($_SERVER['SERVER_NAME']) {
case 'www.site1.com':
$color = '#ff0000';
break;
case 'www.site2.com':
$color = '...';
break;
...
default:
$color = '...';
?>
.someclass { color : <?php echo $color ?>; }
This is somewhat inefficient, however. You'd be building a css file just to change a single color each time. Better way is to simply embed the color change in the page's header as an in-line style. That way you don't have to mess with making your server parse CSS files as if they were PHP scripts, and you can put the site-specific css overrides into that inline style in the site's header.
Honestly, I would suggest you add a class to your html tag:
<html class="site1">
And within your CSS, define your css:
.site1 * .button1{ background:#f00;}
.site2 * .button1{ background:#f0f;}
.site3 * .button1{ background:#ff0;}
You can find some more information on this subject here for a PHP approach.

php array getting placeholder from database

i have this designing my table:
<style type="text/css">
tr {
background: <?php echo $colors[$status];?>;
color:white;
}
</style>
and
$status = $row[4];//value is 0
$colors = array("lime", "red");
The value in the database is 0.
The $status variable defines what color the table row should be. However the row is never lime. Is my array wrong or something else?
make sure the order is correct.
the order should be something like this:
<?php
$status = $row[4];//value is 0
$colors = array("lime", "red");
?>
<style type="text/css">
tr {
background: <?php echo $colors[$status];?>;
color:white;
}
</style>
your issue could be due to the fact that $colors was never declared before you started using it
If your css is defined in a separate file like "style.css", then your server won't know to parse php code inside. To do that you'll need to use the ".php" extension on your style file and include <?php header('content-type:css);?> at the top so the browser knows to interpret the css declarations.
Read more about using php in your css files here: http://www.barelyfitz.com/projects/csscolor/

Categories