php – Laravel get_file_contents() replaces & with &-ThrowExceptions

Exception or error:

How can I avoid Laravel replacing & with & when calling get_file_contents()? I always get a “Bad Request” response because of this,
which is not a problem when not using Laravel.

How to solve:

use file_get_contents(htmlspecialchars_decode($URL));

Answer:

Use htmlspecialchars to encode it back into the ampersand symbol. This will also work on &, <, >, " and optionally ' as I assume Laravel will also escape those too.

For example:

file_get_contents(htmlspecialchars($URL));

And optionally:

file_get_contents(htmlspecialchars($URL, ENT_QUOTES));

Answer:

I solve my problem just use the " instead ' when building string URL path like follow:

 public function __construct($url, $username, $password)
{
    $this->url = $url;
    $this->params  = 'send?username='.$username.'&password='.$password.'&dlr=no';
}

to:

 public function __construct($url, $username, $password)
{
    $this->url = $url;
    $this->params  = "send?username=".$username."&password=".$password."&dlr=no";
}

Instead of use file_get_contents() you can use guzzlehttp/guzzle you can use this link for installation, and following example to send request and get response:

$client = new Client([
    'base_uri' => $this->url,
    'timeout' => 1.0,
]);
$request = $client->request('POST', $params);
$response = $request->getBody()->getContents();

You can access the content’s of body by getContents() method, hop this help you.

Leave a Reply

Your email address will not be published. Required fields are marked *