简体   繁体   English

在PHP脚本中调用时,无法通过Perl建立MySQL连接

[英]Unable to make a MySQL connection through Perl when called in a PHP script

I'm creating a connection to a MySQL database within a Perl script, called by a PHP script. 我正在通过PHP脚本调用的Perl脚本中创建与MySQL数据库的连接。 Here are the 2 scripts: 这是2个脚本:

Perl: Perl的:

#!/usr/bin/perl
# script name = MyCode.pl
use DBI;
my $data_source = q/dbi:mysql:name:localhost/;
my $user = q/myname/;
my $pwd = q/pword/;

print "before...\n";
# Connect!
$dbhandle= DBI->connect($data_source,$user,$pwd) or die "can't connect
       $data_source: $DBI::errstr \n";
print "...after \n";

PHP: PHP:

<?php
 // script name = Test.php
 $myResult=shell_exec("perl /path/MyCode.pl");
 echo $myResult;
?>

When executed on the command line, Test.php prints "before..." and "...after" and the DB connection is indeed established within the Perl code. 在命令行上执行时,Test.php打印“before ...”和“... after”,并且在Perl代码中确实建立了DB连接。 However, when Test.php is executed from my (Chrome) browser, all that prints is "before..." and no connection is made. 但是,当从我的(Chrome)浏览器执行Test.php时,所有打印的内容都是“之前......”并且没有建立连接。 And no error message is displayed. 并且显示任何错误消息。

Why is there success on the command line but not from a web server? 为什么在命令行上有成功但在Web服务器上没有成功?

Yes, PHP shell_exec() function doesn't capture STDERR. 是的,PHP shell_exec()函数不捕获STDERR。

To debug your code, you can add a 2>&1 at the end of system command to redirect STDERR to STDOUT : 要调试代码,可以在系统命令末尾添加2>&1以将STDERR重定向到STDOUT

$myResult = shell_exec("perl /path/script.pl 2>&1");

Also, you can setup the DBI module to die if some error occurs at runtime: 此外,如果在运行时发生某些错误,您可以将DBI模块设置为die

$dbh = DBI->connect($data_source,$user, $pwd, { RaiseError => 1, PrintError => 0}) or die $DBI::errstr;

My first guess: from PHP you execute it with "perl /path/MyCode.pl" 我的第一个猜测:从PHP中你用“perl /path/MyCode.pl”执行它

The shell opened by Apache are under different user than yours and that user does not perl in it path. Apache打开的shell与您的用户不同,并且该用户不会在其路径中使用perl。

Try using Perl from full path: "/full/path/to/perl /path/MyCode.pl" 尝试从完整路径使用Perl:“/ full / path / to / perl /path/MyCode.pl”

FYI: Executing script with perl "scriptname" is not a good practice. 仅供参考:使用perl“scriptname”执行脚本不是一个好习惯。 Instead define a full path in to your Perl in the shebang and always start your script using the full path. 而是在shebang中定义Perl的完整路径,并始终使用完整路径启动脚本。 This way you could avoid errors like this. 这样你可以避免这样的错误。

Regards, Andras 此致,安德拉斯

Problem fixed...I needed correct path specification: this is done (on godaddy) by using: 问题已解决......我需要正确的路径规范:这是通过使用以下方式完成的(在godaddy上):

use cPanelUserConfig;

in the Perl script to access the DBD::mysql module that I installed. 在Perl脚本中访问我安装的DBD :: mysql模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM