No, it is not safe. This approach is vulnerable to XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery) attacks. Number of ways to construct possible XSS attacks with img
tags is huge. Have a look at OWASP list Malformed img tags just to give you an idea.
You may say that escaping can help you. Yes it is, but escaping alone does not guarantee XSS prevention. Here is what OWASP (The Open Web Application Security Project) recommends in general:
You MUST use the escape syntax for the part of the HTML document you're putting untrusted data into
Plus check what data is allowed (white list) instead of checking endless list of not allowed data.
Here is OWASP's XSS prevention cheat sheet.
OWASP also released a library ESAPI
to be used for escaping in the right context.
But let's say you are done with XSS. With CSRF malicious user can construct legitimate request inside your img
tag for updating some user's profile. And let's say such user comes to see this profile and all of the sudden his/her profile is updated! In this case you will probably need to generate "challenge" / validation token associated with user's session which will be attached to each user's request.
My recommendation is either use external trusted service like gravatar or implement upload.
If you do want to use user's input then I strongly encourage you to familiarize yourself with ESAPI library for this case and OWASP XSS and CSRF prevention cheat sheets.