Css background image name from url variables - php

I have a landing page where I'd like to split test multiple backgrounds and popup overlays.
In the same folders I have images like 01.jpg 02.jpg etc.
The url will be similar to these:
mywebsite.com?bg=01&ov=01
mywebsite.com?bg=07&ov=10
etc...
I'd like to set a default value in case someone reaches the page with the clean url and also take care of security by allowing only numbers in the filename.
Here's what I have put together (it doesn't work):
<?php
if(isset($_GET['bg']){
$bg = (int) abs($_GET['bg']);
}else{
$bg = '01';
}
if(isset($_GET['ov']){
$bg = (int) abs($_GET['ov']);
}else{
$ov = '01';
}
?>
<style>
body {
background-image: url(<?php echo $bg; ?>.jpg);
background-size: cover;
}
.overlay {
background-image: url(<?php echo $ov; ?>.jpg);
background-size: cover;
}
</style>
Can somebody help me with this?

Related

PHP file_exists method not working as expected

I am trying to set the background of the html body dynamically. Basically if a file exists, use it, otherwise use the default. But it keeps using the default regardless of whether the file exists or not.
<style>
body
{
padding-top: 50px;
background-image: url("<?php
clearstatcache();
if(file_exists("/profile_img/".$profileData["ID"]."_bg.jpg"))
{
echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
}
else
{
//echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
echo "/profile_img/default.jpg?". rand(5, 15);
}
?>");
background-size: cover;
background-position: 50% 50%;
}
</style>
I have tried using the file (the commented line) and it works. I can not see why this doesn't work
Some issues:
Using / will be absolute, causing it to look in the root directory.
Always check vars are set before using.
All that's changing is the filename, so you can use a ternary, which will reduce alot of that code.
<?php
$background = isset($profileData["ID"]) && file_exists('./profile_img/'.$profileData["ID"].'_bg.jpg')
? $profileData["ID"].'_bg.jpg' : 'default.jpg';
?>
<style>
body {
padding-top: 50px;
background-image: url("/profile_img/<?= $background.'?_='.microtime(true) ?>");
background-size: cover;
background-position: 50% 50%;
}
</style>
If it's still not working:
Check the file actually exists.

Dynamic CSS with PHP based on database

found a couple answers here on StackOverflow and used them as my models, but I must be missing something. I'm trying to set a couple of background colors dynamically in CSS based on what is in my database, but it's not working - when I check Inspect Element in Chrome, background-color has a line through it and a warning mark for 'Invalid property value'.
Here's my code; it's in two separate files - the first is in the header include file, and the second is in the linked .php / css-esque file.
Header include: [Edited 4/29 to include session code]
session_start();
// check if $_SESSION was set before
if (!isset($_SESSION['email'])) {
header("Location: bad_login.php");
exit();
}
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
PHP/CSS file:
<?php header("Content-type: text/css");
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
EDIT 4/29:
This is the CSS generated:
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: ;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: ;
}
I also echoed the variable back in the html so I know that there should be something in the variable. Should I be opening the database and assigning the variable inside the css.php file?
CSS/PHP is linked this way in header:
<link type="text/css" rel="stylesheet" href="../css/carrier.php">
Instead of using the .css file extension, use .php
in the html file: is it linked to .php?
<link rel='stylesheet' type='text/css' href='css/style.php' />
in the style.php add
<?php
header("Content-type: text/css; charset: UTF-8");
?>
Now you can set up variables for whatever you like:
source
Edit:
Don't forget about session_start(); since you're using sessions (I don't understand how, since nothing gets posted to css/carrier.php you should rather have it in session from a different file & then just use the $companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];).
is this the way your code looks?
<?php
session_start();
header("Content-type: text/css; charset: UTF-8");
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
The answer of yesitsme is correct. Other thing you can do is that each storage changes in the database, run the process of creating this "new" CSS file with the appropriate .css extension.
What if with every request you create a new CSS file?
I mean, you have two paths, when creating the first call to the Web and update it from time to time, either, at the time you keep the data in the database associating it to a script.
With this new CSS and stored is generated through fwrite () and other functions that PHP has to manage files, keep the name of the CSS created in the BDD and then in your place the link as appropriate.

Random background images in wordpress?

I am using WP 3.5.1, twenty twelve child theme and PHP 5.2 on my server.
I am trying to use a php script(that works on my other websites) in order to get random background-image but it's not working:
CSS:
body {
background: url(<?php include ("bg.php"); echo $selectedBg; ?>) no-repeat fixed;
}
PHP:
<?php
$bg = array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg');
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
my php file is in the same folder as the jpg's.
Any ideas?
No errors. If I use background: url(1.jpg); (instead of php) it works fine but obviously shows 1 image.
Small solution:
We know that he have 5 images on the server:
'1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'
So quick tip:
<body style="background: url('pahttoimages/<?= rand(1, 5) ?>.jpg') no-repeat top center;">
i think the CSS file can't explain your PHP code
try body {
background: url(<?php echo '1.jpg'; ?>) no-repeat fixed;
}
As far as I can see, your code is valid.
Except, you should really write the last line like:
$selectedBg = $bg[$i];
No need for quotes here.
I suspect this is what is causing the error:
my php file is in the same folder as the jpg's. Any ideas?
The background-image needs to be relative to the template-file you are using, not the PHP-file. You script will only work if the images are located in the same folder as the template-slices.
In my WP-installation, I have a template located in /wp-content/themes/mytemplate/ and template-graphics located in /wp-content/themes/mytemplate/images/. If I were to use your script, I would need to preappend /images/ before all the backgrounds in your array.
By the way, you should consider installing Firebug on Firefox and inspect the source. Is the background-name parsed into the template? Does loading the image return a 404 not found-error? Is the location and path correct?
background-image: url(<?php include ("bg.php"); echo $selectedBg; ?>);
background-position: fixed;
background-repeat: no-repeat;
Do this:
// bg.php
<?php
return array(
'1.jpg',
'2.jpg',
'3.jpg'
);
// Wordpress CSS
<?php
$imageUrls = include('bg.php');
$imageUrl = $imageUrls[ array_rand($imageUrls) ];
?>
.someClass {
background-image: url(<?php echo $imageUrl ?>);
}
background: url('<?php $a = array('darkred.jpg','red.gif','pink.png'); echo $a[array_rand($a)];?>');

Navigation with CSS and PHP - Image Based Hover Menu (jQuery)

I have a menu that is image based (one yellow and one blue, for example). I designed the buttons in Illustrator and then converted to PNG files. Right now, I'm using CSS for hovering affects.
So when I hover over the image, it changes. So this is good (because it works), but its far from perfect (that's why I'm here)... One of my buttons in CSS looks like this:
.home_menu, .about_menu, .video_menu, .demo_menu, .contact_menu {
float: left;
margin-bottom: 10px;
margin-top: 10px;
margin-left: 10px;
width: 100px;
height: 34px;
display: block;
}
.home_menu {
background: transparent url('../images/buttons/home_but.png');
}
.home_menu:hover {
background-image: url('../images/buttons/home_but_hov.png');
}
The HTML is like started out like so:
<div id="main_menu">
</div>
So basically I'm changing the CSS background image for each class.
Two questions. First, I'm trying to get each menu to be the blue version when on that page. So I wrote a PHP function to do this (in a class), just in case I want to avoid JavaScript. It looks like this:
// Display table and loop through links and images from array
public function print_navigation($image_dir, $ds, $page_nav, $page_nav_alt, $menu) {
$current_file = explode('/', $_SERVER['PHP_SELF']);
$current_page = $current_file[count($current_file) - 1];
$current_page;
//$i = 0;
foreach ($page_nav as $key => $value) {
$menu_output .= '<a href="';
$menu_output .= $key;
$menu_output .= '" id="';
$menu_output .= $menu[$key];
$menu_output .= '" style="background: transparent url(';
if ($current_page == $key) {
$menu_output .= $image_dir . $ds . $page_nav_alt[$key];
}
else {
$menu_output .= $image_dir . $ds . $page_nav[$key];
}
$menu_output .= ');"';
$menu_output .= '></a>';
$i++;
}
echo $menu_output;
}
It seems to work for the Home page ($home variable), but not for the others. I have variables like this (arrays and variables in another file, truncated for brevity):
$menu = array(
$home => 'home_menu',
...);
$page_nav_ylw = array(
$home => $home_but_ylw,
...);
$page_nav_blu = array(
$home => $home_but_blu,
...);
Then I have all the images in variables, referenced to in the arrays, eg, $home_but_ylw refers to the PNG for that button.
The PHP function is a bit odd, because I use the $key for two arrays, which I'm sure is bad. But I'm having a hard time getting it to work otherwise.
Second question is: is there any reason I can't add JavaScript (like jQuery) right on top of this to get me the hover effects so that I can remove it from the CSS? Ideally I'd like to display the buttons with a PHP loop that also handles current page and then do the hover affects with jQuery.
Sorry for the long post. Hope it makes sense.
Thanks in advance!
If you were planning on serving your pages dynamically then I think jQuery would be a much better option. However, if your links are going to separate pages then try something this:
function printNav($Page = "home"){
$HTML = "";
$HTML .= "";
$HTML .= "";
$HTML .= "";
$HTML .= "";
echo $HTML;
}
On each separate page:
<div id="main_menu">
<?php printNav("home"); ?>
</div>
CSS:
.ActiveNav {
background-image: url('../images/buttons/blue_bg.png');
}
.MenuItem {
float: left;
margin-bottom: 10px;
margin-top: 10px;
margin-left: 10px;
width: 100px;
height: 34px;
display: block;
}
.HomeMenuItem {
background: transparent url('../images/buttons/home_but.png');
}
.HomeMenuItem:hover {
background-image: url('../images/buttons/home_but_hov.png');
}
EDIT: If you wanted a different image for each button - I would suggest using a generic button background and hover and putting the text and icons on top of it.
Based on this answer, I was able to find a work around to my problem:
PHP menu navigation
Basically, I used the GET method to get the selected class. This worked nicely. I consolidated my CSS, and was able to get this thing working.
Here is what it turned out like, for one link:
<?php $class = $_GET['selected_tab']; ?>
<div id="main_menu">
<a href="index.php/?selected_tab=home" id="home_menu" title="Home"
class="<?php if(strcmp($class, 'home') == 0) {echo 'selected';} ?>"></a>
CSS like so:
#home_menu {
background: transparent url('../images/buttons/home_but.png');
}
#home_menu:hover, #home_menu.selected {
background-image: url('../images/buttons/home_but_hov.png');
}
Next step is to convert to jQuery.
Thanks Mike GB for your help but it wasn't quite what I was looking for.

Generating dynamic css using php and javascript

I want to generate tooltip based on a dynamically changing background image in css.
This is my my_css.php file.
<?php
header('content-type: text/css');
$i = $_GET['index'];
if($i == 0)
$bg_image_path = "../bg_red.jpg";
elseif ($i == 1)
$bg_image_path = "../bg_yellow.jpg";
elseif ($i == 2)
$bg_image_path = "../bg_green.jpg";
elseif ($i == 3)
$bg_image_path = "../bg_blue.jpg";
?>
.tooltip {
white-space: nowrap;
color:green;
font-weight:bold;
border:1px solid black;;
font-size:14px;
background-color: white;
margin: 0;
padding: 7px 4px;
border: 1px solid black;
background-image: url(<?php echo $bg_image_path; ?>);
background-repeat:repeat-x;
font-family: Helvetica,Arial,Sans-Serif;
font-family: Times New Roman,Georgia,Serif;
filter:alpha(opacity=85);
opacity:0.85;
zoom: 1;
}
In order to use this css I added
<link rel="stylesheet" href="css/my_css.php" type="text/css" media="screen" />
in my html <head> tag of javascript code. I am thinking of passing different values of 'index' so that it would generate the background image dynamically. Can anyone tell me how should I pass such values from a javascript ? I am creating the tooltip using
var tooltip = document.createElement("div");
document.getElementById("map").appendChild(tooltip);
tooltip.style.visibility="hidden";
and I think before calling this createElement, I should set background image.
You seem to be asking two completely independent questions.
First, the way to pass a parameter would be in your <link> tag:
<link rel="stylesheet" href="css/my_css.php?index=3" type="text/css" media="screen" />
When the page loads, the browser will request the css/my_css.php?index=3 page from your server and use the CSS that gets returned.
However, you're also asking about setting this value with JavaScript. That suggests that you want the CSS to change throughout the request. In that case, PHP is absolutely the wrong technology to be using.
Instead, consider adding classes like:
.tooltip-background-1 {
background-image: url(../bg_red.jpg);
}
Then you do not need any dynamic content in the CSS file. Just include all four (or more) rules at once, and use JavaScript to change which class applies to the element.
Finally, if you goal is simply to choose a random background color, you could just let PHP choose the random value, eliminating any need for a parameter or for JavaScript and PHP to interact at all.
I suggest you for improve a part of the code use that:
$bg_image_path = '../bg_';
switch($i)
{
case 0: $bg_image_path .= 'red.jpg'; break;
case 1: $bg_image_path .= 'yellow.jpg'; break;
case 2: $bg_image_path .= 'green.jpg'; break;
case 3: $bg_image_path .= 'blue.jpg'; break;
}
instead of specifying the background image in the css file, try just doing it all with JavaScript. So remove the background-image from the css file and remove all the php and remove the colour (if that is what you want to change when the background image changes), basically anything you need to change, remove from the css and change it with JavaScript.
Then use some code like this:
<html>
<head>
<script type="text/javascript">
var i = 0;
var cols = new Array(8);
cols[0] = "FFFFFF";
cols[1] = "EEEEEE";
cols[2] = "DDDDDD";
cols[3] = "CCCCCC";
cols[4] = "BBBBBB";
cols[5] = "AAAAAA";
cols[6] = "999999";
cols[7] = "888888";
cols[8] = "777777";
var imgs = new Array(8);
img[0] = "img1.jpg";
img[1] = "img2.jpg";
img[2] = "img3.jpg";
img[3] = "img4.jpg";
img[4] = "img5.jpg";
img[5] = "img6.jpg";
img[6] = "img7.jpg";
img[7] = "img8.jpg";
img[8] = "img9.jpg";
function change()
{
document.getElementById("div").bgColor = cols[i];
document.body.background = img[i];
i++;
if(i > 8)
{
i=0;
}
}
</script>
</head>
<body onLoad="setInterval('change()',1000)">
<div id="div">Tooltip</div>
</body>
</html>
This code loops through the array of colors and background images, it will change once per second. It changes the color of the divs background and the backgrounds image.

Categories