在php和路径问题中执行LaTeX

I am trying to compile a latex source file from php, using exec:

echo shell_exec("/usr/texbin/pdflatex source.tex");

Unfortunately, latex doesn't seem to see all packages when it is called via php.

For example, I get

LaTeX Error: File `customclass.cls' not found

when I try to use customclass, installed in my local texmf folder. There is also the same problem for some packages installed elsewhere.

This has certainly something to do with a path variable or something like that to set up, but I haven't been able to find what for an hour.

Has someone an idea ?

The PHP interpreter is probably running as some other user, like www-data or something related: this means that it can't see the packages installed in your usual user's texmf directory (I'm assuming that's what you mean by local), because the user's texmf is only loaded when pdflatex is run as that user.

This seems like a potential solution to extending the LaTeX path to wherever your local texmf is, based on shell variables: Temporary installation of (La)TeX files (from the TeX FAQ).

You can put your *.cls files into the same directory as source.tex. If your then change the directory to be the "current directory", when starting latex, then it also will be found by the latex interpreter and used for compiling your Latex file.

This is also a better solution for using with with php, as you would not want to make the user of your application install something into the home directory of www-data user. This might be forbidden for security reasons.

So, the solution is:

  • put source.tex into directory called latexfiles (or a name of your choice)
  • put your *.cls files to latexfiles
  • use the following code to compile your latex document:
passthru('cd /path/to/latexfiles/; pdflatex source.tex', $r);
echo $r; 

The source of /Users/My/Sites/tex/index.php file is bellow. For example let it be reachable by http://localhost/~My/tex/index.php link.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <title>PDF file compillation</title>
</head>
<body>
<?php 
ini_set('safe_mode', 'Off');
$output = array();
/*
   /usr/texbin/ - directory, where the pdftex exists
   /Users/My/Sites/tex/output - directory for test.pdf and everything else. This directory have to have permissions to write.
   /Users/My/Sites/tex/test.tex - source .tex file
*/
exec("/usr/texbin/pdftex --shell-escape --synctex=1 -output-directory=/Users/My/Sites/tex/output /Users/My/Sites/tex/test.tex", $output);
if($output){
    echo("<h3>Console output</h3><pre>".implode("
", $output)."</pre>");
/*
    /Users/My/Sites/tex/output/test.pdf - the result file after compilling
*/
    echo('<p>Go to compilled <a href="http://localhost/~My/tex/output/test.pdf">PDF file</a></p>');
}else{
    echo('<h3>Error</h3><p>Shell script execution failed.</p>');
}
?>  
</body>
</html>