algorithmicCoder
algorithmicCoder

Reputation: 6789

Handling a space in a get parameter

I am using a command like

 $page = file_get_contents($url);

where

$url = "http://www.site.com/search/index.cfm?tab=names&workername=firstname lastname";

When the url is typed directly in the browser chrome adds a %20 in between firstname and lastname and the website handles things properly.

However when I use $url with a space, file_get_contents grabs only results that match the firstname and isn't aware that workername = "firstname lastname"

When I explicitly add "%20" in between it returns NULL...

What's the work around?

Thanks guys!

Upvotes: 5

Views: 32068

Answers (2)

gabriel capparelli
gabriel capparelli

Reputation: 101

You need to urlencode your text:

$fixed= urlencode($workername);
$url = 'http://www.example.com/search/?tab=names&workername='.$fixed;

Upvotes: 1

animuson
animuson

Reputation: 54729

A few problems:

  1. I hope this is just because you quick-typed it here, but you need to have the string in single quotes.
  2. There is no query string for the URL because you never start it with the ?, so no, neither of those variables will exist in $_GET.
  3. You do have to redefine spaces as %20 for URLs.

$url = 'http://www.site.com/search/?tab=names&workername=firstname%20lastname';
       ^                           ^                              ^^^        ^

Edit:
It is possible that the website you're trying to query is ignoring them as GET variables. Have you tried adding this code to explicitly say it is a GET request?

$options = array(
  'http' => array('method' => "GET", 'header' => "Accept-language: en\r\n")
);
$context = stream_context_create($options);
file_get_contents($url, false, $context);

Upvotes: 3

Related Questions