Return data from a URL with Query String

Asked

Viewed 989 times

0

There is a service that needs to send data via query string and it gives me a JSON return, however, I am not getting this return, it does not send the query string.

$url = 'https://www.servico.com.br?nome=abc&cpf=abc&cep=abc'

Having the variable $url I tried it from the forms below:

$dataReturn = file_get_contents($url);
//Retorna uma mensagem de erro dizendo que os parâmetros não foram passados.
//Como se tivesse enviado apenas: www.servico.com.br

$dataReturn = readfile($url);
//Retorna uma mensagem de erro dizendo que os parâmetros não foram passados.
//Como se tivesse enviado apenas: www.servico.com.br

$dataReturn = new SoapClient($url); // Essa foi no desespero
//Retorna uma mensagem de erro dizendo que não é um wsdl

$dataReturm = Response::json($url);
//Também dá erro. :(

Any suggestions to return the data???

  • Have some documentation of this service?

  • Yes, there is the documentation. When I make the request via the URL browser generated by PHP, it works. The problem is exactly in my PHP request.

  • It may be that some header is missing, no?

  • Worse than not, the error applies exactly in the absence of the query string, which it does not mount. :(

4 answers

2

Try using file_get_contents() with HTTP Context Options

$getdata = http_build_query(
  [
    'nome' => 'abc',
    'cpf' => 'abc'
  ]
);

$opts = array('https' =>
    array(
        'method'  => 'GET',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $getdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('https://www.servico.com.br', false, $context);
  • This will generate an error. It will tell that the file www.servico.com.br does not exist, as it did not specify the protocol. In php, to query a url you need to specify the wrapper or protocol, as I mentioned in my reply. Your reply applies best in cases where post requests are used. It is possible to pass get without using stream_context_create.

  • This is just an example, it needs to define the protocol in the first parameter of file_get_contents(). In the case of using stream is a good option, because I believe it is necessary to pass something else in the header of this request. He needs to take a look at the doc of that service

  • It is good to post the right example, so that other users do not have problems, understand? just for this.

  • Error: [Errorexception] file_get_contents(https://www.servico.com.br): failed to open st Ream: HTTP failed request! HTTP/1.1 400 Bad Request

  • Yes, add the protocol to the string

  • With the protocol also gives error.

  • When it includes the protocol HTTPS in the Stackoverflow string he omitted, but was passed with the protocol yes...

  • Note that in the $opts array key you have http, try https if this service is https

  • I made that change in $opts I switched to HTTPS, the error claiming the absence of parameter appears now.

  • This service has doc?

  • Yes, it does. The information is in agreement, for example, I need to make this request inside the PHP code, gives the error, however, if I take the full URL that is created by PHP code and game in the browser, it runs smoothly.

  • When you are in the browser, you are logged in to this service?

  • No, it is a process that works independent of login.

  • Forgive me, but instead of GET parameters, wouldn’t they be POST parameters? .

  • I’ve done it too, gives Laravel error saying that the requested method does not exist, it is a GET even...

Show 10 more comments

2

Well technically the "file_get_contents" function already contemplates sending urls with built-in query strings, so what I can think is that the error is on your server or more likely on the server you receive, such as "user_agent" blocking, IP blocking, header blocking, and more.

Test Your Server
Well to test your server you can create 2 simple files, one that receives and the other that sends, and display this data on the screen, this may indicate that your server is working properly ... as the example below:

[ Sends ]

<?php
var_dump(file_get_contents("http://seuserver.com.br/recebe.php?nome=abc&cpf=abc&cep=abc"));
?>

[ Receives ]

<?php
print_r($_GET);
?>

If you can view the data you sent then it falls in the second case, that the server you receive has some restriction ... the most common is the "user_agent" or poorly formatted header, then you can simulate an "agent", because many servers block to precisely not be accessed by robots, so using the answers of colleagues, would be more or less like this:

[ Sends ]

<?php
 $opts = array(
  "http" => array(
   "method" => "GET",
   "user_agent" => "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36"
 )
);
$context  = stream_context_create($opts);
$response = file_get_contents("http://seuserver.com.br/recebe.php?nome=abc&cpf=abc&cep=abc", false, $context);
var_dump($response);
?>

[ Receives ]

<?php
 print_r($_GET);
 echo "\r\n";
 echo $_SERVER["HTTP_USER_AGENT"];
?>

Finally if this solution does not solve I advise starting for something more elaborate as using the extension Curl or make your own HTTP connection module using fsockopen.

  • 1

    Tip: select code and press {} or control-K that it formats itself.

0

Try with CURL, use this code:

$url = 'https://www.servico.com.br'

$querydata = array(
    'nome' => 'abc',
    'cpf' => 'abc',
    'cep' => 'abc'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($querydata));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$jsonResult = curl_exec($ch);
curl_close($ch);

echo $jsonResult;

-4


RESOLVED

Guys, thank you so much for all the answers. However, I managed to solve the problem very simply. And so:

$handle = fopen($url, 'r');
flock($handle, LOCK_SH);
$result = file_get_contents($url);
fclose($handle);

TIP

It is worth remembering that this way serves for multiple requests, just put inside a loop, as I did also as follows:

foreach ($urls as $url) {
    $handle = fopen($url, 'r');
    flock($handle, LOCK_SH);
    $result[] = file_get_contents($url);
    fclose($handle);
}

Here’s a tip for those who need it too!!!

  • In this passage, fopen($url, 'rt'). Where did you get this second parameter, rt? Does not exist in the manual: http://php.net/manualen/function.fopen.php

  • The flock() also does not make sense because it does not make sense to block writing since there is no way to write on a url page. rsrs.. The strange thing is that you’re wearing file_get_contents(). In the end, the fopen() is doing nothing. rsrs.. Actually you are making a double request where the result is only obtained from file_get_contents().

  • The strange thing is that if I take the fopen() and the flock()does not work for muítiplas requisitions... It does not even execute the first requisition... according to the rt was a clerical error, the correct is just r as I gave Ctrl C + Ctrl V, went unnoticed...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.