First of all, to be clear, you're not injecting CSS rules here, but a link to an external CSS file that must be hosted somewhere. Is this really what you want?
- Regarding the risk of XSS injection, you're fine with htmlspecialchars(), as long as you provide the correct encoding of your page as 3rd parameter;
- You should, however, at the very least make a sanity check of the URL (check that it starts with
http://
or https://
, and that it's syntactically valid;
- If your site is on
https
, you must only accept URLs starting with https
, or you'll get an unsecure content warning in your browser;
Other than that, the risks should be very limited. If the link does not point to a valid CSS file, it will likely be ignored. The only real annoyance is the ability for an attacker to make visitors of your site trigger a GET
request on any URL they want.
That being said, I would advise that you allow users to provide CSS rules instead, i.e. what goes inside a <style>
tag. Now if you do this, it's a different story: you have to be sure that the provided CSS code does not contain </style>
, or this opens the door to XSS injections.
If you're following this route, I would advise you to parse the CSS rules provided with a CSS parser such as this one. This way, you can ensure that only valid CSS can be given, which is good for both security and quality.