Search code examples
phpencodingphp-curl

How do I encode a GET request for the $search variable in the URI?


How do I encode a GET request for the $search variable in the URI (example: Android and Corp) to get (Android%2Band%2BCorp) instead of (Android+and+Corp)?

Form_

 <form action="search.php" method="GET">
  <input type="text" name="search" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
  <input value="1" name="chank" id="one" type="radio" checked />
  <label for="one" class="switch__label">1</label>
  <input value="2" name="chank" id="two" type="radio" />
  <label for="two" class="switch__label">2</label>
  </form>

search.php_

$search=$_GET['search'];
$channel=$_GET['chank'];
$page=$_GET['page'];
include "conf/info.php";
$title = 'Result | '.$search;
include "header.php";
include "api/api_search.php";

GET_ api.php

$cs = curl_init();
curl_setopt($cs, CURLOPT_URL, "".$home."".$vapi."/search/".$chank."?api_key=".$key."&language=".$lang."&query=".$search."&page=".$page."");
curl_setopt($cs, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($cs, CURLOPT_HEADER, FALSE);
curl_setopt($cs, CURLOPT_HTTPHEADER, array("Accept: application/json"));
$response = curl_exec($cs);
curl_close($cs);
$search = json_decode($response);

But I still get '+' instead of true '%2B' in my address bar


Solution

  • It looks like curl is encoding your string from _GET (with the +) into %2b. You can use urldecode() to get the 'original' before building the curlopt url:

    $s = 'some+cool+string';
    echo $s . PHP_EOL; // some+cool+string
    echo urlencode($s) . PHP_EOL; // some%2Bcool%2Bstring
    echo urldecode($s) . PHP_EOL; // some cool string