What is the best practice for reading and storing data from a <textarea> in PHP?

When reading and storing data from a <textarea> in PHP, it is best practice to use the htmlspecialchars() function to prevent any potential cross-site scripting (XSS) attacks. This function will convert special characters to HTML entities, ensuring that the data is safe to store and display.

// Read and store data from a &lt;textarea&gt;
if(isset($_POST[&#039;textarea_data&#039;])){
    $textarea_data = htmlspecialchars($_POST[&#039;textarea_data&#039;]);
    
    // Store the data in a database or file
    // For example, storing in a database using PDO
    $pdo = new PDO(&quot;mysql:host=localhost;dbname=mydatabase&quot;, &quot;username&quot;, &quot;password&quot;);
    $stmt = $pdo-&gt;prepare(&quot;INSERT INTO mytable (textarea_data) VALUES (:textarea_data)&quot;);
    $stmt-&gt;bindParam(&#039;:textarea_data&#039;, $textarea_data);
    $stmt-&gt;execute();
    
    echo &quot;Data stored successfully!&quot;;
}