John Davidson

Python sending information to PHP

0 comments
Message:


I have this code:


data.py:


import requests
userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
resp = requests.post('http://127.0.0.1/post.php', params=userdata)
print(resp.content)

post.php:


<?php 
$firstname = htmlspecialchars($_GET["firstname"]);
$lastname = htmlspecialchars($_GET["lastname"]);
$password = htmlspecialchars($_GET["password"]);
echo "firstname: $firstname lastname: $lastname password: $password";
?>

And in my localhost the page is seeing like this:


Notice: Undefined index: firstname in C:\xampp\htdocs\post.php on line 2

Notice: Undefined index: lastname in C:\xampp\htdocs\post.php on line 3

Notice: Undefined index: password in C:\xampp\htdocs\post.php on line 4

firstname: lastname: password:

What is wrong?



My Answer:
The issue is with how you are sending the data from Python to PHP. In your Python code, you are using the `params` parameter in the `requests.post` method, which sends the data as URL parameters in the request. However, in your PHP code, you are trying to access the data using `$_GET`, which is used to retrieve data sent in the URL parameters.

To fix this issue, you can send the data as form data in the request body instead. Here's how you can modify your Python code:

python
import requests
userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
resp = requests.post('http://127.0.0.1/post.php', data=userdata)
print(resp.content)


And modify your PHP code to access the data using `$_POST` instead of `$_GET`:

php
$firstname = htmlspecialchars($_POST["firstname"]);
$lastname = htmlspecialchars($_POST["lastname"]);
$password = htmlspecialchars($_POST["password"]);
echo "firstname: $firstname lastname: $lastname password: $password";
?>


With these changes, your Python code will send the data as form data in the request body, and your PHP code will be able to access the data using `$_POST`. This should resolve the "Undefined index" notices and correctly display the data in your localhost page.

Rate this post

4 of 5 based on 6036 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us