How To Background Image In Php

In this blog post, we will learn how to set a background image using PHP. While PHP is a server-side scripting language and not directly responsible for the visual appearance of a website, you can still use PHP to dynamically generate the HTML and CSS code to apply a background image to your web pages.

Steps to Set a Background Image using PHP

  1. Create an HTML file with an embedded PHP script to generate the CSS code.
  2. Define the path to the background image in the PHP script.
  3. Use the PHP echo function to generate the CSS code that sets the background image.


Let’s say you want to set a background image for the body element of your web page. The following example demonstrates how to achieve this with PHP:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Background Image Example</title>
        body {
            background-image: url('<?php echo $bg_image; ?>');
            background-repeat: no-repeat;
            background-size: cover;

    <h1>Welcome to My Website</h1>
    <p>This is a simple example of setting a background image using PHP.</p>

In this example, we first define the path to the background image in the $bg_image variable. Then, we use the echo function to insert the value of this variable as the URL of the background-image property in the CSS code.

Additional Considerations

  • Make sure the path to the background image is correct, otherwise, the image will not be displayed.
  • For a responsive web page, you may want to use different background images for different screen resolutions or devices. You can achieve this by using PHP conditional statements to check the screen size and generate the appropriate CSS code.
  • If you are using an external CSS file, you can still use PHP to generate the background image URL. Simply change the file extension from .css to .php, and add the necessary PHP code at the top of the file. Don’t forget to update the link to the CSS file in your HTML file accordingly.

That’s it! You now know how to set a background image using PHP. While this approach may not be commonly used, it can be very helpful when you need to generate dynamic background images based on user preferences, server-side variables, or other factors.