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);
};
};
?>
Related
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 am facing a difficulty receiving the full length of a request in PHP file. I have written a sample like this.
Wrote a test.php file with below content,
<?php
$data = $_GET['data'] ;
echo($data);
?>
Now I have checked this with the browser with the following URL,
http://myserver.com/test.php?data=DDDDDDDDDDDDDDDDDDDD
I have tested this by increasing the number of D letters increased to see how much data can be passed maximum.
What I found was only 478 characters were received and shown in the echo statement. When I put more letter 'D' s in the parameter it won't show.
What I gathered was maximum of 512 characters can be received. If the total length is more that that it won't pass the get parameter. (will result empty data). I changed the browser but the effect is same.
But this same thing work perfectly well with my localhost (WAMP server) with Firefox, Chrome etc and can send / receive largeer request data. I understand this is not a browser issue but the server has a limit. (My GET Requests are about 1000 characters long in average and did not work in the godaddy server).
I am using GoDaddy shared hosting server. I guess this can be solved if I can increase the request length allowed at GoDaddy Server. But don't know if this is possible also.
Please help me to find a solution.
// in the sending page:
session_start();
$_SESSION["data1"] = $data1;
$_SESSION["data2"] = $data2;
// in the recieving page:
Session_start();
$data1 = $_SESSION["data1"];
$data2 = $_SESSION["data2"];
As far as I know session variables has no limits in size.
The only drawback is that the users can't bookmark or share the results with someone else
My goal is fairly simple, this is a PHP file and I included it into my header because I want to display the last bitcoin price using bitstamp.net not any other bitcoin exchange prices.
<?php
function getprice($url){
$decode = file_get_contents($url);
return json_decode($decode, true);
}
$btcUSD = getPrice('https://www.bitstamp.net/api/ticker/ '); //bitstamp
$btcPrice = $btcUSD["last"];
$tempround = round($btcPrice, 2);
$btc_Display = "$".$tempround;
?>
Well, this seems to work, but some times upon refreshing the page I get an error.
Warning: file_get_contents(https://www.bitstamp.net/api/ticker/ ):
failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST
in C:\xampp\htdocs\hidden\btcprice.php on line 3
The error doesn't happen often its very random in timing, but what does it mean and how can I prevent it?
It took me a while to get the error because I don't know what is causing it. I'm curious how to prevent it, am I leaving something out? I used a guide to learn how to do this that got the last bitcoin price from btc-e, but I don't want to use btc-e. I have to use bitstamp last price.
Also no JavaScript is allowed (or should I say I'm trying to avoid JavaScript for this little project) and I don't understand PHP OOP stuff, so please no examples in that.
Your code is working for me. The w3.org defines 400 as follows:
The request could not be understood by the server due to malformed
syntax. The client SHOULD NOT repeat the request without
modifications.
However, that can happen when you use a Web-Api. Espacially Api's from Bitcoin-exchanges can be pretty unstable and answer with errors from time to time, according to my own experience. How RobotMind already mentioned, you should put a
try
{
}
catch
{
}
around the getPricefunction.
Another option is to use Curl. This way you can easily access the Status-Code and react accordingly if an error should happen.
First edit (more details):
I used Modify Headers plugin in Firefox and visited the page (http://api.wunderlist.com/me/tasks), this showed the full and correct json string that I need. It never fails (25+ tests)
I tried using file_get_contents, but also file_get_contents cuts the response down. At various points.
cURL does the same, cuts down the response json at various points. Looks "at random"
Original post:
I'm breaking my head on a strange issue here. I've created a PHP Wrapper for Wunderlist2 (http://www.wunderlist.com) which can be found here: https://github.com/PENDOnl/Wunderlist2-PHP-Wrapper
It worked perfectly until I was notified by a user that the class stopped working all of a sudden. Since I created a free service (http://wcal.me) to provide a calendar feed for Wunderlist users, I decided to take a look at that script since that's the most easy way for me to debug the script.
Login in to Wunderlist and fetching the authtoken works, also all other functions in the class seem to work find (getting 'me', 'me/lists', etc.) However, in case of the getTasks function ('me/tasks') the response that I get is not complete, it simply stops in the middle of a json string. Therefor the json_decode function returns NULL and thus no tasks will be available in the calender feed/method response.
I also noticed that it's pretty random, because in some cases (<10%) it works like it should, but after another refresh the output is cut in half again. Also, the exact location of the 'cut' is different per refresh.
Is there anyone that can identify what the problem is? I tried to see if there is a way to wait untill a complete download of the file before it is returned, but it would be strange if that wasn't the default behaviour of cURL. I also tried to increase the timeout time, but since it returns a value I guess it doesn't timeout either.
All code can be foundin the Github repo, so far this is the only part I've changed to debug:
// get / put / delete requests should have HTTP Code 200 OK
// only exception is the login method, which returns HTTP Code 200 OK
if($httpCode == 200 && (strtolower($method) != 'post' || $action == '/login'))
{
$return = json_decode($output, true);
if($_SERVER['REMOTE_ADDR'] == MY_IP) {
if( is_null($return) ) {
echo "<b>Output of json_decode is null:</b><br><br>";
echo $output;
} else {
echo "<b>Output of json_decode os not null:</b><br><br>";
echo $output;
}
}
return $return;
}
The full response should look like something similar to this:
[{"assignee_id":null,"completed_at":null,"completed_by_id":null,"created_at":"2013-11-10T13:16:54Z"},{"assignee_id":null,"completed_at":null,"completed_by_id":null,"created_at":"2013-11-10T13:16:54Z"}]
But instead in most cases it's:
[{"assignee_id":null,"completed_at":null,"completed_by_id":null,"created_at":"2013-11-10T13:16:54Z"},{"assignee
Of course, this is a minified response, there is more information in the response available and there are many more items in the array.
For testing purposes, if you authenticate with the class, what result does browsing to http://api.wunderlist.com/me/tasks yield?
Also I'm sure you've already fixed but in base.class.php, $action is being checked for empty values twice instead of $action & $method.
Problem was with Wunderlist, just waiting for their fix :)
In a long tiredsome quest to speed up my site, I have figured out something is wrong with the redirection: currently my index.php handles all the homepage redirections via PHP header location 301 Redirect Permanently: website.com >> website.com/en/home and website.de >> website.de/de/home etcettera etcettera (around 20 for this multilingual website) it takes anywhere from 200ms to 6000ms to do the redirecting. Check out the waterfall!
After that, the page loads in a thunderbolt's blink of an eye!
What a waste of time wouldn't you say? What is the server doing all this time?
After careful examination, my best guesse is: ITS DOING LAUNDRY!
I am almost giving up on PHP for this!
Any and all clues to my puzzling prob are very welcomed +1
A. Given facts: Apache/2.0.54 Fedora, PHP 5.2.9. there is no database: just flat php files with around 15 php includes that completes my page with headers and footers). YSlow Grade: 92/100! Good page Speed: 93/100! javascript and css are as much as possible combined. Cache controlls seem well set too (as proven by the grades). Whats missing in those 7 points out of 100: not using Keep-Alive (beyong my controll in shared hosting and not using Content Delivery Network. I can live with those missing 7 points, but this is major hit on speed!
B. Furthermore: i recently was given great insights over here that i should use url rewriting via htacces. Point taken, BUT, perhaps there is sometin else wrong here that i should correct before moving on to the for me more difficult apache regex syntaxes.
C. Faster way: When I php include the intended homepage, instead of redirect, then all loads fast, but the url is not rewritten: it sits at website.com on the browser bar, whereas i wish after including it to become website.com/en/home. Is this possible with PHP? To include+change the current address of the url, too?
Conclusions: you can redirect using index.php, or using .htaccess. Sofar from my tests (coming from the genius answers below!THANKS EVERYONE!) the latter seems unmatched in speed: much faster redirecting than a php redirect! reducing the redirect to shorter than the first dns lookup.
see here how to do this correclty for multilingual site
Damn, I hate getting stuck with this kind of problem. You need to eliminate some variables.
First I should point out that PHP will not flush all of its own headers until you start outputting things (or, if the output_buffering(?) ini directive is set to x bytes, until you have output x bytes). So the following script will not finish "sending headers" until the very end:
<?php
header('Content-Type: text/pants');
sleep(6);
header('Ding-Ding: time to put the socks in the dryer');
echo "z"; // headers are sent here
What happens to the call to en/home if you put exit; or echo "wheeeee"; exit; at the very top of that PHP script? Then what happens when you substitute it with a plain, empty file? If the php script with exit is slow but the plain text file is fast, the PHP interpreter is probably playing funny buggers. If you still get the delay for both, you've eliminated the actual response generation as the cause (but I'm still trying to come up with some ideas if this is the case).
Also, can you ssh to the server? If so, can you try wgetting the same page from inside the server? If you can without the speed problem, I would be looking at the client side. If you can't SSH, you could try doing a request from PHP, though I'm really not sure if this will work:
<?php
$context = stream_context_create(array(
'http'=>array(
// send request headers if you need to
'header'=>array(
'Foo: Bar',
'Bar: Baz',
),
),
));
$start = microtime(true);
$response = file_get_contents('http://yourserver.com/', null, context);
$end = microtime(true) - $start;
var_dump($end);
// for some bizarre reason, PHP emits this variable into the local scope.
var_dump($http_response_header);
Have you tried doing the same request from other machines, or other places in the world? This can confirm or deny if it's just your machine.
Another thing you can try if it is the response generation is to do a little bit of hack-profiling on the production server. I hate having to do this stuff, but sometimes your code just refuses to behave on the production server like it behaves in your development environment or on staging. Do this to the script that generates /en/home:
<?php
// put this at the very top
$rqid = uniqid('', true);
$h = fopen(__DIR__.'/crap.log', 'a');
fwrite($h, $rqid.' [START] '.microtime(true).PHP_EOL);
fclose($h);
// do all that other wonderful stuff, like laundry or making a cup of tea
// put this at the very end
$h = fopen(__DIR__.'/crap.log', 'a');
fwrite($h, $rqid.' [END] '.microtime(true).PHP_EOL.PHP_EOL);
fclose($h);
Run a few requests against it, check to make sure 'crap.log' is getting stuff written to it (check permissions!!), and then you'll have some data that will show whether there is something in your script that needs to be investigated further as the cause of the slowness.
Oh, did I mention MySQL indexes? Are you doing any queries during the request? Have you added all of the proper indexes to the tables?
Steven Xu raises a good point in the comments for your question - are you sure the program you're using to generate the waterfall is giving you good info? Try installing Firebug if you haven't already, click the little firebug icon in the bottom right of firefox and make sure the "Net" panel is open, then re-run your request and see if the waterfall is consistent with the results you're seeing in the program you used.
Also, I know this is kind of a boneheaded suggestion and I apologise, but I think it needs to be said: your host doesn't allow ssh and only uses PHP 4? I would seriously consider another host. It may even solve this specific problem.
I will add more stuff as I think of it.
If it is indeed the headers taking ages, then your JS/CSS/HTML is irrelevant.
You can do the forwarding in .htaccess.
RewriteEngine On
RewriteRule ^$ en/home [R=301]
This will essentially send the same header, but it won't invoke the PHP engine first to do it :)
Update
On closer inspection, it would seem to me that your en/home page is taking the longer time to download.
I think Ignacio Vazquez-Abrams may have the answer: after you call header() to do the redirection you need to call exit() to cause the PHP script execution to stop. Without that the script will keep executing, sending output to the browser, until the end. Since the browser has to wait for the server side script to end before performing the redirection that could cause the problem.
Update
Just read Alex's update and he seems to be correct. The /en/home page is where the time is.