Search code examples
phpstringurlquotes

PHP string with singlequotes for url request


There is some site, whitch is using odata protocol for api access. To load users with specific status id, for example, I can use this url:

https://domain.com/contacts/?$filter=status_id eq 1

Plain and simple. In this case I'm just defining a string and getting expected response with curl:

$ch = curl_init();
$query = 'https://domain.com/contacts/?$filter=status_id eq 1'
curl_setopt($ch, CURLOPT_URL, $query);
$response = curl_exec($ch);

But the real problem starts with this:

https://domain.com/contacts/?$filter=email eq '[email protected]'

Here email is surrounded with single quotes. I've tried both single and doublequotes string with escaping:

$query = 'https://domain.com/contacts/?$filter=email eq \'[email protected]\''
$query = "https://domain.com/contacts/?\$filter=email eq '[email protected]'"

None of this has worked -- I've been getting request error every time. But if I run this in ruby -- everything working as it expecteted:

RestClient.get "https://domain.com/contacts/?$filter=email eq '[email protected]'", []

What can I do here? The version of PHP is 5.3.


Solution

  • https://domain.com/contacts/?$filter=email eq '[email protected]'
    

    This is not a valid URI. The valid URI encoded form would be:

    https://domain.com/contacts/?%24filter=email%20eq%20'email%40example.com'
    

    URLs have certain special characters which you cannot use directly, but which must be encoded to %.. sequences in order to be valid. You do this in PHP by using rawurlencode. You must encode the items separately:

    $url = 'https://domain.com/contacts/?' . rawurlencode('$filter') . '=' . rawurlencode("email eq '[email protected]'");
    

    Whether the receiving server will accept that URL or not is a different topic, but at least you're covering the basics on your end.