How to convert PERL to PHP, or run PERL from PHP?

I have a snippet of working PERL code from my web host that I need to execute from PHP. Is there any way to call a perl program from a PHP page, or somehow “translate” it into PHP?

Unfortunately, the encryption method used must stay exactly the same. This code is already in production, so it would be an incredible burden to use a different method.

$newpassword = "text";
$encrypted_password = mycrypt($new_password});

sub mycrypt {
	my($pw)=@_;
	$pw = crypt $pw,gen_salt(2);
	return $pw;
	}

sub gen_salt {
	my($size)=@_;
	my($s,$len,$passwd,$c,$i);
	$s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$len = length($s);
	$passwd = "";
	for($i=0;$i<$size;$i++) {
		$c = int(rand $len)+1;
		$passwd .= substr($s,$c,1);
		}
	return $passwd;
	}

There are a couple of PHP functions that can invoke system calls - if you’ve got proper permissions on the server you should be able to use a PHP command to execute the PERL script on the command line and read in the output.

/me rustles up the PHP manual

http://www.php.net/manual/en/function.system.php

Or you could use the backtick operator which is quite funky but only works if safe mode is off:

http://www.php.net/manual/en/language.operators.execution.php

Something like this might work:

$output = `perl perlscript.pl --parameters`;

I don’t know how to pass command line paramters to a PERL script but if you find that out you can pass the perl script the thing you want to crypt - the output of the PERL script will be stored in $output

That hould work - I’ve never tried it myself though.

I think it would be even easier to just translate into PHP. I don’t know much Perl, but it should be ok. I dunno what the whole “my” thing does, though …I know that there is a crypt function in php (see http://www.php.net/crypt ), so it might look something like this:


				    $new_password = "text";
                         $encrypted_password = mycrypt($new_password);

                         function mycrypt($pw){
                                 $pw=crypt($pw,gen_salt(2));
                                 return $pw;
                                 }

                         function gen_salt($size) {
                                 //my($size)=@_;
                                 //my($s,$len,$passwd,$c,$i);
                                 $s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                                 $len = strlen($s);
                                 $passwd = "";
                                 for($i=0;$i<$size;$i++) {
                                 	$c=intval(rand($len))+1;
                                     $passwd .=substr($s,$c,1);
                                         }
                                 return $passwd;
                                 }