Use CSS to define print page - php

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.

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.

Stylized HTML table with vertical scroll inside tbody

today I experimented with HTML tables and populating them from a MySQL database. My code worked well for what I needed and as is the table looked something like this:
http://codepen.io/anon/pen/ogYRwj
However I ran into a major problem when actually integrating it onto my website. I use the include statement to display my table as well as my menu to swap between all my webpages. The table was displayed like this:
So I experimented with the width of the tbody.td element and I ended up changing this code:
thead th,tbody td {
width: 20%;
float: left;
border-right: 1px solid black;
}
to this:
tbody td{
width: 10%;
float: left;
border-right: 1px solid black;
}
thead th {
width: 20%;
float: left;
border-right: 1px solid black;
}
And somehow, it freakin' worked! But the lines between the thead.th elements didn't line up with the lines of the tbody.td elements on other devices such as my android, but it worked:
The code works when I include it using the PHP statement include /path/to/file.php, but now if I try to directly view /path/to/file.php it looks really strange, similar to the first image above!
Now I can't figure out what is wrong with the first version and how to display it properly on other devices such as Android?
Please come to rescue CSS and PHP wizards!
(EDIT:
The HTML output is pretty much identical to the local except
with results from the MySQL database.
The table is put into a PHP file where I link to the CSS file using
<link rel="stylesheet" type="text/css" href="path/to/style.css">
I have one main PHP file (index.php) in which I include the PHP file containing the HTML table (logs.php) using a function called getPage.
This is the code for index.php:
<?php
require_once(dirname(__FILE__) . '/functions/functions.php');
getPage('includes','home');
?>
<html>
<head>
<title>Fågelmatare</title>
</head>
<body>
<h3>Fågelmatare</h3>
<hr />
Home |
Logs |
Videos |
About
<hr />
<?php
if(!isset($_GET['page'])){
getPage('includes','home');
}else{
getPage('includes',$_GET['page'], 'home');
}
//switch($_GET['page']{
?>
</body>
</html>
I click on the Logs hyperlink to display my table (in logs.php).
In functions.php
<?php
function getPage($dir, $filename, $default = false){
$root = $_SERVER['DOCUMENT_ROOT'];
$path = $root . '/' . $dir;
if(is_dir($path)){
if(file_exists($path . '/' . $filename . '.php')){
include $path . '/' . $filename . '.php';
return true;
}
if(file_exists($path . '/' . $filename . '.html')){
include $path . '/' . $filename . '.html';
return true;
}
if($default){
if(file_exists($path . '/' . $default . '.php')){
include $path . '/' . $default . '.php';
return true;
}
if(file_exists($path . '/' . $default . '.html')){
include $path . '/' . $default . '.html';
return true;
}
}
}
return false;
}
?>
Here is the source code for logs.php
I'm using nginx as my web server, running on a Raspberry Pi.
)
I have another approach, although cross browser support still isn't very good. It uses position:sticky so you'll need to test in Safari or enable experimental flags for position:sticky.
Here's the experiment:
http://codepen.io/jpdevries/pen/vLVbpQ?editors=1100
The idea is that you wrap the <table> in a <div>, set that <div> to position:relative then simply set the <thead> to position:sticky;top:0;.
You can then just set the max-height and overflow on the wrapper <div> to make that scrollable. As it scrolls, the <thead> will stick to the top.
It is admittedly sort of a "cheap trick" because as you can see below the scrollbar starts at the top of the <table>, not the top of the <tbody>. It is quick and easy though and should be more relevant once browser support stabilizes.

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)];?>');

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