I am trying to send data using POST from StachExchange API. I am not sure what seems to be the problem. I have checked the script, it's working fine when I try to POST data some other way. The problem seems to be with the python script. The scripts gets the data from the API but doesn't seems to be posting to "generate.php" Nonetheless here's the code:
#!/usr/bin/env python
import requests, json
userinput = input('Enter a keyword: ')
userinputq = input('Enter page: ')
getparams = {'page':userinputq, 'pagesize':'100', 'order':'desc', 'sort':'votes', 'intitle':userinput, 'site':'stackoverflow', 'filter': '!5-HwXhXgkSnzI0yfp0WqsC_-6BehEi(fRTZ7eg'}
r = requests.get('https://api.stackexchange.com/2.2/search', params=getparams)
result = json.loads(r.text)
if result['has_more'] == False:
print("Error given.")
else:
for looping in result['items']:
if looping['is_answered'] == True:
try:
newparams = {'order':'desc', 'sort':'votes', 'site':'stackoverflow', 'filter': '!4(Yrwr)RRK6oy2JSD'}
newr = requests.get('https://api.stackexchange.com/2.2/answers/'+str(looping['accepted_answer_id']), params=newparams)
newresult = json.loads(newr.text)
titletopost = 'Title:', looping['title']
bodytopost = '<h1>Question:</h1><br>'+(looping['body'])+'<br>'+'Link to Question: '+(looping['link'])+'<br><br><br>'+'<h1>Answer:</h1><br>'+(newresult['items'][0]['body'])
enterremove = bodytopost.replace('\n', '').replace('\r', '')
print(enterremove)
userdata = {"secret":"Secret", "topic_title":titletopost, "body":enterremove}
requests.post("http://www.example.com/generate.php", data=userdata)
except KeyError: print("No answer ID found.")
print("")
print("")
Can anyone please explain the problem?
Nevermind! There's nothing wrong with the python script. Actually I forgot to change "$_GET" to "$_POST" in 'generate.php' while I was testing it.
Related
I am trying to send data from AngularJS to PHP.
I am sending the data from the controller.js of AngularJS.
I am receiving the data through PHP. The data comes well for others variables.
However, I don't know which part is the problem.
My goal is to have the PHP recognize $step_number and run through the IF-statement in PHP, but even though I send wrong data, it works!
Which means,
if the $step_number in PHP is '2', then the IF-statement in PHP should not work as shown in below. But, it runs!
I thought this was the proper way to write the code as other data are being passed to PHP.
Controller.js
$http.post("../crud/projects_update.php",{
step_number : '1', // This one, I am trying to send, but I don't know whether this is not being sent or the problem is occurred in PHP.
project_id : $scope.project_data.project_id // This works in the PHP. It is well sent.
project_title : $scope.project_data.project_title
}
PHP
require_once 'connect.php';
$data = json_decode(file_get_contents("php://input"));
$step_number = $data->step_number; // This should be received from AngularJS and if the $step_number is not matched in the IF-statement, then the function in { } should not work.
if ($step_number = '1'){
$project_id = $data->project_id;
$project_title = $data->project_title;
$conn->query("UPDATE `projects` SET
`project_title` = '$project_title',WHERE `project_id` = $project_id") or die(mysqli_error());
}
Two things need to change:-
1.Change step_number : '1', to step_number : 1,
2.Change
if ($step_number = '1'){ //this is assignment not comparison
to:-
if ($step_number == 1){ // now it's comparison
I am sending the json data from a python program using the below code
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
and receiving it in a php server side using the below code.
<?php
if($_GET['temp_value']) {
$temp_value = $_GET['temp_value'];
echo $temp_value;
# $data = array($id, $description);
$arr=json_decode($temp_value,true);
} else {
echo "not found";}
// Connect to MySQL
include("dbconnect.php");
// Prepare the SQL statement
$SQL = "INSERT INTO test1.temperature1 (temp_value) VALUES ('$arr')";
// Execute SQL statement
mysqli_query($dbh,$SQL);
Echo "<a href=http://localhost/json1/review_data.php><center><u><b><h1>Manage values<h1><b><u></center></a>"
?>
along with the json data I have implemented like Id,time and date also gets updated in the database when i send the data.But what is happening here is like whenever i send the data from the python program it won't give any errors,when i see in the database and in the php page only 0(zero) values are inserted in both,however time and id gets updated.please someone suggest me a proper code and way.
Try this:
<?php
$json_payload = json_decode($_GET['json_payload']);
$temp_value = $json_payload['temp_value'];
?>
When you do this:
r = requests.get('http://localhost/json1/js2.php',data=payload)
You are sending a get request containing a JSON string representation of your data:
'{"temp_value": 132}'
stored in the get parameter named json_payload.
Therefore, on the client side, you must retrieve the contents of the json_payload parameter and decode the JSON string therein in order to retrieve temp_value.
Alternatively, you could do this:
payload = {"temp_value":132}
r = requests.get('http://localhost/json1/js2.php',data=payload)
And leave your PHP code unmodified.
import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)
print(r.url)//http://localhost/json1/js2.php
Json data is not passed in to php.Check your python code
payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
Result:
http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3
You have to use like
payload = {"temp_value":132}
I have very strange problem with sendfrom. To process I am using dynamic vales from form received with $_POST.
$myaccount = trim($_POST['myaccount']);
$to_wallet = trim($_POST['to_wallet']);
$wammount = trim($_POST['wammount']);
I can echo them and I can clearly see all the data passed from form
Now I am inserting them to
$message = ($bitcoin->sendfrom($myaccount, $to_wallet, $wammount));
What I discovered that all the $myaccount, $to_wallet are correctly passed but $wammount causing problem and code is not executed. I am inserting in form 0.0001 inside the field
"wammount" however once this is hard coded
$myaccount = trim($_POST['myaccount']);
$to_wallet = trim($_POST['to_wallet']);
$wammount = 0.0001;
and running command below everything run well and transaction is processed. Any idea why ?
$message = ($bitcoin->sendfrom($myaccount, $to_wallet, $wammount));
What does adding floatval() do?
$wammount = floatval(trim($_POST['wammount']));
I'm want to post a binary data string from a Python script to a webserver where a PHP script should pick it up and store it. I receive the whatever I echo in my POST part of the php script on the Python side so I assume, the actual POST works. However, I'm posting 23 Bytes and strlen($_POST['data']) stays 0.
My PHP script to pickj up the data looks like this:
if (isset($_REQUEST["f"]) && $_REQUEST["f"]=="post_status") {
$fname = "status/".time().".bin";
if (file_exists($fname)) {
$fname = $fname."_".rand();
if (file_exists($fname)) {
$fname = $fname."_".rand();
}
}
echo strlen($_POST['data'])." SUCCESS!";
}
and the Python POST script looks like this:
data = statusstr
host = HOST
func = "post_status"
url = "http://{0}{1}?f={2}".format(host,URI,func)
print url
r = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
r.get_method = lambda: 'PUT'
response = urllib2.urlopen(r)
print "RESPONSE " + response.read()
Why does my data not seem to get through, I'm wondering?
Thank you,
PHP will only populate posted values into the $_POST/REQUEST arrays for data that is sent as one of the form data content types. In your case, you need to read in the binary data directly from standard in like this:
$postdata = file_get_contents("php://input");
I know this question has been asked before, but I've had little success even after visiting similar questions. I'm currently developing a Flash project which involves being able to create an account and log in. However, I keep getting "undefined" from my attempts to parse PHP output.
Here is my ActionScript 3.0 code for the function that contains the code.
function gosubmit(event:MouseEvent) {
if (username.text != "" && password.text != "") {
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest();
phpFileRequest.url = "php/controlpanel.php";
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, execResult);
phpVars.username = username.text;
phpVars.password = password.text;
phpLoader.load(phpFileRequest);
phpLoader.addEventListener(Event.COMPLETE, execResult);
function execResult(event:Event) {
trace(event.target.data.execResult);
}
}
Here is the PHP code in php/controlpanel.php.
<?php
mysql_connect("localhost", "root", "password");
// change localhost to something else later
// change password to something else later
mysql_select_db("game");
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$salt_mysql = mysql_query("SELECT salt FROM players WHERE username='".$username."'");
$salt = salt_row["salt"];
$unhashed_password = $password.$salt;
$password = hash("SHA256", $unhashed_password);
$exec_mysql = mysql_query("SELECT * FROM players WHERE username='".$username."' AND password='".$password."'");
if (mysql_num_rows($exec_mysql)) == 1 {
echo "execResult=login_accepted";
}
if (mysql_num_rows($exec_mysql)) == 0 {
echo "execResult=login_rejected";
}
else {
echo "execResult=error";
}
?>
I have compared my code with multiple sources, even copied whole projects from sources trying to figure out what I have done wrong, but with little success. However, there is something weird I found out. Out of pure experimentation, I put the following into controlpanel.php:
=&execResult=test
And, instead of getting "undefined", I got "test". The weird part is that I only used that one line of code; no <?php tags or anything. Moreover, if I put more code beyond that, regardless of what kind of code I entered, it would always show up literally in the Flash output. So I can now hardcode a value and return it into Flash, but that's not what I need. I need to be able to determine a value based on conditionals and have it automatically returned into Flash.
Can anyone help me out? I am truly stumped.
Thanks :)
Seems that you are executing flash from the editor/debugger, (if you are checking the results with trace function).
Then using a relative url for request "php/controlpanel.php" is like opening the file localy without the execution from server of php directives.
Maybe thats why you get literaly all php code, or the correct value when you only put "=&execResult=test" as the content of the php file.
Try using absolute url with the http:// in order to perform an http request where server and php execution are involved.