Jump to content

sending json data by python to server


erfan shaigani

Recommended Posts

hi , in the python requests POST tutorial in the site , there is this piece of code ,

url = 'https://ipaddress of my server .../myphp.php'
myjson = {'somekey': 'somevalue'}

x = requests.post(url, json = myjson)
 

it sends the json data to a php file in a server that i have access to

how can I access json data in myphp.php file in the server ???

thanks

 

 

Link to comment
Share on other sites

I'm not sure how Python is sending the data, but your PHP code will depend on the format of the data.

Assuming that Python is sending a JSON string, you can read the string using file_get_contents('php://input') and transform it into an array or object using json_decode().

<?php
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Print out the structure for testing
var_dump($data);

?>

 

Link to comment
Share on other sites

9 hours ago, Ingolme said:

I'm not sure how Python is sending the data, but your PHP code will depend on the format of the data.

Assuming that Python is sending a JSON string, you can read the string using file_get_contents('php://input') and transform it into an array or object using json_decode().


<?php
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Print out the structure for testing
var_dump($data);

?>

 

thanks a lot it worked for me , but i have another question , what if i want to send a file i mean really a file.json to a directory on my server?

Link to comment
Share on other sites

From PHP's end, you would use the $_FILES array as in this tutorial: https://www.w3schools.com/php/php_file_upload.asp

I'm not familiar with Python's libraries, but if you can't find a library to upload files you're going to have to manually build the body of a file upload HTTP request which is not that easy. An easier alternative is to send a POST request where one variable contains the file contents and another variable contains the name of the file.

Whichever way you do it, you should do some validation on the PHP end to prevent people from using this as a gateway to hack into your server. If they manage to upload a PHP file or another kind of executable file then they can do anything.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...