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.
Related
The last few days I've been experimenting with defining CSS stylesheet that is configuring the page to be printed out.
This is my final solution, which is working (at least what I can see in the html output):
home.php being called initially:
<?php
$_SESSION['pageWidth'] = 20;
$_SESSION['pageHeight'] = 15;
$_SESSION['pageOrientation'] = "landscape";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<?php
echo "<style type='text/css' media='print'>
.card {
clear: both;
page-break-before: always;
}
.no-print, .no-print *
{
display: none !important;
}
#page : left{
margin: 0.5cm;
}
#page : right{
margin: 0.5cm;
}
#page : top{
margin: 1.5cm;
}
/* https://docs.w3cub.com/css/#page/size */
#page {
size: " . $_SESSION['pageWidth'] + 2.5 ."cm " . $_SESSION['pageHeight'] + 2.5 . "cm " . $_SESSION['pageOrientation'] . " !important;
}
</style>";
?>
</head>
During using integrated php files (called by include "cardGenerator.php";), the session_variables are updated with other values (width, height and maybe orientation, depending on the content).
Unfortunately, even my initial set values are ignored by browsers even though in the browser session, it looks all good:
I've been trying it with chrome, edge and firefox - all of them ending up in ignoring the #page{size: } statement.
Does anybody have an idea or same experiences with browsers?
I've been doing this:
put variable values into session to overwrite these value from any php file at any time and to integrate it into css
put css <style> </style> section into header of home.php which is the "leading" php
trying to print out from chrome, edge, firefox
trying with different width/height values
checked many solutions in stackoverflow
During studying some additional material, I've realized that defining a width and a height actually leads to kind of a landscape/portrait. So this information is obsolete. My working code:
<?php
echo "<style type='text/css' media='print'>
.card {
clear: both;
page-break-before: always;
}
.no-print, .no-print *
{
display: none !important;
}
#page : left{
margin: 0.5cm;
}
#page : right{
margin: 0.5cm;
}
#page : top{
margin: 1.5cm;
}
/* https://docs.w3cub.com/css/#page/size */
#page {
size: " . $_SESSION['pageWidth'] + 2.5 ."cm " . $_SESSION['pageHeight'] + 2.5 . "cm !important;
}
</style>";
?>
So, hopefully, this helps other with similar issues. As well as my approach on passing PHP variables into a stylesheet.
I am showing a table in HTML on my web page where a check mark is shown properly (I am using ✔ for the bold check mark).
I am using classic-asp to display the HTML. The html buildup (tableOutput) is then posted to a PHP script ($output = $_POST["output"]) that uses mPDF.php (version 6.0) to print to PDF the same HTML table and somehow the check mark wont print correctly (%u2714 in printed on my PDF). All the rest of the table is printed correctly, only the check mark has a problem.
I tried adding the Symbola.ttf and Symbola_hint.ttf fonts in the mpdf\ttfonts folder but it didnt do the trick.
HTML (classic-asp):
tableOutput = tableOutput & "<TD class='center pass_x' style='font-family:symbola;'>✔</TD>"
PHP (create_report_pdf.php):
$output = $_POST["output"]; //This is the html buildup tableOutput discussed previously
$header = Irrelevant;
$footer= Irrelevant;
$mpdf = new mPDF( 'utf-8', 'A4-L', 0, '', 5, 5, 20, 20);
$mpdf->allow_charset_conversion = true;
$mpdf->WriteHTML($style,1);
$mpdf->SetHTMLHeader( $header );
$mpdf->SetHTMLFooter( $footer );
$mpdf->WriteHTML( $output );
$mpdf->Output($temp ,'F' );
config_fonts.php (I addded symbola.ttf and Symbola_hint.ttf in the mpdf\ttfonts folder):
$this->fontdata = array (
"symbola" => array (
'R' => "Symbola.ttf",
'I' => "Symbola_hint.ttf",
),
CSS (PHP $style variable points to create_report_pdf.css):
.report-table{
border: 1px solid black;
border-collapse: collapse;
font-size: 7pt;
width: 100%;
}
th,td{
font-size: 7pt;
border: 1px solid black !important;
vertical-align : middle;
}
.center{ text-align: center; vertical-align: middle; }
INPUT{
border-color:#ffffff !important;
}
.pf{ width: 45px; }
.fix-cell{ width: 90px; }
.dr-column, .dr-input{ width: 100px; }
.comments, .comments-input{ width: 130px; }
Thank you very much for your help
There are two possible solutions:
Replacing manually the %u2714 with the respective html entity ✔ by doing the following:
$output = str_replace('%u2714', '✔', $output);
Implement more generic approach that will handle all such special chars. The approach is based on the fact that %uXXXX is a non-standard notation scheme for URL-encoding Unicode characters. So you need to convert %uXXXX notation to HTML entity notation &#xXXXX; and then this can be decoded to actual UTF-8 by html_entity_decode.
$output = preg_replace('/%u([0-9A-F]+)/', '&#x$1;', $output);
$output = html_entity_decode($output, ENT_COMPAT, 'UTF-8');
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?
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.
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)];?>');