Jump to content
Larry Ullman's Book Forums

Preg_Replace To Recognize Hyperlinks In Forum Body


Recommended Posts

I am using alot of the code when creating my forum and I am having an issue I can't seem to figure out. How can I change or add a preg_replace to validate the body of a forum post and create a link when one is entered by a registered user? I want to be able to do this but still prvent against XSS attacks.

Link to comment
Share on other sites

There are a couple of approaches you can take here. (Actually, there are probably more than a couple, but I can only think of a couple.)

 

The first and probably simpler technique is to force the user to put [link][/link] tags or the like around links to make them active. By doing so, you can easily transform a static URL into a hyperlink. If you need details about the actual preg replace to do this, just ask. As a standard requirement, before running the preg replace, you should probably run htmlspecialchars or the like on the entire post to avoid any rogue JS from causing trouble.

 

If you're using a WYSIWYG editor for your posts, you can add an option that, when you highlight text and click a button, [link][/link] tags are placed around the highlighted text. I'm not sure, but I think this forum uses very similar technology.

 

The more complicated and hard-to-handle solution is to transform URLs to hyperlinks without [link][/link] tags. I personally don't like this though, as every browser has slightly different ways of interpreting hyperlinks, and to catch every possibility, you'd have to be intimately familiar with the specs of each browser in this regard in order to write a regex that's robust enough to catch everything.

Furthermore, you might run into the problem where a user might not want certain URLs turned into hyperlinks, but if you blindly convert them all, then the user has no control over this.

 

Personally, I think option 1 is a lot safer and easier to implement, so I'd do that.

As an added point (and something I should have said at the beginning), XSS attacks cannot be caused by HTML hyperlinks. They can only be caused by JS code, so I don't really think that XSS attacks are related to your question. And again, if you run a function like htmlspecialchars on your posts, you should be fine.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...