Search code examples
phpcurlencode

Encoding params of url that generated dynamically for use in CURL


I write a robot and fetch all URL in web page. the URLs is be like this:

http://www.example.com/result/رایانه

Now, When I try to fetch content of this url by CURL, give me this error:

400 Bad request

I know this cause because for "رایانه" in url and must encoding it.
But that URL is dynamically, and I need a solution for encode just params in URL.
Be like this:

"http://www.example.com/result/" . urlencode("رایانه")

Or another example:

Maybe I have this URL:

http://www.example.com/result/سوتی/?foo=علی&bar=حسن

If I use urlencode() return this:

http%3A%2F%2Fwww.example.com%2Fresult%2F%D8%B3%D9%88%D8%AA%DB%8C%2F%3Ffoo%3D%D8%B9%D9%84%DB%8C%26bar%3D%D8%AD%D8%B3%D9%86

But so must just encode this words: سوتی, علی, حسن.
and have this correct encoded:

http://www.example.com/result/%D8%B3%D9%88%D8%AA%DB%8C/?foo=%D8%B9%D9%84%DB%8C&bar=%D8%AD%D8%B3%D9%86

I need this for use in CURL.
How can I do this?

EDIT:

I found this code:

echo implode("/", array_map("urlencode", explode("/", $string)));

return:

http%3A//www.example.com/result/%D8%B3%D9%88%D8%AA%DB%8C/%3Ffoo%3D%D8%B9%D9%84%DB%8C%26bar%3D%D8%AD%D8%B3%D9%86

But the result is not exactly true.


Solution

  • I find a solution:

    $string = 'http://www.example.com/result/سوتی/?foo=علی&bar=حسن';
    $string = urlencode($string);
    echo str_replace(array('%3A', '%2F', '%3F', '%3D', '%26'), array(':', '/', '?', '=', '&'), $string);
    

    Output:

    http://www.example.com/result/%D8%B3%D9%88%D8%AA%DB%8C/?foo=%D8%B9%D9%84%DB%8C&bar=%D8%AD%D8%B3%D9%86
    

    It work with any URL and accept for use in CURL.