I have been having trouble with a HTTP-GET request rendering consistently on my Wordpress site. Below is the 3rd party PHP script that is being used for the GET request. I don't have any experience with PHP, and I would like to ask the community if everything seems sounds in the code below.
I checked for syntax errors already, and as noted above, the code functions, just not always. I have spent hours on the phone with my hosting provider who says its not them, hours on the phone with my web dev team who says its not them, and all my testing of my API is showing it works from various sources (Postman, browser, c# request).
What I know:
- The API does NOT paginate data unfortunately, which was believed to be the main issue at first. But now were seeing this issue with requests as small as < 50KB. Requests can contain thousands of rows, which can increase the response size to ~2MB.
- The hosting provider has ruled out any timeouts, which is set at 60 seconds. Most responses are processed and returned from my endpoint within 2-5 seconds.
Update 1: Team is testing PHP functionality in another host to eliminate the possibility of environmental host issues.
Update 2: Hosting environment seems to be responsible for the issues with not rendering the data appropriately.
Update 3: Still haven't found the root cause. Closing question with no answer.
Script:
<?php
$request_url = "[endpoint_url]&PortalId=".$_GET['PortalId']."&StartDate=".$_GET['StartDate']."&EndDate=".$_GET['EndDate']."&Location=".$_GET['Location']."&County=".$_GET['County']."&LastName=".$_GET['LastName']."&FirstName=".$_GET['FirstName'];
$jrequest = file_get_contents( $request_url );
if( $jrequest ) {
$jsondata = json_decode($jrequest, true);
if( ! empty( $jsondata ) ) {
$success=1;
$totaljsondata = count($jsondata);
};
};
?>
We have a contact.html form that uses reCaptcha v2, whose backend processing is in a php file.
I've taken enough steps to understand that when we send the verification to google's api, the response comes back empty. Below is code that gave me this proof.
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST["g-recaptcha-response"].'&remoteip='.$_SERVER['REMOTE_ADDR'];
$verify = file_get_contents($url);
echo $url;
if (empty($verify)) echo 'Failed to fetch data';`
However, when I manually enter the url into a browser, I get a JSON response back that indicates success.
What, then, is the difference? Why would file_get_contents return empty if a simple get request from a Chrome browser give me trouble?
I have read that file_get_contents is synchronous, so I wouldn't expect this is just a noob error on waiting for the response.
Any help would be appreciated, this is my very first time working with PHP. It's not hard, but I may be missing something vital.
Sorry everyone, I can't understand why, but the problem was in the method used to access the site verify.
Using curl syntax, I finally got it working.
Change the configuration in php.ini file and don't need curl.
allow_url_fopen=0 to allow_url_fopen=1
I need your advice. I made API in php to communicate with my android application and mySQL database. Now I wanna put this api on free online hosting with free database, the problem is that when i make query for that API I'm receiving my json data with junk from hosting like HTML tags and commercial text "[hosting name] free hosting". When my app receives this data, it shuts down. Everything works fine on local wamp server but at online hosting my app is crashing
I have 3 questions for you
Is it normal on free hosting or maybe my API is wrong designed?
If I put my php files on paid serwer will I avoid this additional stuff added by hosting company?.
Check out part of my sample user registration php code
$new_sql_select_query = "select * from userinfo where userName like '$userName' and userEmail like '$userEmail';";
$sql_all_data = mysqli_query($con, $new_sql_select_query);
$userDataJson = array();
while ($row = mysqli_fetch_array($sql_all_data)) {
$userDataJson["userId"] = $row["userId"];
$userDataJson["userName"] = $row["userName"];
$userDataJson["userEmail"] = $row["userEmail"];
$userDataJson["accountBalance"] = $row["accountBalance"];
}
$responseJson["success"] = 1;
$responseJson["message"] = "User correctly added to base!";
array_push($responseJson["user"], $userDataJson);
echo json_encode($responseJson);
I have an idea but I do not know how to do it correctly. I am generating a new json data file by code below
$myjson = json_encode($responseJson);
file_put_contents('myfile.json', $myjson);
but here is another problem, my app need to be somehow redirected to this new file because right now my app is connecting directly to a specific php file in this case CreateNewUserDB.php so how should I do it?. Should I return link to this generated json file to my app and then make another connection but this time to this "myfile.json" file?. Waiting for answers.
Regards
The reason that your app might be crashing is that when you do send response to your app on localhost, then only json data is sent. But as you said on the free hosting, you got some html. When your java code tried to make a json object out of it, it must have thrown an exception and hence the error.
There are plenty of free hosting, that are good and don't do these type of advertisements. https://www.biz.nf/ is one of them. I used it in my early years. Also paid hosting will not give you problems like these
This is an old thread, but I had a similar problem recently.
I uploaded my php json api in my shared hosting and solved the problem setting the right format by adding the header for json in the php file:
header('Content-Type: application/json');
I encourage you to work with Firebase, it will handle all the background staff for you, and it gives you access to the database also, besides that, it's very fast comparing to regular databases.
I hosted a website i worked on on amazon web services, and for some reason some things dont work compared to when I run it locally on localhost.
of those things are the
if (array_key_exists("error", $json))
function and
the file_get_contents function.
Ive commented out the array key exists part and that solved the issue, at least for that part of logging in, until i get to the view documents page where a slim application error displays
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
and the issue for that lies in the viewdocspage.php file, particularly this code:
<?php
$raw = file_get_contents("http://cosoft.us-east-1.elasticbeanstalk.com/cosoft/mywiki/api.php?action=query&list=allpages&format=json");
$pages_response = json_decode($raw, true);
$pages_array = $pages_response["query"]["allpages"];
$page_titles = [];
I looked and read up on many threads that the issue lies with the file_get_contents in which the URL contains special characters, such as spaces (which mine doesnt have) and so needs to be encoded, using urlencode (or rawurlencode..?)
now ive tried encoding the whole url like this:
$raw = file_get_contents(urlencode("http://cosoft.us-east-1.elasticbeanstalk.com/cosoft/mywiki/api.php?action=query&list=allpages&format=json"));
but that resulted in this error:
slim error
Message: file_get_contents(http%3A%2F%2Fcosoft.us-east-1.elasticbeanstalk.com%2Fcosoft%2Fmywiki%2Fapi.php%3Faction%3Dquery%26list%3Dallpages%26format%3Djson): failed to open stream: No such file or directory
I figured that this may happen since I read that not all the URL should be wrapped by this encoding, but heres where Im stuck: which part of the url do i use the encoding on? the only special characters i keep coming accross regarding this error is spaces, but i dont have any spaces, so its something else which i dont know what it is...
Help is appreciated, thanks!
You would just need to url_encode the parameters. Say you had a value $value='My name is earl'
If you wanted to pass this value as a parameter in your url
http://somesite.com/?name=$value there would be spaces in the value that is url_encoded. So if you encode it as 'http://somesite.com/?name='.urlencode($value), when this is encoded the value will turn into My+name+is+earl
Reading resources from a URL may be restricted by the server's configuration.
http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
You should use CURL for this.
Basically i want this json output to be transferred to my server/php.
i try this
$url="http://maps.google.com/maps/nav?q=from:9500 wil to:3000 bern";
$conte = file_get_contents($url);
echo $conte;
the json is not echo, how can i save the output to my server?
You need to urlencode the GET parameters:
echo file_get_contents('http://maps.google.com/maps/nav?q=from:9500%20wil%20to:3000%20bern');
# Returns
# {"name":"from:9500 wil to:3000 bern","Status":{"code":200,"request":"directions"},"Placemark":[{"id":"","address":"Wil, Switzerland","AddressDetails":{"Country":{"CountryNameCode":"CH","CountryName":"Schweiz","AdministrativeArea":{"AdministrativeAreaName":"St. Gallen","SubAdministrativeArea":{"SubAdministrativeAreaName":"Wil","Locality":{"LocalityName":"Wil"}}}},"Accuracy": 4},"Point":{"coordinates":[9.048081,47.463817,0]}},{"id":"","address":"Frohbergweg 7, 3012 Bern District, Switzerland","AddressDetails":{"Country":{"CountryNameCode":"CH","AdministrativeArea":{"AdministrativeAreaName":"BE","SubAdministrativeArea":{"SubAdministrativeAreaName":"Bern","Locality":{"LocalityName":"Bern District","DependentLocality":{"DependentLocalityName":"Länggasse-Felsenau","Thoroughfare":{"ThoroughfareName":"Frohbergweg 7"},"PostalCode":{"PostalCodeNumber":"3012"}}}}}},"Accuracy": 0},"Point":{"coordinates":[7.436386,46.954897,0]}}],"Directions":{"copyrightsHtml":"Map data \u0026#169;2010 Google, Tele Atlas ","summaryHtml":"178\u0026nbsp;km (about 2 hours 2 mins)","Distance":{"meters":177791,"html":"178\u0026nbsp;km"},"Duration":{"seconds":7343,"html":"2 hours 2 mins"},"Routes":[{"Distance":{"meters":177791,"html":"178\u0026nbsp;km"},"Duration":{"seconds":7343,"html":"2 hours 2 mins"},"summaryHtml":"178\u0026nbsp;km (about 2 hours 2 mins)","Steps":[{"descriptionHtml":"Head \u003Cb\u003Esouth\u003C\/b\u003E on \u003Cb\u003EToggenburgerstrasse\u003C\/b\u003E toward \u003Cb\u003ELerchenfeldstrasse\/\u003Cwbr\/\u003ERoute 16\/\u003Cwbr\/\u003ERoute 7\u003C\/b\u003E","Distance":{"meters":29,"html":"29\u0026nbsp;m"},"Duration":{"seconds":2,"html":"2 secs"},"Point":{"coordinates":[9.048030,47.463830,0]}},{"descriptionHtml":"Take the 1st left onto \u003Cb\u003ERoute 7\u003C\/b\u003E","Distance":{"meters":625,"html":"650\u0026nbsp;m"},"Duration":{"seconds":109,"html":"2 mins"},"Point":{"coordinates":[9.047930,47.463570,0]}},{"descriptionHtml":"At the traffic circle, take the \u003Cb\u003E1st\u003C\/b\u003E exit onto \u003Cb\u003EGeorg Rennerstrasse\u003C\/b\u003E","Distance":{"meters":871,"html":"850\u0026nbsp;m"},"Duration":{"seconds":77,"html":"1 min"},"Point":{"coordinates":[9.056170,47.463110,0]}},{"descriptionHtml":"Take the ramp to \u003Cb\u003EZürich\/\u003Cwbr\/\u003EFrauenfeld\u003C\/b\u003E","Distance":{"meters":330,"html":"350\u0026nbsp;m"},"Duration":{"seconds":22,"html":"22 secs"},"Point":{"coordinates":[9.053350,47.455800,0]}},{"descriptionHtml":"Merge onto \u003Cb\u003EA1\u003C\/b\u003E\u003Cdiv class=\"google_impnote\"\u003EToll road\u003C\/div\u003E","Distance":{"meters":173696,"html":"174\u0026nbsp;km"},"Duration":{"seconds":6790,"html":"1 hour 53 mins"},"Point":{"coordinates":[9.050270,47.453900,0]}},{"descriptionHtml":"Take exit \u003Cb\u003E36-Bern-Neufeld\u003C\/b\u003E toward \u003Cb\u003EBremgarten\u003C\/b\u003E","Distance":{"meters":579,"html":"600\u0026nbsp;m"},"Duration":{"seconds":33,"html":"33 secs"},"Point":{"coordinates":[7.436980,46.966570,0]}},{"descriptionHtml":"At the traffic circle, take the \u003Cb\u003E2nd\u003C\/b\u003E exit onto \u003Cb\u003ENeubrückstrasse\u003C\/b\u003E","Distance":{"meters":1357,"html":"1.4\u0026nbsp;km"},"Duration":{"seconds":243,"html":"4 mins"},"Point":{"coordinates":[7.429580,46.966790,0]}},{"descriptionHtml":"Turn right at \u003Cb\u003EMittelstrasse\u003C\/b\u003E","Distance":{"meters":146,"html":"150\u0026nbsp;m"},"Duration":{"seconds":24,"html":"24 secs"},"Point":{"coordinates":[7.437750,46.956720,0]}},{"descriptionHtml":"Take the 1st left onto \u003Cb\u003EBrückfeldstrasse\u003C\/b\u003E","Distance":{"meters":104,"html":"100\u0026nbsp;m"},"Duration":{"seconds":33,"html":"33 secs"},"Point":{"coordinates":[7.436060,46.956100,0]}},{"descriptionHtml":"Take the 1st right onto \u003Cb\u003EFrohbergweg\u003C\/b\u003E\u003Cdiv class=\"google_note\"\u003EDestination will be on the left\u003C\/div\u003E","Distance":{"meters":54,"html":"54\u0026nbsp;m"},"Duration":{"seconds":10,"html":"10 secs"},"Point":{"coordinates":[7.436830,46.955320,0]}}],"End":{"coordinates":[7.436234,46.955057,0]}}]}}
How do you want to save it? As a file?
If you can open via file_get_contents(), then URL opening for fopen() wrappers is on.
Then you can just do...
$url = 'http://maps.google.com/maps/nav?q=from:9500 wil to:3000 bern';
$content = file_get_contents($url);
file_put_contents('google-map-json.txt', $content);
You can get that into a usable object in PHP with json_decode().
You may want to do that if you want to save it to your database.
If you don't want to overwrite the file each time, you could generate a random hash of the response for the filename, or something similar.
Update
sorry my bad. i know how to save file. but the json is not even echoed through file_get_contents.
You may not have URL fopen() wrappers enabled.
You can find out by running this...
var_dump(ini_get('allow_url_fopen'));
If it is disabled, and you can't or don't want to turn it on, you can use cURL (if you have that library installed).
Update
When I tried to access the page via file_get_contents(), I got...
HTTP/1.0 400 Bad Request
You may need to use cURL, and mimic a browser (user agent etc).
Or you can set
ini_set('user_agent', 'Mozilla or something');
And then use file_get_contents().
Update
I tried with cURL too, and it didn't work :(
I think the next step is to examine all the headers your browser sends (when it works), and then send the equivalent via cURL.
Update
I noticed the Markdown editor wasn't liking the URL (see my OP's edit), and it dawned me - urlencode() the GET params!
You can write the data to a file using PHP's IO functions
$fp = fopen('data.txt', 'a');
fwrite($fp, $conte);
fclose($fp);
You can use json_decode to parse the data from the file_get_contents() variable. (I would personally use cURL instead of file_get_contents()).