Home > Blockchain >  How can I use PHP to display a random image as a background image
How can I use PHP to display a random image as a background image

Time:01-20

I'm trying to learn how to build a website. I've built the index page and here is the PHP and HTML.

<?php
session_start();
$png = array('png1.jpg', 'png2.jpeg', 'png3.jpg', 'png4.jpg');

$random = rand(0,4);
$picture = "$png[$random]";
?>


<!DOCTYPE HTML>
<html>  
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>

<form action="login.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>

</body>
</html>

and here is the CSS where I link to the image file:

body{
  background-image: url('png1.png');
}

I'm running the site on replit.com and here is the png1.jpg:

enter image description here

The background image is not appearing. Only the form is showing.

CodePudding user response:

You appear to try generating a random background image using PHP but then do nothing with that, unless somehow you are hoping that it will exist within your stylesheet? As the stylesheet is a .css file any PHP code within will not be executed by the server so to have a dynamic style you could simply add an inline style tags to the page that sets the body background

<?php

    session_start();
    $png = array( 'png1.jpg', 'png2.jpeg', 'png3.jpg', 'png4.jpg' );

    $random = rand(0,count($png)-1);
    $picture = $png[ $random ];
    
?>
<!DOCTYPE HTML>
<html>  
    <head>
        <link rel='stylesheet' href='index.css'>
        <style>
            body{
                background-image:url(<?php echo $picture; ?>);
                background-size: cover;
            }
        </style>
    </head>
    <body>
        <form action='login.php' method='post'>
            <label>Name: <input type='text' name='name' /></label>
            <label>Password: <input type='text' name='password' /></label>
            <input type='submit'>
        </form>
    </body>
</html>

CodePudding user response:

I am not sure if your image is not showing or if it is showing in the wrong place.

using the css below you will allow you to set your background image properly.

 body {
      background-image: url('png1.png');
      background-repeat: no-repeat;
      background-attachment: fixed;  
      background-size: cover;
    }
  • Related