Json data from php API at online hosting - php

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.

Related

JSON Requests failing in Wordpress via PHP Script

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);
};
};
?>

PHP + PayPal IPN + SQLite = a mysterious 503 error?

I have a simple php Paypal ipn listener which inserts the raw POST data into an SQLite (v2) database. It was working. Then...it stopped working. (I don't recall making any changes to it.) It uses a basic php sample that Paypal provides using CURL to communicate with Paypal (followed by the db insert). It just gives a 503 Service Unavailable error now.
It works (minus actually doing anything :)) if I comment out the final line, that simple contains "sqlite_exec(...)".
Alternatively, a MySQL insert works fine.Mailing results works as well.
The SQLite database appears normal. Another script reads & updates as normal.
Web host sees no issues on the server side.
Can anyone make sense of this?
Or maybe there is a way to send the POST data to another script so that it gets processed separately, on its own, instead of altogether as one page?
Update: What I'm trying to insert is the "raw post data" string...
$raw_post_data = file_get_contents('php://input');
...as seen on the top line here under php sample code: https://www.x.com/developers/PayPal/documentation-tools/code-sample/216623 . My script is the same except with an insert at the bottom, which basically looks like this:
$dbloc = "/db/ipn.sqlite";
if($db = sqlite_open("$dbloc", 0666, $sqlite_error)){}else{die ($sqlite_error);}
$datetime = date("Y-m-d H:i:s");
$data = $raw_post_data;
$sql="INSERT INTO Paypal (entrydate,verified,data) values ('$datetime',$verified,'$data')";
sqlite_exec($sql,$db);
From when are you getting this error ?
Paypal has done some IPN changes recently.
please check this links:
https://www.x.com/content/bulletin-ipn-and-pdt-scripts-and-http-1-1
http://www.tipsandtricks-hq.com/forum/topic/paypal-ipn-and-pdt-changes-effective-from-1st-february-2013
please let us know what you are trying to insert into the db.

cpanel XML API 404 error

Had a look at quite a few posts on stack and the cpanel forum but still cant seem to find a solution.
Im trying to retreive information via an api call but it just always seems to fail. I know its to do with the url 404'ing but not sure how to fix.
I am using the the XMl API class:
https://github.com/CpanelInc/xmlapi-php/
The code I have is:
$this->load->library('xmlapi');
$xmlapi = new xmlapi(XMLAPI_HOST);
$xmlapi->password_auth(CPANEL_USER, CPANEL_PASSWORD);
$xmlapi->set_debug(1);
echo '<pre>';
print_r($xmlapi->accountsummary(CPANEL_USER));
echo '</pre>';
The above outputs the xml array. In the error_notice it says:
HTTP error 404, The requested page was not found.
Thats fine. So I echo out the url it uses which 404's:
http://mysite.co.uk:2082/xml-api/accountsummary
The cpanel docs are a little awkward to navigate but just cant find anything on the actual url structure, besides its the class that compiles the url. ive tried adding www, tried an ip etc but no idea why its erroring.
Also if it helps im accessing a normal cpanel account, not a WHM admin and its through http.
Thanks for reading, any help guidance on getting it working would be appreciated.
The issue you are experiencing is that you are attempting to use the accountsummary function from cPanel ports (2082/2083). The accountsummary function is limited to the administrator accounts since this function is designed to provide administrative api level access for pulling account information from any user on the server.
To access the accountsummary api, you will need to call the accountsummary api from the following url:
https://$SERVER_IP:2087/xml-api/accountsummary?user=$USERNAME
You will need to replace $SERVER_IP and $USERNAME with their respective values.
http://docs.cpanel.net/twiki/bin/view/SoftwareDevelopmentKit/ShowAccountInformation

Securing my own administration panel

I need ways to securize my own php administration panel. I read here about some:
A simple authentication using apache2.conf
Using ssl to send encrypted passwords
Host the tools on a completely seperate domain
A proper robots.txt should also be used
Using chmod 777 when i want to use and do a chmod 000 when i finish
But eachone has problems.
If i want to do it with apache2.conf, i must use ssl too. Only with this is it secured?
If i upload the tools in other domain and use robots.txt to "hide" them, could someone find them?
Using chmod is like "non-professional"
What do you use to secure your administration panel?
But eachone has problems. If i want to do it with apache2.conf, i
must use ssl too. Only with this is it secured?
Sort of. If you don't use ssl, passwords are sent over the net unencrypted if someone is listening in on your communication, they will know the password. That being said, it is usually impossible for someone to listen to your communication with the server unless one of the participating parties has already been compromised or you are communicating through an unsafe medium like unencrypted public wlan.
If i upload the tools in other domain and use robots.txt to "hide"
them, could someone find them?
Yes, if they guess the URL. robots.txt just hides you from search engines, but it does not work for protecting your admin panel from unwanted access.
Using chmod is like "non-professional"
And unsafe. It means that whenever you are working on the admin panel, everyone else also can. Don't do this.
What do you use?
Access control with Apache (either through the global config or an .htaccess file) with SSL. It may be a bit painful to set up at first, but for the given problem, it really is the only choice that makes any sense.
What you could do is use a php class that requires you to log in or sign up to your Website. You can find plenty from a quick Google.
Then, you should make an API on your Website that only sends data back if you're authenticated. Here's an example that would read data from a MySQL database:
<?php
require_once $_SERVER["DOCUMENT_ROOT"] . "/includes/accounts.class.php"; //Change this to the path to your authentication script
header("Content-Type: application/json"); //Important if you're using json
$account = new Accounts(); //A fictional Accounts class is opened
$json = array();
if (!$account->authenticated or $account->rights != "administrator") { //Ask the class if the user is not an admin
$json = array(
"error" => "Not an administrator"
);
} else {
$query = mysqli_query($link, "SELECT * FROM example"); //Assuming you use mysqli and there's a table called example
if (!$query or mysqli_num_rows($query) < 1) {
$json = array(
"error" => "Query returned no results"
);
} else {
while ($row = mysqli_fetch_array($query)) { //Read the data from the table
$json[] = $row;
}
}
}
echo json_encode($json); //Send the data as a json string
Remember that the above code is only an example of how you would do this sort of script. You'll need to modify it to work with the class and database you are using.
Now you can make your own program for your own internal use that logs in to and queries data from your API. This could be a Website running on an internal server, a Windows program or a smartphone app. All it would need to do is fill in the form on the log in Webpage, then send a HTTP request to the script above and decode the json result.

How to fetch data from PHP web services installed in CakePHP from iPhone?

I created the PHP web services, which reads data from MySQL and return to my iPhone app. Previously I used the same code successfully in many apps. The web server on which I installed my web services is CakePHP based, while my web services are written in simple PHP.
I'm failing to get the data from them in my iPhone app. Web services are working perfectly on localhost, but as installed them on the server, I'm receiving binary data instead of XML file. I changed the encoding and content-type tag. Doing this web services returning the following fault code.
error in msg parsing: Charset from HTTP Content-Type &apos;US-ASCII&apos; does not match encoding from XML declaration &apos;utf-8&apos;
So anyone can help me? Did I need to rewrite all of my web services in CakePHP or simple PHP web services can work? Here is the code of one of my web service.
<?php
include('vp-config.php');
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
define("PATH_DIR",str_replace("\\","/",dirname(__FILE__))."/");
$server = new soap_server;
$server->register('getAllNews');
function getAllNews($page) {
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn) or die(mysql_error());
$q = "SELECT
`website_contents`.`id`,
`website_contents` .`website_top_category_id`,
`website_contents` .`created`,
`website_contents` .`short_description`
FROM `website_contents`
WHERE `website_contents`.`website_content_type_id` = 2
AND `website_contents` .`short_description` IS NOT NULL
ORDER BY id DESC LIMIT " . $page ." , 30";
$rs = mysql_query($q);
while($r = mysql_fetch_array($rs)){
$items[] = array('id'=>$r['id'],
'website_top_category_id'=>$r['website_top_category_id'],
'created'=>$r['created'],
'short_description'=>$r['short_description']
);
}
return $items;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$serve
r->service($HTTP_RAW_POST_DATA);
CakePHP does a lot of content handling to ensure that you need to do a little work as possible. If you're just attempting to access some simple data, you might just leave it out of CakePHP and keep them as separate scripts. Creating them in CakePHP might be using a sledgehammer for hanging a picture frame (if you get my analogy).
Given your explanation in the comments, I would recommend importing them into CakePHP as libraries. You would be able to take your webservice code as a set of PHP files (or however you organized them) and they can be dropped into the appropriate folder in the app/ directory according to which version of Cake is being used. From there, they can included into the rest of CakePHP without you needing to know what your client is actually doing with his code.
Read up here for how your code would be imported. Keep in mind that significant changes have been made to this process between version 1.2 and 1.3 so note that in your reading below:
Loading Vendor files in CakePHP 1.2
Plugins in CakePHP 1.3
Changes from 1.2 to 1.3 in regards to Vendor files
Hope this helps!

Categories