I have a logo div that I want to use my logo image as the background for, such as:
.logo {
background: #FFF url(images/logo.jpg);
}
However, on a settings page in my script, I would like to have a text input field to specify what the image URL is for the background image.
How can I set the background image for this div as the inputted image URL without having to do:
<div><img src="/images/logo.jpg" /></div>
(The script is written in PHP)
Here are two options to dynamically set a background image.
Put an embedded stylesheet in the document's
<head>
:Define the
background-image
CSS property inline:Note: Make sure to sanitize your input, before saving it to the database (see Bobby Tables). Make sure it does not contain HTML or anything else, only valid URL characters, escape quotes, etc. If this isn't done, an attacker could inject code into the page:
I think you can set the background image dynamically using javascript as given here.
If you prefer not to use javascript, why can't you use inline
style
attribute.ex
That's entirely js and jQuery, because I don't know PHP, but it's a solution!
You either need to generate the css from a PHP script (somewhat advanced), or use inline styles to do the trick. Ex:
This is incredibly insecure, but the most concise answer I can give..