In PHP, how to get an element using id?
P粉930448030
2023-08-23 00:09:38
<p>I would like to add an email sending system to my website. </p>
<p>The problem is when I try to assign a variable text from my HTML file, it doesn't happen. I want the content in the variable should be written in the message of the email. This is my code: </p>
<pre class="brush:php;toolbar:false;"><html>
<?php include('form.php'); ?>
<head>
</head>
<body>
<form action="./form.php" method="post">
<div name="name"><input type="text" id="name"></div>
<div name="surname"><input type="text" id="surname"></div>
<div name="message"><textarea rows="4" cols="50" id="message">Inserisci qui il tuo testo.</textarea></div>
<div name="subject"><select id="subject">
<option selected="selected">--Inserisci Oggetto--</option>
<option>Registrazione al sito</option>
<option>Recupero credenziali</option>
</select></div>
<input type="submit" value="Invia penzolini"/>
<input type="hidden" name="button_pressed" value="1" />
</form>
</body>
</html>
<?php
$dochtml = new domDocument();
$dochtml->loadHTML('index.html');
if(isset($_POST['button_pressed']))
{
//Get the name
$name = $dochtml->getElementById('name');
//Get the last name
$surname = $dochtml->getElementById('surname');
//Get the email subject
$subject = $dochtml->getElementById('subject');
//Message <70 characters
$msg = "Inviato da" . ' ' . $name . $surname . ' ' . $dochtml->getElementById('message'); // /n=space
// send email
mail("panzersit@gmail.com",$subject,$msg);
echo 'Email inviata.';
}
?></pre>
<p><br /></p>
PHP cannot access your DOM directly. PHP only runs on the server and simply receives requests and gives responses.
After submitting this form to its action page
./form.php
, the values entered into the form will be stored in$_POST
with the key name of itsname
Attributes. In your HTML code, add thename
attribute to the input tag like this:Now, if I submit this form and enter Zachary in the
name
input tag and Taylor in thesurname
input tag, I can get those values like this:In the
./form.php
file:$name = $_POST['name']; // "Zachary"
$surname = $_POST['surname']; // "Taylor"
To verify that there was any input first, use:
isset($_POST['key'])
, because sometimes the input value is not even sent to the action page when it is null. This prevents PHP from throwing an error when referencing a non-existent $_POST key.To get the posted data from the submitted form, you can use
$_POST['fieldname']
to achieve this.Just try the following and see what you get after the form is submitted.
Uncomment the two lines above, see what you get, and then comment them out again.