0

So I am trying to get it do it will choose either 1.jpg 2.jpg or 3.jpg. My guess is I am doing this wrong but I am getting no php errors nor is my IDE telling my that my CSS is wrong, so I have nothing to go on.

Code:

HTML/CSS:

<html>
    <head>
        <link rel="stylesheet" href="css/styles.css" type="text/css" media="all">
        <script type="text/javascript" src="js/jquery-1.4.2.min.js" ></script>
        <?php
            include 'php/backgorundlogic.php';
        ?>
        <style>
            body {
                background:url($bgset);
                background-size:cover;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <input class="searchbar" type="text" />
        </div>
    </body>
</html>

PHP:

<?php
    $rbg = mt_rand(1, 3);
    $ext = '.jpg';

    $bgset = 'img/' + $rbg + $ext;
?>

DEMO: here

2
  • Are you sure $bgset is a valid image filename ;) Commented Feb 8, 2013 at 21:04
  • 1
    Just checking, did you intend to include backgorundlogic.php, or backgroundlogic.php? Commented Feb 8, 2013 at 21:05

3 Answers 3

4

use . instead of +

<?php
    $rbg = mt_rand(1, 3);
    $ext = '.jpg';

    $bgset = 'img/' . $rbg . $ext;
?>

and change this line

    <style>
        body {
            background:url(<?php echo $bgset; ?>);
            background-size:cover;
        }
    </style>
Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is indeed another problem. However, consider explaining the difference between the two operators for the OP's benefit.
2

This line:

background:url($bgset);

Should be this:

background:url(<?php echo $bgset ?>);

Right now the PHP engine is passing $bgset through as plain text since it is not in a PHP script context. You might consider being a bit more future-proof and HTML-escape the value as well:

background:url(<?php echo htmlspecialchars($bgset) ?>);

2 Comments

How do I set two answers as the answer?
@user2014751 You can't. In this case it may be appropriate to refrain from selecting a correct answer unless it addresses all of your problems.
0
 background: url('<?php $a = array(‘anyfile.jpg’,'anyotherfile.gif’, ‘somefile.png’); echo $a[array_rand($a)];?>');

or if your image names conform to something with an integer on the end, eg. clouds3.png

 background: url('/images/lm/clouds<?php echo rand(0,10)?>.png') ;

Comments

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.