PHP file_get_contents () doesn't work when + (plus) sign is in file name

I have several files that have a plus sign in their name and I cannot open them as the function interprets it as a space.

Example:

File name: Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html

      

And when I try to open it:

Warning: file_get_contents(/cores/Report_Tue-Jun-02-2015-14:11:04-GMT 0200-(W.-Europe-Daylight-Time).html) [function.file-get-contents]: failed to open stream: No such file or directory in .... on line 150

      

this is my code:

$file = $_GET['FILE'];  
$file = str_replace('+', '%2B', $file);
$content = file_get_contents($file);

      

Any thoughts / solutions?

+3


source to share


3 answers


The following methods work fine for me.



<?

    # File name: Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html 

    # Method 1.

    $file = 'Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html';

    $data = file_get_contents($file);

    print($data);

    # Method 2.

    $data = file_get_contents('Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html');

    print($data);
?>

      

+1


source


First of all, the file must not contain: sign.
Then below code works fine for me.

$content = file_get_contents('Report_Tue-Jun-02-2015-141104-GMT+0200-(W.-Europe-Daylight-Time).html');

echo $content;

      

If you don't work then use:



$link = urlencode($url);
$content = file_get_contents($link);
echo $content;

      

I think it's his job every time.

+1


source


Information on how to write a valid URI is available in RFC3986 . First, you need to ensure that all special characters are represented correctly. for example spaces for plus signs and the trade mark must be URL encoded.

It is also necessary to remove extra spaces at the beginning and end. Using the function urlencode()

for the entire URL will result in an invalid URL. Leaving the URL like this is also incorrect because unlike browsers, the file_get_contents () function does not perform URL normalization. In your example, you need to replace the plus sign with% 2B: `

 $string = str_replace('+', '%2B', $string);

      

This is what ex. encodeURIComponent()

in JavaScript. Unfortunately, this is not what urlencode

PHP does ( rawurlencode

safer). check also link

I hope this works for you.

0


source







All Articles