Security fix in PHP- Python and Cybersecurity

Security fix in PHP- Python and Cybersecurity

1. PHP Bug Example: Form Not Submitting

📄 Code:

php
<?php
if ($_POST['submit']) {
$name = $_POST['name'];
echo "Hello, $name";
}
?>
<form method="post">
<input type="text" name="name">
<button type="submit">Submit</button>
</form>

Bug:

Submitting the form shows nothing, even though no error appears.


🔍 Debugging Steps:

✅ Step 1: Check if $_POST['submit'] is set

But wait — your form doesn’t have:

html
<input type="submit" name="submit">

The submit button is a <button>, not an input with a name="submit". So $_POST['submit'] is not being sent.


Fix:

Change the PHP condition:

php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
echo "Hello, $name";
}

Now it works! ✅

🐍 2. Python Bug Example: API Returning Wrong Data

🧪 Scenario:

You’re building a Flask API:

python

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route(‘/double’, methods=[‘POST’])
def double_number():
num = request.form[‘num’]
return jsonify({‘result’: num * 2})

app.run()


Bug:

Calling /double with num=5 returns:

json
{"result": "55"}

🧠 Why?

Because request.form['num'] is a string, not a number. "5" * 2 in Python results in string repetition, not math.


Fix:

Convert it to an integer first:

python
num = int(request.form['num'])

Now:

json
{"result": 10}

🛡️ 3. Cybersecurity Bug Example: SQL Injection

🔥 Vulnerable PHP Code:

php
$username = $_POST['username'];
$password = $_POST['password'];
$query = “SELECT * FROM users WHERE username = ‘$username‘ AND password = ‘$password‘”;
$result = mysqli_query($conn, $query);

Bug:

A hacker enters:

  • username = ' OR 1=1 --

  • password = anything

The resulting query:

sql
SELECT * FROM users WHERE username = '' OR 1=1 -- ' AND password = 'anything'

This bypasses login and grants access to any user. 🔓


Fix (Use Prepared Statements):

php
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

This sanitizes inputs and blocks SQL injection.


🔚 Summary Table

Example Bug Fix
PHP Form $_POST['submit'] not set Use $_SERVER['REQUEST_METHOD'] == 'POST'
Python API String math instead of integer math Use int() to convert input
SQL Injection User input injected into raw query Use prepared statements

Related posts

Leave a Comment