Cannot make MySQL connection via Perl when called in PHP script

I create a connection to a MySQL database in a Perl script, the PHP script is called. Here are two scenarios:

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 // 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 in the Perl code. However, when Test.php is executed from my browser (Chrome), everything that prints is "before ..." and no connection is made. And the error message is not displayed.

Why is there success on the command line, but not from the web server?

+5
source share
3 answers

Yes, the PHP function shell_exec() does not write STDERR.

To debug your code, you can add 2>&1 at the end of the system command to redirect STDERR to STDOUT :

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

In addition, you can configure the DBI module to die if an error occurs at run time:

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

My first guess: from PHP you are executing it with "perl / path / MyCode.pl"

The shell opened by Apache is under a different user than yours, and this user does not use perl in this way.

Try using Perl from the full path: "/full/path/to/perl/path/MyCode.pl"

FYI: Running a script with perl "scriptname" is not good practice. Instead, define the full path to your Perl in shebang and always run your script using the full path. This way you can avoid errors like this.

Regards, Andras

0
source

The problem is fixed ... I need the correct path specification: this is done (on godaddy) using:

 use cPanelUserConfig; 

in a Perl script to access the DBD :: mysql module that I installed.

0
source

All Articles