LaTeX Equations and Graphics in PHP
When Things Go Awry
If something goes wrong at the rendering stage, you can try to process a LaTeX file manually by using the shell with the following commands for diagnostics:
latex --interaction=nonstopmode my.tex dvips -E my.dvi -o my.ps convert -density 120 my.ps my.png
This allows you to isolate the specific step at which the LaTeX renderer fails.
During the LaTeX rendering process, a large number of temporary files are created. This cleanup method deletes these extraneous files, and there's really not much to it, as shown in Listing 5.
Listing 5. cleanup.php
function cleanup($hash) {
$current_dir = getcwd();
chdir($this->TMP_DIR);
unlink($this->TMP_DIR . "/$hash.tex");
unlink($this->TMP_DIR . "/$hash.aux");
unlink($this->TMP_DIR . "/$hash.log");
unlink($this->TMP_DIR . "/$hash.dvi");
unlink($this->TMP_DIR . "/$hash.ps");
unlink($this->TMP_DIR . "/$hash.png");
chdir($current_dir);
}
The transform method, shown in Listing 6, drives the rendering class and provides a public access point for the programmer.
Listing 6. transform.php
function transform($text) {
preg_match_all("/\[tex\](.*?)\[\/tex\]/si", $text, $matches);
for ($i = 0; $i < count($matches[0]); $i++) {
$position = strpos($text, $matches[0][$i]);
$thunk = $matches[1][$i];
$hash = md5($thunk);
$full_name = $this->CACHE_DIR . "/" .
$hash . ".png";
$url = $this->URL_PATH . "/" .
$hash . ".png";
if (!is_file($full_name)) {
$this->render_latex($thunk, $hash);
$this->cleanup($hash);
}
$text = substr_replace($text,
"<img src=\"$url\" alt=\"Formula: $i\" />",
$position, strlen($matches[0][$i]));
}
return $text;
}
The preg_match_all function in PHP extracts the thunks as well as the positions of each thunk. Each thunk then is parsed individually through the loop. Next, a unique md5 of the thunk text is created. This tells us whether a thunk has been cached before. If the thunk has not been cached, I call the LaTeX renderer method and immediately clean up the resulting temporary files. In either case, the thunk is substituted with a URL. When all thunks are processed, the text is returned.
Now, let's look at a few examples that illustrate the kinds of equations you can render with the help of LaTeX. Most of these equations are taken from A Guide To LaTeX by Helmut Kopka and Patrick W. Daly, considered by many to be one of the essential books on the LaTeX system.

Figure 2. Example: Fractions
[tex]
\begin{displaymath}
\frac{a^2 - b^2}{a + b} = a - b
\end{displaymath}
[/tex]

Figure 3. Example: Correlation of Two Variables, X and Y
[tex]
\begin{displaymath}
\mathop{\mathrm{corr}}(X,Y)=
\frac{\displaystyle
\sum_{i=1}^n(x_i-\overline x)
(y_i-\overline y)}
{\displaystyle\biggl[
\sum_{i=1}^n(x_i-\overline x)^2
\sum_{i=1}^n(y_i-\overline y)^2
\biggr]^{1/2}}
\end{displaymath}
[/tex]
[tex]
\begin{displaymath}
I(z) = \sin( \frac{\pi}{2} z^2 ) \sum_{n=0}^\infty
\frac{ (-1)^n \pi^{2n} }{1 \cdot 3
\cdots (4n + 1) } z^{4n + 1}
-\cos( \frac{\pi}{2} z^2 ) \sum_{n=0}^\infty
\frac{ (-1)^n \pi^{2n + 1} }{1 \cdot 3
\cdots (4n + 3) } z^{4n + 3}
\end{displaymath}
[/tex]
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Home, My Backup Data Center
- Python Programming for Beginners
- New Products
- Paranoid Penguin - Building a Secure Squid Web Proxy, Part IV
- New Products
- Hey God - You may not be
3 hours 27 sec ago - Reply to comment | Linux Journal
5 hours 33 min ago - Drupal is an Awesome CMS and a Crappy development framework
10 hours 12 min ago - IT industry leaders
12 hours 34 min ago - Reply to comment | Linux Journal
1 day 5 hours ago - Reply to comment | Linux Journal
1 day 7 hours ago - Reply to comment | Linux Journal
1 day 9 hours ago - great post
1 day 9 hours ago - Google Docs
1 day 10 hours ago - Reply to comment | Linux Journal
1 day 14 hours ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.





Comments
Another aproach to LaTeX equations with PHP
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.
Regards,
Filipi Vianna
A bit of trouble
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 = "http://127.0.1.1/lj/cache"; 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
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.
Thanks!
matt
Awesome!
Hi!
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
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"
Carlos
Web CAS, another LaTeX+PHP on Apache
Although I has not read the interesting article, a project of SourceForge, WMI (Web Mathematic Interactive, http://wmi.sf.net), 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.
Curious
How did you know that the article was interesting if you hadn't read it? I did read it and it was great help!