Custom WP form which changes user role on submit - php

Basically I have a page which displays to a user only when they're logged in, it has a custom contact form on it. When the form is submitted, their user role should automatically change to "Author".
I literally have no idea where to start with this, if anyone has any ideas or can help me out a little that would be amazing because I'm really struggling with this.
EDIT
This is what I currently have, all it does at the minute is send emails.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = trim(stripslashes($_POST['name']));
$email = trim(stripslashes($_POST['email']));
$subject = trim(stripslashes($_POST['subject']));
$message = trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';
$body = '<html><head></head><body>' .
'<b>Name:</b> ' . $name . '<br><br>' .
'<b>Email:</b> ' . $email . '<br><br>' .
'<b>Nature of Enquiry:</b> ' . $subject . '<br><br>' .
'<b>Message:</b> ' . nl2br($message) .
'</body></html>';
$headers = "From: " . strip_tags($email_from) . "\r\n";
$headers .= "Reply-To: ". strip_tags($email_from) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if( isset($_POST['checkbox']) ) {
mail($email_to, $subject, $body, $headers);
// Change user role to "author
echo '<p>You are now an author.</p>';
} else {
echo '<p>It appears you are a spambot, if this is a mistake please try again and check the "I am not a spambot" checkbox.</p>';
}
}
?>
<form method="post" action="#">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="<?php echo $name; ?>" required>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" value="<?php echo $email; ?>" required>
<label for="subject">Nature of Enquiry</label>
<input type="text" id="subject" name="subject" value="<?php echo $subject; ?>" required>
<label for="checkbox">I am not a spambot</label>
<input type="checkbox" id="checkbox" name="checkbox">
<label for="message">Message</label>
<textarea id="message" name="message" required><?php echo $message; ?></textarea>
<button type="submit">Submit</button>
</form>

This would be a matter of using the class WP_User and its set_role method.
$user_id = 2;
$role_name = 'author';
$user = new WP_User( $user_id );
$user->set_role( $role_name );

Related

PHP - Email form is sending over 50 mails after form submit

I have a problem that after I fill out the contact form on my HTML website I receive over 50 same E-mails. Its a HTML form connected to contact.php file which code is shown bellow. I have set everything but maybe there is a problem in my code or somewhere else.
My code is over here
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+ (ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Vyplnte meno.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Vyplnte email.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Zadali ste nesprávny e-mail, skúste to znovu.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Vyplnte text správy.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "noreply#marcelaskolenia.sk";
$address = "lubosmasura#gmail.com";
$toCustomer = $email;
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'Mate novu spravu od ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "Mate novu spravu od $name." . PHP_EOL . PHP_EOL;
$e_content = "\"$subject\"" . "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "Kontaktujte $name cez email, $email alebo cez mobil $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers .= 'To: Test <noreply#marcelaskolenia.sk>' . "\r\n";
$headers .= 'From: Testk <noreply#marcelaskolenia.sk>' . "\r\n";
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3 class'mark'>Sprava bola odoslana.</h3>";
echo "<p>Dakujeme <strong>$name</strong>, Vasa sprava nam bude dorucena.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
HTML code
<div class="contact_form">
<div id="message"></div>
<form id="contactform" class="row" action="contact.php" name="contactform" method="post">
<div class="col-md-12">
<input type="text" name="name" id="name" class="form-control" placeholder="Meno">
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<input type="text" name="phone" id="phone" class="form-control" placeholder="Telefónne číslo">
<input type="text" name="subject" id="subject" class="form-control" placeholder="Predmet">
<textarea class="form-control" name="comments" id="comments" rows="6" placeholder="Text správy"></textarea>
<button type="submit" value="SEND" id="submit" class="btn btn-primary"> ODOSLAŤ</button>
</div>
</form>
</div>
</div><!-- end col -->
Any Ideas why is this happening?
Thank you.

Puzzling php contact form not working. Any insights?

This php contact form I'm using returns the message that my message has be sent but no email is received by the specified email address.
Here's the php:
<?php
$to = 'blahbahblah#gmail.com';
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$html = "";
$html .= "Name: " . htmlentities($name, ENT_QUOTES, "UTF-8") . "<br>\n";
$html .= "Email: " . htmlentities($email, ENT_QUOTES, "UTF-8") . "<br>\n";
$html .= "Message: " . htmlentities($message, ENT_QUOTES, "UTF-8") . "<br>\n";
$headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=utf-8\r\n";
$headers .= "From: " . $name . "<". $email .">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$html = utf8_decode($html);
mail($to, $subject, $html, $headers);
if ($html)
echo 'ok';
else
echo 'error';
} else {
echo "error";
}
?>
And here's the html associated with it:
<form method="post" action="contact.php">
<p>
<input type="text" name="name" id="name" placeholder="Name" />
</p>
<p>
<input type="text" name="email" id="email" placeholder="Email" />
</p>
<p>
<input type="text" name="subject" id="subject" placeholder="Subject" />
</p>
<div class="textarea-wrapper">
<textarea name="message" id="message" cols="45" rows="10" placeholder="Message"></textarea>
</div>
<button id="submit">Send</button>
</form>
I realize issues like these are frequent, but I've unable to figure it out. Any insight is greatly appreciated.
"<br>\n"
use "\r\n" instead and try again
You need to change your SMTP settings per your conversation with the support rep. These are set in your PHP.INI
The From address should belong to the domain from where you are running the script. If your script is running on your-website.com then the From address should be like xyz#website-name.com
$headers = "From: xyz#website-name.com";
mail($to,$subj,$body,$headers);
To check the contact form that I have used, visit: http://manageproac.com/support/

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

This is the error coming while i try to send mail using php.
Failed to load resource: the server responded with a status of 405 (Method Not Allowed) sendmail.php
this is the form
<form action="sendmail.php" method="post" id="contactform" >
<div id='name-error' class='error'>Please enter your name.</div>
<input name="name" placeholder="Name" class="form-control" type="text" id="name">
<div id='email-error' class='error'>Please enter your valid E-mail ID.</div>
<input name="email" placeholder="Email" class="form-control" type="text" id="email">
<div id='subject-error' class='error'>Please enter the subject.</div>
<input name="subject" placeholder="Subject" class="form-control" type="text" id="subject">
<div id='message-error' class='error'>Please enter your message.</div>
<textarea name="message" placeholder="Message" id="message" rows="4" class="form-control"></textarea>
<div id='mail-success' class='success'>Your message has been sent successfully.</div>
<div id='mail-fail' class='error'> Sorry, error occured this time sending your message.</div>
<input type="submit" value="Send Message" class="form-control" id="send-message">
</form>
this is the query
$.post("sendmail.php", $("#contactform").serialize(), function(result){
enter code here if (result == 'sent'){
$('#mail-success').slideDown(500).delay(1000).slideUp(500);
$('#send-message').removeAttr('disabled').attr('value', 'Send Message');
} else{
$('#mail-fail').slideDown(500).delay(1000).slideUp(500);
$('#send-message').removeAttr('disabled').attr('value', 'Send Message');
}
});
}
});
this is the sendmail.php file
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$from = "info#vonesoft.com";
$to = "mujtaba1004#gmail.com";
$head = "New Contact Lead - VOneSoft";
$body = "Hi , <br /><br />";
$body .= "<table border='1' cellpadding='4' cellspacing='0'>";
$body .= "<tr><td>Name </td><td> " . $name . " </td></tr>";
$body .= "<tr><td>Email </td><td> " . $email . " </td></tr>";
$body .= "<tr><td>Subject </td><td> " . $subject . " </td></tr>";
$body .= "<tr><td>Message </td><td> " . $message . " </td></tr>";
$body .= "</table>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= "From:" . $from "\r\n";
mail($to, $head, $body, $headers);
echo '1';
?>
You forgot to concatenate here
$headers .= "From:" . $from. "\r\n";
-------------^

php contact form not sending mail after validation

I'm using a contact form for my website, which I validate and then email to myself, the validation is working correctly and it emails me if the user enters all the details correctly first time. However if the user enters incorrect data, then corrects it and hits send again, it won't send an email, below is the form and PHP code I have so far.
HTML code for contact form
<form action="contact.php" method="post">
<fieldset>
<label for="name">Name:<span class="star">*</span></label> <br />
<input type="text" name="name" id="name" placeholder="Enter your name" maxlength="50" required />
<label for="email">Email:<span class="star">*</span></label> <br />
<input type="email" name="email" id="email" placeholder="Enter your email address" maxlength="100" required />
<label for="number">Telephone: </label><input type="tel" name="number" id="number" placeholder="Enter your phone number" maxlength="12" />
<label for="message">Message:<span class="star">*</span></label>
<textarea name="message" id="message" placeholder="Enter your message" cols="54" rows="5" required></textarea>
<p class="small"><span class="star">*</span> Denotes a required field </p>
<input type="submit" id="send" name="send" value="Send" />
</fieldset>
</form>
PHP code for sending the form
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
{
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
}
$send = $_POST['send'];
$message = "";
foreach ($details as $field => $detail)
$message .= $field . ": " . $detail . "<br />";
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$message = wordwrap($message, 70, "/r/n");
$headers = "From ". $details['email'];
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
if ($send)
{
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
echo "<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>";
}
}
else
{
mail($to, $subject, $message, $headers);
echo "<p class='success'>Mail was sent successfully</p>";
}
EDIT
In order for the code to work on the same page, you need to set the action to action=""
Otherwise, you need to use two pages. One for your form and one for contact.php which is your handler. I suggest you use two pages, but here is a version that will work inside one page.
<?php
if(isset($_POST['send'])) {
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
die("<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>");
}
$message = "";
foreach ($details as $field => $detail)
$message .= $field . ": " . $detail . "\n";
$send = $_POST['send'];
$email = $_POST['email'];
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$headers = "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
echo "<p class='success'>Mail was sent successfully</p>";
exit;
} // closing brace for if(isset($_POST['send'])) {
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post">
<fieldset>
<label for="name">Name:<span class="star">*</span></label> <br />
<input type="text" name="name" id="name" placeholder="Enter your name" maxlength="50" />
<label for="email">Email:<span class="star">*</span></label> <br />
<input type="email" name="email" id="email" placeholder="Enter your email address" maxlength="100" />
<label for="number">Telephone: </label><input type="tel" name="number" id="number" placeholder="Enter your phone number" maxlength="12" />
<label for="message">Message:<span class="star">*</span></label>
<textarea name="message" id="message" placeholder="Enter your message" cols="54" rows="5" ></textarea>
<p class="small"><span class="star">*</span> Denotes a required field </p>
<input type="submit" id="send" name="send" value="Send" />
</fieldset>
</form>
</body>
</html>
Original answer
This line is not properly formatted.
$message = wordwrap($message, 70, "/r/n");
change it to:
$message = wordwrap($message, 70, "\r\n");
You need to use \ instead of /
EDIT
The only way I could get your form to work, is to add a die function.
Try this now:
<?php
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
die("<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>");
}
$message = "";
foreach ($details as $field => $detail)
$message .= $field . ": " . $detail . "\n";
$send = $_POST['send'];
$email = $_POST['email'];
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$headers = "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
echo "<p class='success'>Mail was sent successfully</p>";
exit;
?>

Hide web page if no variable present in the url

I have created a form that pulls a variable from a url using the following code:
<?php $id = $_GET['id']; echo $id; ?>
Using this is link as an example (http://www.mydomain.co.uk/customerform.php?id=12) it would display 12 on the webpage.
What I would like to know, is it possible to stop the web page from loading if there is no varible in the URL e.g ?id=12 ?
Either in php, javascript?
So If you visited the following link, the web page would display:
http://www.mydomain.co.uk/customerform.php?id=12
and if you visited this link (without the variable), the page would not display:
http://www.mydomain.co.uk/customerform.php
Thank you for any help.
Update below...
I have added Krishnanunni's code and it successfully prevents the web page from displaying if the is no vartiable in the url. But adding this code prevents the form submitting...
Is there a way of keeping the url variable when the form is submitted?
Can anyone help? Thanks
<body id="main_body" >
<div id="form_container">
<?
/* only load page is variable is presnt in the URL */
if (!isset($_GET['id']) || empty($_GET['id']))
{
die("Bad Request");
}
?>
<?
/* Mailer with Attachments */
$action = $_REQUEST['action'];
global $action;
function showForm() {
?>
<form id="contact" class="appnitro" name="idform" enctype="multipart/form-data" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000"/>
<input name="to_email" type="hidden" id="to_email" value="myemail#domain.co.uk"/>
<div>
<input id="invoice" name="invoice" class="element text medium" type="hidden" maxlength="255" value="<?php $id = $_GET['id']; echo $id; ?>"/>
</div>
<div>
<input id="subject" name="subject" class="element text medium" type="hidden" maxlength="255" value="Enquiry Form - (Invoice: <?php $id = $_GET['id']; echo $id; ?>)"/>
</div>
<label class="description" for="from_name">Name </label>
<div>
<input id="from_name" name="from_name" class="element text medium" type="text" maxlength="255" value=""/>
</div>
<label class="description" for="position">Position </label>
<div>
<input id="position" name="position" class="element text medium" type="text" maxlength="255" value=""/>
</div>
<label class="description" for="uemail"> Email </label>
<div>
<input id="email" name="email" class="element text medium" type="text" maxlength="255" value=""/>
</div>
<label class="description" for="phone"> Phone </label>
<div>
<input id="phone" name="phone" class="element text medium" type="text" maxlength="255" value=""/>
</div>
<input name="Reset" type="reset" class="contactform_small" value="Reset" />
<input name="Submit2" type="submit" class="contactform_small" id="Submit" value="Submit" />
</form>
<?
}
function sendMail() {
if (!isset ($_POST['to_email'])) { //Oops, forgot your email addy!
die ("<p>Oops! You forgot to fill out the email address! Click on the back arrow to go back</p>");
}
else {
$to_name = "MY BUSINESS";
$from_name = stripslashes($_POST['from_name']);
$subject = Trim(stripslashes($_POST['subject']));
$to_email = $_POST['to_email'];
$EmailFrom = Trim(stripslashes($_POST['email']));
// get posted data into local variables
$position = Trim(stripslashes($_POST['position']));
$position2 = Trim(stripslashes($_POST['position2']));
$phone = Trim(stripslashes($_POST['phone']));
$invoice = Trim(stripslashes($_POST['invoice']));
//Let's start our headers
$headers = "From: $EmailFrom<" . $_POST['email'] . ">\n";
$headers .= "Reply-To: <" . $_POST['email'] . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
$headers .= "X-Sender: $from_name<" . $_POST['email'] . ">\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['email'] . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "Invoice: ";
$message .= $invoice;
$message .= "\n";
$message .= "\n";
$message .= "My Business Enquiry Form";
$message .= "\n";
$message .= "\n";
$message .= "Contact Details: ";
$message .= "\n";
$message .= "\n";
$message .= "Name: ";
$message .= $from_name;
$message .= "\n";
$message .= "Position: ";
$message .= $position;
$message .= "\n";
$message .= "Email: ";
$message .= $EmailFrom;
$message .= "\n";
$message .= "Phone: ";
$message .= $phone;
$message .= "\n";
$message .= "\n";
// send the message
mail("$to_name<$to_email>", $subject, $message, $headers);
print "Form sent successfully";
}
}
?>
<?
switch ($action) {
case "send":
sendMail();
showForm();
break;
default:
showForm();
}
?>
<div id="footer">
</div>
</div>
</body>
Start your php page with this code
if (!isset($_GET['id']) || empty($_GET['id']))
{
die("Bad Request");
}
This should solve your problem

Categories