-1

I have a form where i get a filename from a inputbox. I create the a directory and change the extension form "gpx" to "xml" of the file before i upload the file to my directory. In php5 i need preg_replace, but in php i can't do it anymore.

I have this code: My old code is:

  if (!file_exists($dirPath)) {
    mkdir($dirPath, 0755,true);
    }
    $target = '/'.$mappe.'/'; 
    $target = $dirPath .'/'. basename( $_FILES['gpsfilnavn']['name']); 
        $target =    preg_replace("/(\w+).gpx/ie","$1.'.xml'",$target);    
        $xmlfil = $xmlfil . basename( $_FILES['gpsfilnavn']['name']); 
        $xmlfil =    preg_replace("/(\w+).gpx/ie","$1.'.xml'",$xmlfil);     
        if(move_uploaded_file($_FILES['gpsfilnavn']['tmp_name'], $target)) {
        echo "The file ".  basename( $_FILES['gpsfilnavn']['name'])." has been  uploaded";

Can anybody help me what i have to change?

compac
  • 21
  • 1
  • 3

2 Answers2

2

There has been a change since PHP 7 regarding the preg_replace() function.
According to the man-page

7.0.0 Support for the /e modifier has been removed. Use preg_replace_callback() instead.

Maybe this helps you?

Audax
  • 91
  • 1
  • 4
1

I've stumbled upon this issue today when upgrading a phpBB-based website from PHP5 to PHP7. I came up with three different workarounds that can be used for different scenarios, the second one being the only viable one for mine since I had template-based regexp stored within the filesystem/db instead of static ones, which I couldn't easily alter.

Basically, I went from this:

$input = preg_replace($search, $replace, $input);

to something like this:

$input = preg_replace($search, 
    function($m) use ($replace) { 
        $rep = $replace; 
        for ($i = 1; $i<count($m); $i++) { 
            $rep = str_replace('\\'.$i, '$m['.$i.']', $rep); 
            $rep = str_replace('\$'.$i, '$m['.$i.']', $rep); 
        }
        eval('$str='.$rep); 
        return $str;
    },
    $input);

Needless to say, this is nothing more than a quick-and-dirty workaround, only "viable" for those who cannot easily refactor their code with the updated preg_replace_callback function without having to use any potentially unsecure eval() call: for this very reason it should only be used if the developer has full control over the replacement strings/rules and is able to properly test/debug them. That said, in my specific scenario, I was able to effectively use that in order to get the job done.

IMPORTANT: the str_replace and/or the eval() could break some replacement rules unless they are "properly" defined taking the above code into account.

For further info regarding this issue and other alternative workarounds you can also read this post on my blog.

Darkseal
  • 9,205
  • 8
  • 78
  • 111