Jump to content
Sign in to follow this  
erfan shaigani

sending json data by python to server

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

 

 

Share this post


Link to post
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);

?>

 

Share this post


Link to post
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?

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...