PHP frontend to ImageMagick

Tags:

PHP frontend to ImageMagick | evolt.org has a nice and simple illustration of how to run ImageMagick commands via a PHP script. A bit dated but it simply works — almost.

A couple of things would break on Windows. A fix is in the discussion. However, as it is, it is impossible to deal with things like "-draw ‘text 200, 100 ‘this is a line’" ".  Below are changes I made to the script.

 

        // error with no-parameter commands. See www.evolt.org/article/PHP_frontend_to_ImageMagick/17/55650/
        //if (!preg_match(’/^[a-z0-9\/{}+-!@%]+$/’,$match[4])) {
        //    die(’ERROR: Invalid parameter.’);
        //}

        if (!preg_match(’/^[A-Za-z0-9\/{}+-!@%&\’]*$/’,$match[4])) {
                    die(’ERROR: Invalid parameter.’);
        }

 

 

This change in the matching patter solves 2 problems: (1) it takes care of non-parameter commands such as "flip". More importantly, it allows single quotation marke in the command. It will be crucial in the "do()" command below.

 

         switch ($match[2]) {
            case ‘do’:
                // run imagemagick command, urlencoded by browser
                // if you do:
                //    http://../magick.php/sunset.jpg?do(-draw "text 100,100 ‘Works like magick!’")
                // after urlencoding:
                //    http://../magick.php/sunset.jpg?do(-draw%20%22text%20100,100%20%27Works%20like%20magick!%27%22)

                //now try to replace "’" with %27, or do urlencode manually
                $match[4] = str_replace(’\'’,'%27′,$match[4]);

                // add command to list
                $commands .= urldecode($match[4]);
                break;

Now we have completely bypassed the original script’s mechanism, which requires parsing the commands. Now we simply pass whatever string in the do() to IM’s convert.exe. Of course, this may run into some security risk, but shouldn’t be any more than the original script, I think, because little is changed in the RegEx pattern.

Finally, if this doesn’t run on your Windows machine, you didn’t read the discussion following the lead article carefully. Add this to where it belongs:

 // http://www.evolt.org/article/PHP_frontend_to_ImageMagick/17/55650/
$cache = str_replace(’:',’-',$cache);

Overall, though, we can drop all the other commands, and simply pass everything (url-encoded by the browser) to convert.exe. The script can be further simplified.

Leave a Reply

If the above Image does not contain text, use this secure code: 9ZYC27Bb