In the context of PHP, what are some common mistakes to avoid when manipulating strings for graphic output?
One common mistake to avoid when manipulating strings for graphic output in PHP is not properly escaping special characters. This can lead to vulnerabilities like cross-site scripting (XSS) attacks. To solve this issue, always use functions like htmlspecialchars() when outputting user-generated content to ensure special characters are properly encoded.
// Incorrect way without escaping special characters
$userInput = "<script>alert('XSS attack!');</script>";
echo $userInput;
// Correct way with htmlspecialchars() for escaping special characters
$userInput = "<script>alert('XSS attack!');</script>";
echo htmlspecialchars($userInput);