PHP Using cURL and GET request in URL - php

I am using cURL instead of file_get_contents, which is working fine on the URL until I used a GET request variable in place of the city on the URL below.
Using cURL on the following: (Works)
$url = 'http://www.weather-forecast.com/locations/London/forecasts/latest';
This works fine, however when substituting 'London' with a variable $city:
URL: example.com/weather.php?city=London
$city = $_GET['city'];
$city = ucwords($city);
$city = str_replace(" ", "", $city);
$url = 'http://www.weather-forecast.com/locations/".$city."/forecasts/latest';
I get an error: The page you are looking for doesn't exist (404)
What am I doing wrong in my cURL function? This seems to work perfectly with file_get_contents, is there something I am missing?
cURL function
function curl_get_contents($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$contents = curl_get_contents($url);
echo $contents;

Please replace double quotes with single quotes in url,
$url = 'http://www.weather-forecast.com/locations/'.$city.'/forecasts/latest';

Related

Replace string in raw data response is not working

Using PHP CURL i'm calling one URL and i'm getting some response from one page,Now I need to replace one string from that response but it's not working,please check my code below.
$url = "My URL";
$url1 = $url1 = str_replace(' ', '%20', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$raw_data1 = curl_exec($ch);
curl_close($ch);
$raw = str_replace('#', 'Test', $raw_data1);
echo $raw;
You are trying to replace special character,My suggestion is you should try to use preg_replace() instead of str_replace()
Try the below example:
$url = "My URL";
$url1 = $url1 = str_replace(' ', '%20', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$raw_data1 = curl_exec($ch);
curl_close($ch);
$raw = preg_replace("([#]+)", "Test", $raw_data1);
echo $raw;
To replace a pattern of string always use preg_replace() and in your case the response is coming from other source so better way to replace the string is to find define a pattern and replace Using preg_replace()
This is what you need preg_replace("([#]+)", "test", $raw_data1);

file_get_contents equivalent of curl function

I have following curl program which is working fine.
$data="var1=$var1&var2=$var2";
$ch = curl_init("http://www.website.asmx/FetchData");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
I tried following code to get same data using file_get_contents but it returns false.
$data="var1=$var1&var2=$var2";
$result = file_get_contents("http://www.website.asmx/FetchData?=".$data);
var_dump($result);
exit();
What code will be equivalent to above curl program?
Notice the = at the End of FetchData in:
$result = json_decode(file_get_contents("http://www.website.asmx/FetchData?=".$data));
This should rather read:
//WITHOUT THE EQUAL SIGN AFTER FetchData...
$result = json_decode(file_get_contents("http://www.website.asmx/FetchData?".$data));

PHP - get json data from url

I'm trying to load json data from this url =
http://api.opencagedata.com/geocode/v1/json?query=48.84737%2C2.28605&pretty=1&no_annotations=1&no_dedupe=1&key=b61388b5a248b7cfcaa9579ed290485b
Using file_get_contents works with other json urls but this one is strange. It returns only "{" the first line. Strlen gives 1480 which is right.Substr(2,18) gives "documentation" which is right too. But still i can't echo the entire text. Maybe there's some way to read the text line by line and save it in another string ? The entire text is still fully loaded in the textfile
Here's the php code i tried
<?php
$url = file_get_contents("http://api.opencagedata.com/geocode/v1/json?query=48.84737%2C2.28605&pretty=1&no_annotations=1&no_dedupe=1&key=b61388b5a248b7cfcaa9579ed290485b");
$save = file_put_contents("filename.txt", $url);
echo $url;
?>
Also tried this function but still same.
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
You can get return value with json_decode.
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return json_decode($data,true);
}

cURL with PHP - HTTP cURL to HTTPS

I have the following bit of PHP, it works locally (via apache and localhost) but not on my hosting - $response is always empty:
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$api_key = 'my_api_key';
$randomString = generateRandomString(10);
$endLabel = sha1(md5($randomString));
$user_id = $endLabel;
$amount_doge = '5';
$url = "https://dogeapi.com/wow/?api_key=".$api_key."&a=get_new_address&address_label=".$user_id;
$response = get_data($url);
I wondered if this could be because I'm hosted on HTTP (no SSL option) and I'm calling a HTTPS domain? If so, is there a way around this? I've tried curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); but it doesn't seem to do anything :(
try to use echo curl_error($ch) after $data = curl_exec($ch); to see what curl says
it wil lreport you what happened

file_get_contents() how to fix error "Failed to open stream", "No such file"

I'm getting the following error when I try to run my PHP script:
failed to open stream: No such file or directory in C:\wamp\www\LOF\Data.php on line 3
script:
My code is as follows:
<?php
$json = json_decode(file_get_contents('prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=*key*'));
print_r($json);
?>
Note: *key* is a replacement for a string in the URL (my API key) and has been hidden for privacy reasons.
I removed the https:// from the URL to get one error to disappear.
Am I doing something wrong here? Maybe the URL?
The URL is missing the protocol information. PHP thinks it is a filesystem path and tries to access the file at the specified location. However, the location doesn't actually exist in your filesystem and an error is thrown.
You'll need to add http or https at the beginning of the URL you're trying to get the contents from:
$json = json_decode(file_get_contents('http://...'));
As for the following error:
Unable to find the wrapper - did you forget to enable it when you configured PHP?
Your Apache installation probably wasn't compiled with SSL support. You could manually try to install OpenSSL and use it, or use cURL. I personally prefer cURL over file_get_contents(). Here's a function you can use:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Usage:
$url = 'https://...';
$json = json_decode(curl_get_contents($url));
Why don't you use cURL ?
$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth);
print_r($json);
}
}
You may try using this
<?php
$json = json_decode(file_get_contents('./prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=*key*'));
print_r($json);
?>
The "./" allows to search url from current directory.
You may use
chdir($_SERVER["DOCUMENT_ROOT"]);
to change current working directory to root of your website if path is relative from root directory.
I just solve this by encode params in the url.
URL may be: http://abc/dgdc.php?p1=Hello&p2=some words
we just need to encode the params2.
$params2 = "some words";
$params2 = urlencode($params2);
$url = "http://abc/dgdc.php?p1=djkl&p2=$params2"
$result = file_get_contents($url);
just to extend Shankars and amals answers with simple unit testing:
/**
*
* workaround HTTPS problems with file_get_contents
*
* #param $url
* #return boolean|string
*/
function curl_get_contents($url)
{
$data = FALSE;
if (filter_var($url, FILTER_VALIDATE_URL))
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
}
return $data;
}
// then in the unit tests:
public function test_curl_get_contents()
{
$this->assertFalse(curl_get_contents(NULL));
$this->assertFalse(curl_get_contents('foo'));
$this->assertTrue(strlen(curl_get_contents('https://www.google.com')) > 0);
}
We can solve this issue by using Curl....
function my_curl_fun($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$feed = 'http://................'; /* Insert URL here */
$data = my_curl_fun($feed);
The actual problem of this error has nothing to do with file_get_content, the problem is the requested url if the url is not throwing content of the page and redirecting the request to some where else file_get_content says "Failed to open stream", just before file_get_contents check whether the url is working and not redirecting, here is the code:
function checkRedirect404($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
//echo "Redirects: $target<br>";
return true;
}
}
return false;
}
I hope below solution will work for you all as I was having the same problem with my websites...
For : $json = json_decode(file_get_contents('http://...'));
Replace with below query
$Details= unserialize(file_get_contents('http://......'));

Categories