1

I'm following a tutorial to use a PHP variable in a CSS file.

I have the following "style" PHP sheet, style_header.php:

    <?php
   header('content-type: text/css');
   ob_start('ob_gzhandler');
   header('Cache-Control: max-age=31536000, must-revalidate');
   // etc. 
?>

#headerwrap {
    background: url(assets/img/<?= $pic_array[0] ?>) no-repeat center top;
    ...
    }

this file is linked to my main page (index.php) thanks to:

    <link href="assets/css/style_header.php" rel="stylesheet" type="text/css" media="all" />

and the PHP variable is defined in load_pictures_content.php, which is included in index.php before style_header.php is linked:

    <?php
// requête sur la BDD
$result2 = mysqli_query($connexion, "SELECT img_name FROM pictures");
//$row =  mysqli_fetch_row($result);
$pic_array = array();
$i=0;
//stockage de chaque igne dans array + recupération de l'élément 0 = contenu
while($dpic = mysqli_fetch_array($result2)) {

    $pic_array[$i] = $dpic[0];
    ++$i;

}
?>

I get the following error:

    url(assets/img/<br />
<b>Notice</b>:  Undefined variable: pic_array in <b>/home/leem4147/emilien-lecoffre.com/assets/css/style_header.php</b> on line <b>9</b><br />
) no-repeat center top

1 Answer 1

1

You don't seem to understand PHP execution orders correctly. Your code is executed as following orders.

  1. index.php which includes load_pictures_content, style_header
  2. After rendering index.php, style_header.php will be executed because it is specified as a URL for CSS. At this time, style_header.php is executed without load_pictures_content, so you must see errors.

Solution. You need to include codes on load_pictures_content.php in style_header.php

Here is a mockup code. Dynamic CSS

Sign up to request clarification or add additional context in comments.

2 Comments

ty for your answer, i tried this (put the load_pictures_content.php code in <?php ... ?> of style_header.php) but it act like the CSS property of style_header.php don't exist :/
github.com/swdreams/php-dynamic-css I made some test files for you. I would think you can get an idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.