PHP security, intval and htmlspecialchars

<?php

$id = intval($_GET['id']);

 $sql = mysql_query("SELECT username FROM users WHERE id = $id");
 $row = mysql_fetch_assoc($sql);

$user = htmlspecialchars($row['username']);

?>

<h1>User:<?php echo $user ?></h1>

Can you see any threats in the above code? Should I use htmlspecialchars for everything I output? And should I use is_numeric or intval to verify that get is numeric?

I am just building a minimal site. I'm just wondering if the above code is vulnerable to SQL injection, xss?

+3
source share
3 answers

Generally speaking, it mysql_real_escape_string()is preferable, but since this number is intval()in order. So yes, it looks good in terms of security.

, ints 32 , , , ~ 2,1 , . , , .

, cookie (- ).

+8

PDO . , , .

, , , , . , PDO:

# Make a database connection
$db = new PDO('mysql:dbname=your_db;host=your_db_server', 'username',
    'password');

# The placeholder (:id) will be replaced with the actual value
$sql = 'SELECT username FROM users WHERE id=:id';

# Prepare the statement
$stmt = $db->prepare($sql);

# Now replace the placeholder (:id) with the actual value. This
# is called "binding" the value. Note that you don't have to
# convert it or escape it when you do it this way.
$stmt->bindValue(':id', $id);

# Run the query
$stmt->execute();

# Get the results
$row = $stmt->fetch();

# Clean up
$stmt->closeCursor();

# Do your stuff
$user = htmlspecialchars($row['username']);

; , . bindValue, SQL.

+5

,

int; SQL-.
" ", .

id ​​, mysql_real_escape_string, intval : -)


(, HTML, htmlspecialchars ); HTML/JS.


, : -)


, -, mysqli ( mysql) / PDO; -)

This will allow you to take advantage of the functionality provided by the latest versions of MySQL, such as prepared statements , which are a good way to protect against SQL injection!

0
source

Source: https://habr.com/ru/post/1714130/


All Articles