<p>Directly splicing user input can lead to serious security vulnerabilities and security alternatives must be used. 1. It is prohibited to directly splice user input into SQL, commands or HTML to prevent injection attacks; 2. Database queries must use preprocessing statements (such as PDO parameterized queries) to ensure separation of data from code; 3. When outputting to HTML, special characters must be escaped with htmlspecialchars() to prevent XSS; 4. Avoid passing user input into system commands, use escapeshellarg() if necessary and strictly verify input; 5. All inputs should be type-converted and filtered (such as (int) or filter_var). Always consider user input as untrusted data, keep the data and code separate through design, and fundamentally eliminate the risk of injection. </p>
<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175382457121854.jpg" class="lazy" alt="Secure String Concatenation: Preventing Injection Vulnerabilities in PHP"></p>
<p> When handling user input in PHP, one of the most common — and dangerous — mistakes is insecure string concatenation, especially when building dynamic queries, file paths, or HTML output. This practice opens the door to injection vulnerabilities like SQL injection, command injection, or cross-site scripting (XSS). The key to preventing these issues lies in understanding <strong>secure string concatenation</strong> and adopting safer alternatives. </p>
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175382457254217.jpeg" class="lazy" alt="Secure String Concatenation: Preventing Injection Vulnerabilities in PHP"><h3 id="Why-Direct-String-Concatenation-Is-Risky"> 1. Why Direct String Concatenation Is Risky</h3>
<p> Concatenating user input directly into strings that are later interpreted as code (eg, SQL queries or shell commands) is dangerous because it blurs the line between <em>data</em> and <em>code</em> . For example:</p><pre class='brush:php;toolbar:false;'> // ? Insecure: Direct concatenation
$username = $_POST[&#39;username&#39;];
$password = $_POST[&#39;password&#39;];
$query = "SELECT * FROM users WHERE username = &#39;$username&#39; AND password = &#39;$password&#39;";
mysqli_query($connection, $query);</pre><p> An attacker could input <code>&#39; OR &#39;1&#39;=&#39;1</code> as the username, altering the query's logic — classic SQL injection. </p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175382457469303.jpeg" class="lazy" alt="Secure String Concatenation: Preventing Injection Vulnerabilities in PHP" /><h3 id="Use-Prepared-Statements-for-Database-Queries"> 2. Use Prepared Statements for Database Queries</h3><p> The best defense for SQL injection is <strong>parameterized queries (prepared statements)</strong> . They separate SQL logic from data, so user input is never treated as part of the command.</p><pre class='brush:php;toolbar:false;'> // ? Secure: Using prepared statements with PDO
$username = $_POST[&#39;username&#39;];
$password = $_POST[&#39;password&#39;];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$user = $stmt->fetch();</pre><p> Or with named placeholders: </p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175382457588935.jpeg" class="lazy" alt="Secure String Concatenation: Preventing Injection Vulnerabilities in PHP" /><pre class='brush:php;toolbar:false;'> $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute([&#39;username&#39; => $username, &#39;password&#39; => $password]);</pre><p> This way, even if malicious input is provided, it's treated strictly as data.</p><blockquote><p> ? Note: Never concatenate variables into SQL strings — even if you "sanitize" them. Use placeholders every time.</p></blockquote><h3 id="Escape-Output-for-HTML-Contexts"> 3. Escape Output for HTML Contexts</h3><p> When outputting user data in HTML, direct concatenation can lead to XSS attacks.</p><pre class='brush:php;toolbar:false;'> // ? Dangerous
echo "<p>Welcome, " . $_GET[&#39;name&#39;] . "</p>";
// Input: <script>alert(&#39;xss&#39;)</script> → executes JS</pre><p> Always escape output using <code>htmlspecialchars()</code> :</p><pre class='brush:php;toolbar:false;'> // ? Safe
$name = htmlspecialchars($_GET[&#39;name&#39;], ENT_QUOTES, &#39;UTF-8&#39;);
echo "<p>Welcome, " . $name . "</p>";</pre><p> This converts <code><</code> , <code>></code> , <code>&</code> , etc., into safe HTML entities.</p><h3 id="Avoid-Concatenating-Input-into-System-Commands"> 4. Avoid Concatenating Input into System Commands</h3><p> Never pass user input directly into functions like <code>exec()</code> , <code>shell_exec()</code> , or <code>system()</code> .</p><pre class='brush:php;toolbar:false;'> // ? Dangerous
$filename = $_GET[&#39;file&#39;];
exec("cat /var/data/" . $filename, $output);</pre><p> An attacker could set <code>file=; rm -rf /</code> and delete files.</p><p> Instead:</p><ul><li> <strong>Validate input strictly</strong> (whitelist allowed characters/filenames).</li><li> Use <strong>built-in PHP functions</strong> instead of shell commands when possible.</li><li> If you must use shell commands, use <code>escapeshellarg()</code> or <code>escapeshellcmd()</code> :</li></ul><pre class='brush:php;toolbar:false;'> // ? Safer (but still risk — prefer alternatives)
$filename = escapeshellarg($_GET[&#39;file&#39;]);
exec("cat /var/data/" . $filename, $output);</pre><p> Better yet, avoid shell execution entirely or use secure APIs.</p><h3 id="Use-Type-Casting-and-Input-Validation"> 5. Use Type Casting and Input Validation</h3><p> Before using any input, validate and sanitize it:</p><pre class='brush:php;toolbar:false;'> // ? Validate and cast
$userId = (int)$_GET[&#39;id&#39;]; // Forces integer, truncates garbage
$query = "SELECT * FROM users WHERE id = ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$userId]);</pre><p> For strings:</p><ul><li> Use <code>filter_var()</code> with appropriate filters:<pre class='brush:php;toolbar:false;'> $email = filter_var($_POST[&#39;email&#39;], FILTER_VALIDATE_EMAIL);
if ($email) { /* proceed */ }</pre><h3 id="Summary-Best-Practices"> Summary: Best Practices</h3>
<p> To prevent injection via insecure string concatenation:</p>
<ul>
<li> ? Always use <strong>prepared statements</strong> for SQL.</li>
<li> ? <strong>Escape output</strong> with <code>htmlspecialchars()</code> for HTML.</li>
<li> ? <strong>Avoid shell commands</strong> with user input; if unavoidable, use <code>escapeshellarg()</code> .</li>
<li> ? <strong>Validate and sanitize</strong> all inputs (whitelist acceptable values).</li>
<li> ? Treat all user input as untrusted — no exceptions.</li>
</ul>
<p> Secure string handling isn't about escaping more characters — it's about <strong>never letting data becomes code</strong> . Use structured interfaces (like prepared statements) that maintain this separation by design.</p>
<p> Basically, if you're building strings that will be interpreted, don't mix in raw user data. There's almost always a safer way.</p>
The above is the detailed content of Secure String Concatenation: Preventing Injection Vulnerabilities in PHP. For more information, please follow other related articles on the PHP Chinese website!