www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: easy (or is it?) way to help a user with a mail form

  1. #1
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77

    easy (or is it?) way to help a user with a mail form

    I'm a total newb at PHP, but I'm an OK coder in general and thought an HTML email form that uses a PHP script (in a separate file), would be a good way for me to learn. My hosting company's mailform soultion is crumby anyway, so I figured this way I'll end up with my own mailform in the process. :-) Well thankfully there are a lot of free tutorials around, and with them I was able to do a fair initial job. My site, upon clicking the contact form, will launch a smaller separate HTML window (the site is at www.elfintechnologies.com, and the CONTACT link is on the far right of the menu). After the SUBMIT, and provided all the validation goes well, another HTML page is substituted thanking the visitor, and a button is offered to close the window. I do this with a hidden 'redirect' field in the form in which the URL of my "thanks" redirect page is passed as a value. So the PHP script can then launch it using the header() function.

    But thats fine if all goes well! I'm a little stuck now understanding, philosophically, what to do ifs a validation failure happens. The example I was working from basically just created an error message which ultimately was displayed with a simple 'echo'. That works, but of course that error text then replaces the form completely. So the best i could do then is apologize that the visitor now has to close the window and start over by clicking the menu CONTACT option back on the main page. NOT user friendly!

    Now if this mail form were a pure javascript process, I probably know enough to find a way to display the error message, telling the user what he/she needs to do, by updating "textarea" field somewhere. That would mean I wouldn't have to leave the original page, and hence the user could correct the form without leaving it. But maybe that's not so easy now?! To do anything like that, I guess I first better understand what happens when the user clicks my SUBMIT button, and I guess i don't. Since the php script is accessed by a form "action", I'm not sure whether I could get the PHP script to return an error message to me.

    You'll all probably have to put yourselves back in the PHP 101 frame of mind to even understand my confusion. But the bottom line is that after the user SUBMITS, I'd like some way of telling them what they did wrong so they can correct it, without obliterating the form. Maybe I didn't choose such a simple task for a rainy Holiday afternoon!
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

  2. #2
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    711
    I use the value clause of my input tags to display a php var. That var is where I store the inputs when I receive the POST data. So - when an error occurs I send back my html (with the now-populated php vars) along with an error message and let them try again.

  3. #3
    Join Date
    May 2014
    Posts
    897
    The moment I see anyone talking about using 'redirects' via the header() function, I automatically assume they have been learning bad practices and/or overthinking something simple. Unless you are making redirects for old URL's on a site to a new location, there is rarely if ever a reason to do a redirect in PHP other than ignorance and bad advice.

    The reason I say this is that using a redirect via HEADER is an extra set of handshaking to/from the server, extra send/recieve of cookies to/from the server, and there's no need for it. You can track if a form has been sent/recieved using sessions, and doing so can actually help build a simple bit of spam blocking and security.

    When I write programs in PHP I generally operate on the 'one index to rule them all', but you could easily adapt the methodology to the 'one file per action' design method.

    Let's say you were making a contact form -- let's call it "contact.php" -- this is a rough overview of how I'd make it's functionality.

    contact.php

    This file would be the only one that the 'user' has any business calling. It is called to build the contact form, it is what the contact form would call -- one file, one action. All other 'files' called by it are library files, and as such should only be called by this one.

    It would work using the following process:

    1) Start sessions

    2) see if $_POST contains a value saying we came from a form
    >> If not, send a blank form and exit.

    3) see if our value saying we came from the form matches a value in our sessions
    >> If not, bomb out with a 'hacking attempt or cookies disabled' error.

    4) see if a timeout since our form was sent, stored in sessions, has elapsed.
    >> If so, re-send the form with a timeout error and exit.

    5) create an empty $errors array, and validate the values populating $errors by INDEX with the field name that had the error. (I often make a singleton to handle this)
    >> if count($errors) > 0, re-send the form with error messages inserted next to the appropriate fields and exit.

    6) no errors, send the message, destroy the session value that allows the form to be valid so it can't be re-used, send the 'thank you' page.

    The thank-you and form would both be separate .php files I would include using ... well... include. The themeContactForm.php would also do the following

    themeContactForm.php

    1) generate a unique ID stored in sessions and a hidden input in the form -- for comparison on submit. See step 2 under 'contact.php'

    2) take the current time, and add say... fifteen minutes to it and store that in the session, as the time when the form is no longer valid. See step 3 under 'contact.php'

    You'd be shocked how many spam-bots fall flat on their face from those two steps... So simple it shouldn't stop them, but let's face it, most spam-bots are built by script-kiddie simpletons.

    3) When outputting the form, check if $error[name] exists, if so show the error message for that field.

    4) for each input, see if $_POST[name] exists, and if so:
    echo ' value="', htmlspecialChars($_POST[name]), '"';

    ... and that's a rough overview of how I handle it. A single user-callable PHP file that hands off using "include" instead of wasting the server and the user's time on that extra 'send/refresh for nothing'.

    Usually my system also has an array that contains what the form elements are, their labels, and their appropriate data types. This lets me use one form generator to build all my forms, one validator to validate all my forms -- as both can then process the same array.

    ...an example of such an array structure:

    Code:
    $contactForm = [
    	'heading' => 'Contact Form',
    	'action' => 'contact.php',
    	'sessionId' => 'contactForm',
    	'fieldsets' => [
    		'contactInfo' => [
    			'legend' => 'Contact Information',
    			'fields' => [
    				'name' => [
    					'label' => 'Contact Name',
    					'type' => 'text',
    					'required' => true,
    					'maxLength' => 48
    				],
    				'eMail' => [
    					'label' => 'E-Mail Address:',
    					'type' => 'email', 
    					'required' => true
    				],
    				'phone' => [
    					'label' => 'Contact Phone',
    					'type' => 'phone'
    				],
    			],
    			'message' => [
    				'legend' => 'Contact Message',
    				'fields' => [
    					'subject' => [
    						'label' => 'Subject:',
    						'type' => 'text',
    						'maxLength' => 64
    					],
    					'message' => [
    						'label' => 'Message:',
    						'type' => 'textarea',
    						'required' => true
    					]
    				]
    			]
    		]
    	],
    	'submitValue' => 'Send Message',
    	'hiddens' => [
    		'name' => 'value'
    	]
    ];
    You just make some code that turns that into a form, and some code that uses the same array to validate the values. I also use sessionId as a prefix to the form element's ID's, since ID's need to be unique it helps to make them a bit more complex preventing conflicts with other forms/named elements.

    I hope this helps, or at least gets you thinking on different ways of handling things. I tried not to give you 'working code' and instead an explanation of the process, so you can try and figure out how to implement that yourself.

    As GSP used to say, "Don't tell a man how to do something; tell them what needs to be done, and let them impress you with their ingenuity."
    Java is to JavaScript as Ham is to Hamburger.

  4. #4
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77
    I appreciate all that deathshaddow. To be honest, its mostly over my head. As I said I was a total "newb" at PHP, and maybe I should have added that today's 'rainy afternoon project" (my mailform) was the VERY first time I EVER touched PHP. So I don't know exactly what is even meant by the underlying premise of a 'session". I'm basically a coder of static pages... HTML and CSS, but I needed a mail form. Well all the examples I've found online show an HTML form that calls (or has as the action of a form) a separate PHP file. And as for the "redirect" to display a "thank you" page, that was another thing I got from several online examples. In fact the "monstermail" (which is what my hostmoster account offers me) uses a redirect for the thank-you page too.

    My point is that this happens way too often... While trying to learn something, one looks for online examples, and hopes that when seeing similar methodology a 2 or 3 times in a row, you are at least on the right track enough to try it. Then there's always fiolks who will jump in and say the whole approach is completely wrong.

    So whats a newbie to do? Sure I'd like to master everything, but this "form mail" has been my first occasion to even see a PHP script as a necessary tool. So while I'm sure I'll find better ways in the future, and I'm sure your method is better already, my immediate goal is to finish what I've done, explain the limitations and issues I see, and then... before i abandon the whole thing for a completely new approach (I'm sure there are hundreds), see if what I'm doing is workable.
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

  5. #5
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    711
    IMHO there is no fault in using the header() call to send yourself somewhere else unless you are doing it for the wrong reason. IMHO the right reason is to send the user back to a menu screen from whence they came originally or to a login screen when you detect that they tried to enter this script the wrong way or similar reasons. It is not meant to be used to direct the flow of the CURRENT process to some other script that should have been 'included' in the current script. That is wasteful and shows a lack of design skills.

    Your simple exercise is a good start, albeit with errors. Learn how to use a good database interface (mysqli or PDO), prepared queries, how to check and validate and sanitize your inputs (anything that the user provides!) and how to arrange and write good code, both php and html.

  6. #6
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77
    ginerim: Based on what you said, it would seem then that using header() to go back to the form that contained the errors was a reasonable thing to do. But back to my original issue, I have not been able to do what you suggested, which is to use the value attribute to fill the input fields with variables from the PHP. The syntax I asked about doesn't work, but I don't see how it could anyway. If the PHP code is in a separate file, activated by the "action" attribute in the form tag, then the PHP variables don't exist yet.
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

  7. #7
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    711
    No. It is NOT the way to go. Basically you should contain the pieces of the project together as much as possible. The html (and any needed php vars) s/b in one place in your one script that you can then use for all purposes - a function that outputs your html and displays the initial screen with blank values; displays intermediate repeats of that screen with input values showing; and the final screen (if any) showing the empty screen again with a success message. The rest of that that ONE script should have sections of php code that handle the different portions of the process: recognizing the first time thru and showing the blank html, recognizing a submit with input and grabbing the values and editing them and either sending back error messages or posting to the db and sending back a success message - or if it is necessary using a header to go to a completely new script/page for the next phase of your project.

    Everyone has their own take on this. Above is what I have used. I'm sure there will be issues from other readers. Oh, well....

    As for your question about my suggestion - you should now see what I meant and how it will work if you do things this way instead of breaking up your code into multiple scripts. You can use an include statement to bring in your php code if you find it too complicated to have a large script file to be editing, but using a header to access code that SHOULD be in the current script is what others are seeing as a problem.

  8. #8
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77
    ginerjm...

    OK, that makes sense... sure if all the html AND the PHP functionality are all in one file, it should be a lot easier to exchange data, show errors, and retry without ever leaving the page. I think the problem is that I have been mislead by some misleading statements in several examples, that DID use separate PHP files. Those examples all pointed to hiding one's email address from spammers looking to harvest them. And THAT was my whole reason for going down this road. And in that regard I've been under the assumption that if I combined an HTML form and the PHP to process it in the same file, all a spam-bot would have to do is look at the source, and they would get the whole file, PHP and all. Thus, the separate files.

    I do see where having everything in one file would obviously make user interaction and correction a lot easier. But before I try combining everything into one file like this, let me go back to my original reason for this whole process. If I have my HTML form and PHP in the same file, AND ultimately the PHP contains code to send the form data to me, maybe like the below, will anyone be able to use a spam-bot tool to read the source code and harvest my address?

    // assume my processed message is in here...
    $email_message = "my processed form data message";

    // create email headers
    $email_to = "myEmailAddress@myDomain.com"; // RIPE FOR THE HARVEST?
    $email_subject = "Form Inquiry Inquiry";
    $headers = 'From: '.$email."\r\n".
    'Reply-To: '.$email."\r\n" .
    'X-Mailer: PHP/' . phpversion();

    // send the mail
    @mail($email_to, $email_subject, $email_message, $headers);
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

  9. #9
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,322
    You do not need everything in the same file, but you do have a single file that is the common entry point for all operations. That file can then include/require other files (including HTML templates and such for the actual views) as needed and as dictated by the controlling logic of that top level file (and as modified by any included files that also do any control logic processing). User access/login control can even be included by that file, so that you don't have to do redirects to a login page which then has to do a redirect back to the calling page on successful login (if it even knows what called it), and so forth.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  10. #10
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    711
    A couple of things to do.

    1 - STOP using the @ sign to suppress errors. You should FIX them, not ignore them.
    2 - things placed (stored) in the web-accessible tree are visible to anyone with the right tools that search the web. Things NOT placed in the web tree are not. I store all my sensitive php scripts in a folder above the root web folder so they will not be accessible to those http tools. Things like menu screens with html and php code but no real 'secrets' are safe wherever, but things like you have are not. How to get around that? I use a technique of having a very short script in my web area that does an include of the main script file stored in my (safe) php folder. My main menu that calls up my appls will point to the web-tree 'stub' file that then does the include of a php file that is not accessible to these tools.

    Ex. I have a script that is known as 'mypoolmenu.php'. In it there are a couple of lines to turn on error checking, set a default path for my php files, and then an include for the real guts of the application which I then call with - include($my_php_path."my_pool_menu.php")

  11. #11
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77
    Any others have any thoughts on this? Again, my reason for even considering processing mail form in a PHP file, is to make my email address invisible to spammers. Thats what all the tutorials I've run across say is the advantage. But based on this discussion it seems that all these tutorials are wrong, because the PHP files are just as visible to spammers as anything lease. Of course i can put my pages, PGP or otherwise in a private directory as was suggested above. But if thats really the extent of the protection, I might as well just use a javascript that at least makes my email address less obvious.
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

  12. #12
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,322
    No, your PHP source code is not visible to anyone accessing your site via HTTP unless something has gone wrong with your web server configuration or with what you have deployed on it. Assuming everything is copacetic, if someone surfs to http://www.example.com/mailform.php, all they can see is what that script outputs to the browser, not the source code that generated that output. If you have a concern that at some point in time there's a non-trivial possibility that your web server config might be compromised, causing *.php files to be treated as, say, plain HTML files, then yes, you can prevent anyone from seeing certain sensitive files by storing the outside of the web root and including them into the file that is directly accessed by the HTTP request.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  13. #13
    Join Date
    May 2014
    Posts
    897
    Quote Originally Posted by ginerjm View Post
    2 - things placed (stored) in the web-accessible tree are visible to anyone with the right tools that search the web. Things NOT placed in the web tree are not. I store all my sensitive php scripts in a folder above the root web folder so they will not be accessible to those http tools.
    There are TWO modes of thought on that -- the first is what you are doing, the second is to use functions and classes ONLY in your library PHP files, so if you call them directly via HTTP, they don't output anything.

    Since the OTHER risk -- readfile and/or include during a code elevation -- will work regardless of where you put the files.

    That's actually interpreted language security 101 -- files the user shouldn't be calling directly shouldn't output anything or run any code... which is a hefty part of why I call turdpress "insecure by design" -- well, alongside the idiocy of placing security info in DEFINE.

    Of course, on my own sites I use 'one index to rule them all' -- I have a whitelist in my htaccess of files to be processed normally, and ALL other file requests are passed to index.php ... you know what file extension is NOT on my whitelist? PHP -- any attempt to access via http my library files will be redirected to my index.php; good luck getting past that.

    But even if they did, my library files are filled with nothing but functions, classes and variable declarations, meaning they output jack **** if you were able to call them via HTTP.

    Quote Originally Posted by PeterPan_321 View Post
    But based on this discussion it seems that all these tutorials are wrong, because the PHP files are just as visible to spammers as anything lease.
    If you write them PROPERLY they aren't... well written library sub-files should be filled with functions and classes if they have security info in them... that way you have to get php to execute to access them... so unless there's a code elevation or the hacker is somehow able to upload their own code, it's useless to them -- and really if they are able to execute their own PHP, you're ****ed anyways no matter what you do; at which point it becomes about minimizing risk.

    Really though, you're completely misinterpreting what's being said.

    For example, ginerjm's paranoia about putting files the user shouldn't access directly in the php tree... Well, let's use one of my old-old-older form handlers as an example:

    http://battletech.hopto.org/html_tut...m.library.phps

    What would be the risk in someone being able to call that code directly if it was a .php file? Well, try it, here's a live copy:

    http://battletech.hopto.org/html_tut...rm.library.php

    Zero risk, it's just functions, so unless you can execute functions remotely (which you can't) there's NO DANGER in letting people call it directly. That's just good interpreted language coding practices.

    Look at the template file:
    http://battletech.hopto.org/html_tut....template.phps

    It's all in functions, so you don't have to sweat it being called directly.

    While that's an old and not particularly stunning bit of code (it actually dates from ~2006ish), you might find looking at that useful.
    http://battletech.hopto.org/html_tut...ormValidateMk2

    There's a .rar of it in there too so you can grab the whole thing.

    Quote Originally Posted by PeterPan_321 View Post
    So whats a newbie to do? Sure I'd like to master everything, but this "form mail" has been my first occasion to even see a PHP script as a necessary tool.
    Well, that's because 'doing it right' is a VERY complex task, that really you are going to need a much firmer grasp of PHP before attempting to tackle. Blindly cutting and pasting from anyone's code (even mine) isn't the road to success with anything more complex than HTML. (and even then...) ... It just isn't a "simple thing to do".

    Though if you've only been doing static sites with HTML and CSS, it may be time to step up your game. PHP really is your next logical step, even if it's just to make a "poor man's CSS"; which is where you use PHP includes to just glue together common parts of a site to the unique bits and pieces, so you aren't wasting time having the same code in dozens or even hundreds of separate pages making updates a pain in the ass.
    Java is to JavaScript as Ham is to Hamburger.

  14. #14
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77
    deathshadow: thanks for all that. I really appreciate you're taking the time. I will study your code, especially in light of now having messed with PHP encough to read it and learn some things from it. I won't bore you with my own psycho-analysis, but I wear many hats, and often have had to wear many more than I bargained for in the process of moving ahead on my many projects. that often leads to initial frustration every time another piece of the 1000 piece jigsaw puzzle in a current project becomes something else I have to stop and learn. But hey... I'm also a dyed in the wool do-it-yourselfer, and so I've only myself to blame for the pile of hats on my head. :-) And bottom line, you're right... PHP is something I should have had a better grasp on long ago. I'm already C, C++ and JAVA coder, and have no excuse. But you do see my point about tutorials often being very misleading. I should have gone to the w3cschools for my first look!

    Now to you and everyone else on this thread, every one of you of has been a great help. And with that help, I was able to generate at least a passable mailform. I did, in fact, combine the HTML and the PHP into a single PHP file, which resides in a directory with some basic .HTACCESS blocking. not sure how safe it is from email harvesters, but time will tell I guess.

    The form is launched in its own window by a javascript, when the visitor clicks the contact link. I'm just doing some basic validation on a few fields currently. When a bad field or a rule is broken, the window containing the form is updated with some guidance for the user. So I let the visitor retry, and use little PHP scripts in the "value" field of each <input> within the form, so the user isn't stuck completely starting over with a blank form. When all is deemed well, the php formats and sends me the email. When the email has been sent (and there's nothing left to do), only then do I use the header() function to switch to a mail confirmation page, which contains a button so the visitor can close the window. I left the "@" on my mail() function, only because I'm not sure what would happen otherwise if the actual mail process failed, and I'm not sure how to test that.

    Anyway, if anyone has the time or wants to see the fruit of your help, you can now go to my totally under construction site, www.elfintechnologies.com. Once there, click the CONTACT link on the far right of the menu, and send me an email if you'd like. Feel free to bang on the form a little. Like I said, the only validation I'm doing are the basic email tests, making sure the visitor at least leaves a name, return email, and puts SOMETHING in the message area.

    All suggestions welcome. But bottom line, PHP is now off my list of "mystery" buzz words. It *IS* about time I learned some of the benefits of server side tools, and I'm sure I'll be using PHP a lot more in the future. That is, along with the other 1000 things I'm working on! :-)
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

  15. #15
    Join Date
    Jun 2004
    Location
    Tampa, Florida
    Posts
    77
    Quote Originally Posted by deathshadow View Post
    There are TWO modes of thought on that -- the first is what you are doing, the second is to use functions and classes ONLY in your library PHP files, so if you call them directly via HTTP, they don't output anything.

    Since the OTHER risk -- readfile and/or include during a code elevation -- will work regardless of where you put the files.

    That's actually interpreted language security 101 -- files the user shouldn't be calling directly shouldn't output anything or run any code.
    Hopefully you read my last post, where I did my best to thank you and everyone for all the support. But this one point about security i want to clarify, which somehow got missed. The main reason I started exploring PHP based form mail was to hide my email address. I'm only worried about a spammer or spam bot SEEING a piece of code like this...

    $headers = $email_message = ""; // assume latter var filled in elsewhere
    $email_to = "myemail@mydomain.com";
    $email_subject = "Elfin Technologies Inquiry";
    $headers = 'From: '.$email."\r\n".
    'Reply-To: '.$email."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    //
    mail($email_to, $email_subject, $email_message, $headers);

    As you say, its doubtful a function containing the above could be executed by a hacker, and if they did, sure I'd get some spam. But I was more concerned about the VISIBILITY! If a SPAM-BOT can simply find the file, look for strings with the telltale "@" and harvest them, then I'm going to get a flood of mail offering to enlarge body parts.

    Sure, as in javascript I can do all kinds of tricks to hide the email address. Build the string from ascii codes, or whatever. But it was my understanding that a PHP file could neither be found nor read but an outside trouble maker, unless the server has been hacked and compromised. One person said it was all up for grabs, another confirmed that PHP was safe. So I put mine in a private directory, with some HTACCESS code to (hopefully) prevent that from happening. Best I know how to do. But I'm all ears for other suggestions, because again... hiding the email address was my original priority.
    Randy (PeterPan)
    * * *
    * *
    ... Second Star to the Right, and Straight on Till Morning!
    * * *

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles