• Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Sign in to follow this  
Followers 0
Winnetouch

PHP contact form

8 posts in this topic

Hello.

A couple of weeks ago I concluded a couple of front end development courses and we only touched upon php coding. Since we didn't do much of it I used w3schools.com to learn some basics. I used the tutorial to make a contact form but I have a little problem. Currently the form is set (or rather was until I removed some code) to show anything that was entered in to the form on the site (basically like in this tutorial: https://www.w3schools.com/php/php_forms.asp). What I want the form to do is send the entered information to a predefined email address. But that's not all. It's going to be used on a singlepage website layout. I want the form to also show a prompt box that warns the user that either something went wrong or that the message was sent and reload the page back to the same position (I realise I need to use index#pageposition to do this but I don't know how to implement the link).

Currently this only warns the user of what he did wrong (but not in a prompt box that something wrong happened) and reloads the page to the top. I'm a PHP noob (big noob), and I would appreciate if someone can help me out with this. Thank you :).

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Vpiši ime!";
  } else {
    $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
          $nameErr = "Dovoljene so samo črke in presledki!"; 
        }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Vpiši email naslov!";
  } else {
    $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Vpišite veljaven email naslov!"; 
        }
  }
    
  if (empty($_POST["subject"])) {
    $subjectErr = "Vpiši naslov sporočila!";
  } else {
    $subject = test_input($_POST["subject"]);
  }

  if (empty($_POST["message"])) {
    $messageErr = "Vpiši sporočilo!";
  } else {
    $message = test_input($_POST["message"]);
  }
    
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>

<!DOCTYPE html>

<html>

        <link rel="stylesheet" href="style.css" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
        <meta name="kontakt">

<head>


</head>

<body>

        <div class="col-md-12">

                <div class="form-area">  
                    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                    <br style="clear:both">
                                <h3>Piši nam</h3>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="name" placeholder="Ime">
                                    <span class="error">* <?php echo $nameErr;?></span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="email" placeholder="Email">
                                    <span class="error">* <?php echo $emailErr;?></span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="subject" placeholder="Naslov">
                                    <span class="error">* <?php echo $subjectErr;?></span>
                                </div>
                                <div class="form-group">
                                    <textarea class="form-control" type="textarea" placeholder="Sporočilo" name=message rows="8"></textarea>
                                    <span class="error">* <?php echo $messageErr;?></span>
                                </div>

                        <input type="submit" class="btn btn-primary" name="submit" value="Submit">  

                    <!--<button type="button" name="submit" class="btn btn-primary pull-right" value="Submit">Pošlji</button>-->
                    </form>
                </div>

        </div> 

</body>

 

Share this post


Link to post
Share on other sites

May I suggest that you limit your issues to one at a time and only post the code necessary to illustrate the particular issue in question.

It would greatly encourage other users to respond to your questions -- well, at least me, at any rate.

I do not want to pretend to speak for everyone.

Roddy

 

Share this post


Link to post
Share on other sites

Then let's limit the issue to make the contact form work as a contact form in the first place. How do I verify that everything was entered correctly and then send the email.

Share this post


Link to post
Share on other sites

If you want the form error handling to be smooth and user friendly, isuggest you use javascript/ajax  check this js/ajax .

for the mailing part check this : https://www.w3schools.com/php/func_mail_mail.asp .(if you are working on a local environement the mail will probably fail,you would have to tweek your php.ini but still the email received might be considered as spam) .

Good luck.

Share this post


Link to post
Share on other sites

you can split the page into 2 pages for example

index.php :

<!DOCTYPE html>

<html>

        <link rel="stylesheet" href="style.css" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
        <meta name="kontakt">
		

<head>


</head>

<body>

        <div class="col-md-12">

                <div class="form-area">  
				<div id="error" style="color:#FF6633"></div>
                    <form method="post" action="#" onsubmit="sendmail()">
                    <br style="clear:both">
                                <h3>Piši nam</h3>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="fname" placeholder="Ime" id="idname">
                                    <span class="error">* </span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="email" placeholder="Email" id="idemail">
                                    <span class="error">* </span>
                                </div>
                                <div class="form-group">
                                    <input type="text" class="form-control" name="subject" placeholder="Naslov" id="idsubject">
                                    <span class="error">* </span>
                                </div>
                                <div class="form-group">
                                    <textarea class="form-control" type="textarea" placeholder="Sporočilo" id="idmessage" name="message" rows="8"></textarea>
                                    <span class="error">* </span>
                                </div>

                        <input type="submit" class="btn btn-primary" name="submit" value="Submit">  

                    <!--<button type="button" name="submit" class="btn btn-primary pull-right" value="Submit">Pošlji</button>-->
                    </form>
                </div>

        </div> 
<script>
		document.getElementById("error").display="none";
		function sendmail()
		{
		 event.preventDefault();
		 fname=document.getElementById("idname").value;
		 email=document.getElementById("idemail").value;
		 subject=document.getElementById("idsubject").value;
		 message=document.getElementById("idmessage").value;
		 //alert(fname);
		 
		  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

						
					 	document.getElementById("error").innerHTML = this.responseText;
						
						

			
					  	 
					
    }
  };
  xhttp.open("POST", "./verify.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("fname=" + fname + "&email=" + email + "&subject=" + subject +"&message=" + message);
		 
		 
		}
		</script>
</body>
</html>

and a seconf page that handles the the inputs for eg : verify.php

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["fname"])) {
    echo "Vpiši ime!";
	die();
  } else {
    $name = test_input($_POST["fname"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
          echo "Dovoljene so samo črke in presledki!"; 
		  die();
        }
  }
  
  if (empty($_POST["email"])) {
    echo "Vpiši email naslov!";
	die();
  } else {
    $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Vpišite veljaven email naslov!"; 
		die();
        }
  }
    
  if (empty($_POST["subject"])) {
    echo "Vpiši naslov sporočila!";
	die();
  } else {
    $subject = test_input($_POST["subject"]);
  }

  if (empty($_POST["message"])) {
    echo "Vpiši sporočilo!";
	die();
  } else {
    $message = test_input($_POST["message"]);
  }
    
	// email Stuff goes here here
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>

 

Share this post


Link to post
Share on other sites
20 hours ago, john_jack said:

If you want the form error handling to be smooth and user friendly, isuggest you use javascript/ajax  check this js/ajax .

for the mailing part check this : https://www.w3schools.com/php/func_mail_mail.asp .(if you are working on a local environement the mail will probably fail,you would have to tweek your php.ini but still the email received might be considered as spam) .

Good luck.

Ok... I'll be honest, I didn't understand half of what you said :P. I don't have a php.ini. All I have is a single index.php site because it's a single page site that scrolls up and down. This contact form is the only missing piece. The site is located here: http://viki.si/demosites/postaniskavt/index.php

All I really understand up until now with php is how the form that I've created thus far is verified. I fail to understand how splitting the file in to 2 would make it function like it should. I understand that splitting the site in two would make it more menagable in the background but that's not really my concern for now. For now all I want is for the form that I've created up until now (with all the verification) to check if everything is entered correctly and send the email and send it only if everything is enetered correctly. I'll deal with the alert windows later when the form is functioning as it should. That's probably just a simple add on to the "if" statement anyway if I understand correctly. But I'm lost on how to form the if sentence to make the form check if every single information was entered correctly in to the form.

Share this post


Link to post
Share on other sites

All PHP servers have an INI file which contains various settings and options, whether or not you have access to that file.  If you don't have access to that file there are still several options you can change other ways:

http://php.net/manual/en/configuration.php

As far as handling the form, you should really look into using ajax to submit the form information so that the entire page doesn't need to refresh when they submit the form.  With a 1-page site like that, people would probably not expect the entire thing to refresh when they submit the form.  If you want to go that route then you'll need to use Javascript to gather the form data and send an ajax request to PHP to validate and send the email.  That PHP script would be a different file than your index page, its only job would be to validate and send the email, and return any success or error messages back to Javascript.  That's the example that was shown above, one page with the HTML form and some Javascript to handle it, and a PHP script with the code to validate and process the form.

Regardless of which path you decide to do, I would recommend using something like PHPMailer instead of the built-in mail function.

Share this post


Link to post
Share on other sites
On 4. 4. 2017 at 8:55 PM, justsomeguy said:

All PHP servers have an INI file which contains various settings and options, whether or not you have access to that file.  If you don't have access to that file there are still several options you can change other ways:

http://php.net/manual/en/configuration.php

As far as handling the form, you should really look into using ajax to submit the form information so that the entire page doesn't need to refresh when they submit the form.  With a 1-page site like that, people would probably not expect the entire thing to refresh when they submit the form.  If you want to go that route then you'll need to use Javascript to gather the form data and send an ajax request to PHP to validate and send the email.  That PHP script would be a different file than your index page, its only job would be to validate and send the email, and return any success or error messages back to Javascript.  That's the example that was shown above, one page with the HTML form and some Javascript to handle it, and a PHP script with the code to validate and process the form.

Regardless of which path you decide to do, I would recommend using something like PHPMailer instead of the built-in mail function.

Thanks for the info. I'll look in to PHP mailer and maybe take a look at some tutorials.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0