0

I'm trying to get content from here:

http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1

$json = file_get_contents('http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1');
$obj = json_decode($json);
var_dump($json);

result

string(0) ""

file_get_contents is working fine with other links, is there any way to get this data with php?

Adam Wojda
  • 749
  • 1
  • 7
  • 14

2 Answers2

1

Unfortunately PHP doesn't support cross-domain content requests the same way JS does, at least out of the box. To use URL content request, you must first set

allow_url_fopen

in your php.ini config file. It's common practice for hosts to disallow this by default.

Also, make sure you are dumping $obj and not $json.


Additionally, you could look into PHP's cURL library (similar to JS' ajax), which allows cross-domain requests.

cURL

//  Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Return response as string rather than outputting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set cURL url
curl_setopt($ch, CURLOPT_URL, 'http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1');
// Execute request
$result=curl_exec($ch);
// Close cURL resource
curl_close($ch);

// Dump JSON
var_dump(json_decode($result, true));
Community
  • 1
  • 1
citysurrounded
  • 664
  • 4
  • 8
1

file_get_contents not recomended for getting content from remote sources. More correct way is using curl. Curl may set correct headers, session, cookies and others params which you cannot set for file_get_contents and stream_context_set_default

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL,'http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0');
$curl_response = curl_exec($ch);
curl_close($ch);

$obj = json_decode($curl_response);

var_dump($obj);

And here the result:

object(stdClass)[3341]
public 'twuser_id' => string 'NzU0NDA4MTQwOTU4ODYwNjM3Nw..' (length=28)
Dmitriy.Net
  • 1,476
  • 13
  • 24