Get requests from python aren't sent on php - php

I send my data through get request from python to php website (it's on hosting) and it doesn't work. But when it's on localhost it works
Php:
<?php
$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('text.txt', $req_dump, FILE_APPEND);
?>
Python:
import requests
while True:
theWeight = input("Enter ")
r = requests.get('http://localhost:81/index.php', params={'weight': theWeight})
print(r.url)
I edit only this string for the site that's on hosting and it doesn't get the GET requests
r = requests.get('http://example.com/index.php', params={'weight': theWeight})

The problem is that your page requires JavaScript for work correctly as shown in the r.text output (i.imgur.com/k5hAEZ0.png).
Now your PHP code doesn't anything other than write the .txt file, there is some HTML/JS code under that?
If not it can be that your hosting provider web server has some filter for "no-js-enabled" HTTP requests? I find it strange that the code stops working only on the hosting server
Another way of solving this problem is by using another python lib that supports JavaScript: Web-scraping JavaScript page with Python

Well it was because of the hosting, I only changed it and it works

Related

Setting up a server-side script to continuously record streamed JSON data from an API in a database?

I am trying to set up a server-side connection to an API that continuously parses and records the API's JSON response in a MySQL database throughout the day. My site is set-up as a Wordpress site, and so any Wordpress specific solutions work too.
I know how to keep a connection open and print the responses as they come in using Python, for example. Something like this works:
import requests
import json
headers = {'Content-Type': 'application/json',
"Authorization": "Bearer api_key_here"}
baseurl = 'http://stream.url/here'
payload = { 'key_id' : 'key'}
r = requests.get(baseurl, params=payload, headers=headers, stream=True)
print(r.headers)
print('\n')
for line in r.iter_lines():
if line:
print(json.loads(line.decode("utf-8")))
The output from the above script trickles out line by line as it comes in from the API server.
For example, suppose I get a response like this every second:
{'type': 'TYPE', 'time': '2019-11-18T21:07:12.422789431Z', 'key1': [{'dat1': '1.10739', 'dat2': 10000000}], 'key2': [{'dat1': '1.10752', 'dat2': 10000000}]}
What I am trying to do now is to set up a server side script (preferably in PHP but I can work with other solutions too) that basically does this, except instead of printing the response, it records it into a database table, in real-time, throughout the day.
I don't have much experience setting up a server side script like this, so not sure where to start.
PHP really doesn't "listen" well. You really have two options:
Cronjob that calls a php script that checks the output and runs every few seconds.
Have your python script POST to somewhere instead of / in addition to print.

How to compile and send result php code in python http server?

I am wriritng HTTP server with python socket.
I have a web page that contain PHP code like this
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
which a want to send to client, when i send it normally the PHP file will not be compiled and only send like a string and nothing happen in browser.
if i want to cmpile and send php code what should i do?
i send file like this:
with open(filename[1:]) as f:
outputdata = f.read()
self.request.send(bytes('\nHTTP/1.1 200 OK\n\n','utf-8'))
for i in range(0, len(outputdata)):
self.request.send(bytes(outputdata[i],'utf-8'))
self.request.close()
Your script is working as "intended". Python will not magically parse and execute PHP code. You need a PHP interpreter for that.
You could of course write one in your python server if so inclined, but I would rather recommend you to take a look at either Python web development (if you want to roll your own server for educational purposes you may want to use an existing templating system like Jinja), or PHP development.

Blank results on json parse on https api calling using php and MAMP

I´m trying a very simple php script which is about calling a json data through api calling on a online https link using MAMP.
However if I use the following code I have blank results:
<?php
$cnmkt = "https://api.coinmarketcap.com/v1/ticker/?limit=50";
$json = file_get_contents($cnmkt);
$fgc = json_decode($json,true);
echo $fgc[1]['percent_change_7d'];
?>
But if i copy/paste the content of the https link into a test.json file locally, substituting the https link with the test.json file on $cnmkt variable, the same exact script works properly.
I know i´m missing something very obvious, if someone could help me that would be very much appreciated, thanks.
Stefano
The script is working fine. I get an expected result of 4.63
Disable your AV/firewall and check again.

Json data from php API at online hosting

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.

Ionic framework and php mysql

I am new in Ionic,Apahce Cordova and I created a simple application which has static list view items but I want to get data from MYSQL table and replace this in my static list. I Google it some one worked on it but I don't know where I should put my php files and I created some php files in Ionic app/www/php files but it doesn't work for me and what is your solution guys? Thank you
You can put your php files in localhost or live server.I had the same problem (Cross-Origin Request Blocked) when the app is run in browser.Here are solutions from my experience
1.Test the app in emulator not in browser and change the localhost address to this http://10.0.2.2/test/test.php.This will works fine for me
2.if you are run in android device you cant access from the localhost,so put the files in a live server
eg:http://www.testapp.in/test/test.php
As said above, your PHP files should be hosted on a webserver. And since the resource is not local to your application, you will need $http.jsonp, which allows CORS.
Here's an example of how you'd send a request to a PHP page in AngularJS.
$http.jsonp("http://domain/project/example.php?callback=JSON_CALLBACK&p1=" + $scope.val1 + "&p2=" + $scope.val2)
.success(function(data) {
//some function
})
.error(function(data) {
console.log("http request failed");
});
OR
For sending requests using jQuery, you can refer this post: https://stackoverflow.com/a/28740155/4412363
Now, you can $_GET the data, then you must have the response in JSONP, also you need to add the callback in your response. It'll look like:
echo $_GET['callback'] . '(' . json_encode($result) . ')';
PS: Here, Ionic takes care of the IPs when you're trying on an emulator. So I just set the url's domain to my local IP address, and it works on all the devices (desktop, emulator, and mobile)

Categories