LaTeX Equations and Graphics in PHP

Make the difficulties of displaying mathematical equations on the Web a thing of the past by embedding LaTeX content in your pages.

This PHP page provides a form for entering LaTeX code and then replaces the thunks with URLs to rendered PNG images through the transform method. Everything else is done behind the scenes in the render class.

Minimal Configuration Options

The skeleton for the render class is shown in Listing 2.

You need to let PHP know where your tools are located and provide a directory where PHP can write temporary files and store its cache. For convenience, a URL_PATH also is needed. This URL_PATH is used when generating the image tags in HTML.

Don't be fooled by the simplicity. A vast array of options is available that you can pass to LaTeX and ImageMagick to modify the output PNG image, and you should explore them all. Here, I've merely provided the framework.

wrap Method

The wrap method takes your LaTeX thunk and surrounds it with a prologue and epilogue to create a valid LaTeX source file. You can consider this to be the equivalent of adding additional includes to a C file or importing packages in Java to extend the functionality of the language (Listing 3).

As you can see, I include the packages I routinely need in the LaTeX wrapper. Consequently, I've included the American Mathematical Society (AMS) package, which provides additional mathematical constructs, as well as the PSTricks package to render vector graphics. The pagestyle is set to empty so that page numbers do not appear on images. Also, the thunk is inserted between the document blocks.

Not all of these packages may be available on your system. If necessary, you can download additional packages from the Comprehensive TeX Archive Network (CTAN) Web site (see the on-line Resources) to extend the functionality of your base LaTeX system. For example, packages for bar charts, UML notation and even Karnaugh maps can be downloaded. Whatever your needs, the repository is worth a look.

render_latex Method

The render_latex method (Listing 4) extracts all thunks and processes them individually until the thunk pool is exhausted.

The thunk parameter is obvious: it's the block of LaTeX code we're currently examining. The hash parameter is a unified version of the thunk, essentially, an md5 of the filename base.

I change to the temporary directory and write the thunk to a temporary LaTeX file. LaTeX then creates a DVI file. The command-line parameter tells LaTeX to run non-interactively. The resulting DVI file is converted to PostScript with the use of dvips, and the -E option specifies a bounding box. I then run the resulting PostScript file through convert—that's the program name—to convert the file to a PNG image. The convert tool has a slew of options, and the settings that will work best for you depend on your site.

Finally, be aware that the exec command returns a failure status code. For brevity, I've left out the error checking and always assume that all steps succeed. LaTeX also has a few dangerous commands that could be an issue for multiuser Web sites. It therefore might be prudent to return an error if certain keywords are found in the thunk.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Another aproach to LaTeX equations with PHP

Filipi Vianna's picture

Some time ago I had faced the same problem, but I didn't use the same rendering steps. Instead of rendering to PS and then converting to PNG, I had used dvipng to convert the DVI directly to PNG.

The code is at my personal blog.

Hope it also helps somebody.

Filipi Vianna

A bit of trouble

Skylar Saveland's picture

I have been looking for something like this off and on for months but I am a programming newb with most experience in python; this article has me crash-coursing php.

I think I am having problems naming the .php files, placing them in the right place and/or setting the correct permissions. I know exactly where convert, latex and dvips are, that is not the problem. I have put everything in the document root in separate files, each listing.

wrap.php7870l3.qrk I have just named wrap.php, I can't find any logic for the '7870l3.qrk' part.

If I name the second listing/file 'render.php' I get the follwing error:
Warning: require(render.class.php) [function.require]: failed to open stream: No such file or directory in /var/www/render_example.php on line 26

Fatal error: require() [function.require]: Failed opening required 'render.class.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/render_example.php on line 26

If I name the second listing 'render.class.php' I get a different error:
class render { var $LATEX_PATH = "/usr/bin/latex"; var $DVIPS_PATH = "/usr/bin/dvips"; var $CONVERT_PATH = "/usr/bin/convert"; var $TMP_DIR = "/usr/home/biouser/texwebtmp"; var $CACHE_DIR = "/usr/home/biouser/texwebtmp/cache"; var $URL_PATH = ""; function wrap($text) { ... } function transform($text) { ... } function render_latex($text) { ... } }
Fatal error: Class 'render' not found in /var/www/render_example.php on line 33

Something is going on here... I would b so excited and grateful if i could get this to work!!!

uninformed question

matt's picture

This looks exactly like what I need. I am trying to set up a simple wiki to collaborate with co-writers, and am trying to find how to embed latex capabilities. I am a rookie in programming though, and cannot figure out some things. Specifically, "You need to let PHP know where your tools are located and provide a directory where PHP can write temporary files and store its cache."==> What tools? I see I need latex and dvips etc., but what exactly are these as tools? I use latex, but don't know exactly what I need to upload to the server.



David Sankey's picture


I'm starting to implement this into a math worksheet website I'm (slowly) building. It's superior to html formatting because it doesn't vary from browser to browser. I had to alter it a bit because I'm making worksheets for print and the images weren't printing well. I changed the density to 300. Then, I get the image height using "identity" and reduce it by 40% using the height attribute in the image tag.

The images on screen are a bit choppy but the prints look great. My students are sure to appreciate it!

Would you like me to post a link or give you other credit?

Thanks a bunch!

Dynamic Base URL

Carlos S.'s picture

It may be a good idea to add a function to get the base URL instead of hard writing it on the source code.
it may be something like:

$base_url = 'http' . (isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] == 'on' ? 's' : '' : '');
$base_url .= '://' .$_SERVER['HTTP_HOST'];
if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
$base_url .= "/$dir";
$URL_PATH= $base_url . "/cache"


Web CAS, another LaTeX+PHP on Apache

Anonymous's picture

Although I has not read the interesting article, a project of SourceForge, WMI (Web Mathematic Interactive,, may be the subject that readers are interested. WMI integrates almost the powerful CAS in Linux world, e.g. Maxima, Octave, Gnuplot and Maple etc. within LAMP envirnment. Don't forget to visit the official site.


summentier's picture

How did you know that the article was interesting if you hadn't read it? I did read it and it was great help!