Jump to content

Image extensions in BBCode


ecopetition

Recommended Posts

Hi there,

 

I'm trying to control what image extensions a user can put into an image BBCode, which works with preg_replace. Basically, I don't want them to put .php, .js, .html etc extensions into tags, so need it return an error when they try to do this. However, I do want them to put .png, .bmp, .gif, .jpg etc into the code.

 

Also, if I was to type the following:

[img=www.hotmail.com]

As well as:

[img=www.hotmail.com/image.php.gif]

How could I have this return an error also? (In other words, only if it contains a proper image extension at the end should it work).

 

Any advice as to how to go about this would be greatly appreciated.

 

Thanks a lot in advance,

Peter

Link to comment
https://forums.phpfreaks.com/topic/132320-image-extensions-in-bbcode/
Share on other sites

A long winded version:

$text = 'Hello World!

Good:
[img=http://www.google.co.uk/images/firefox/sprite.png]
Bad:
[img=http://www.google.co.uk/images/firefox/sprite.php]';

$text = preg_replace_callback('#\[img\](.+?)\[/img\]#s', 'parse_image', $text);

function parse_image($data)
{
    $trusted_ext = array('gif', 'jpg', 'jpeg', 'bmp', 'png');

    $info = pathinfo($data[1]);
    if(in_array($info['extension'], $trusted_ext))
    {
        return '<img src="'.$data[1].'" />';
    }

    // this could be just "return false;"
    return '<span style="color:red"><b>REMOVED</b></span>';
}

echo nl2br($text);

K, read the edit.  So basically:

 

$text = preg_replace('#\[img\]([^.]+\.(gif|jpeg|jpg|png))\[/img\]#', '<img src="$1" alt="" />', $text);

 

EDIT: Small typo; had the wrong quotation mark.

 

I tried this method in place of the original code but it doesn't work - BBCode does not function with it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.