How can PHP developers ensure data integrity and prevent injection attacks when passing variables between scripts?
To ensure data integrity and prevent injection attacks when passing variables between scripts, PHP developers should use prepared statements with parameterized queries to sanitize user input. This helps to prevent SQL injection attacks by separating the SQL query logic from the user input data.
// Example of using prepared statements to prevent SQL injection attacks
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL query using a placeholder for the user input
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the user input variable
$username = $_POST['username'];
// Execute the query
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the statement and connection
$stmt->close();
$conn->close();