dave_w Posted May 25 Share Posted May 25 Hi, I'm struggling to get a simple example to work (with really no experience in php and just enough to make things work in html). My problem is this simple web page runs the php script when the page is loaded, writing to a file. I don't want the script to run until the submit button is pressed. What am I doing wrong? Thanks, Dave test.php.txt Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/ Share on other sites More sharing options...
dave_w Posted May 25 Author Share Posted May 25 BTW, I changed the name from test.php just so I could upload it. Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/#findComment-1625282 Share on other sites More sharing options...
phppup Posted May 25 Share Posted May 25 (edited) On this site, we do not normally open attachments. In order to post code, use the <> button located in the toolbar. As for your issue, the PHP script will be read by the server when loading the webpage. It is currently doing what you have directed it to do (and has proven that it functions adequately). If you want to change your instructions to not run unless the submit button is clicked, then you have created a new CONDITION that needs to be added to the code. There are several ways to handle this: //let's say this is your button <input type="submit" name="my_submit" value="runPHP"> //Assuming the button is inside a <form method="POST"> tag, you now have several alternatives or combinations to use as conditions <?php if(isset($_POST['my_submit'])){ //code to run if the CONDITION is met hours here } else { //what to do if condition is NOT met echo "Sorry, the button was not clicked"; } //end the condition //OR do this if you want to meet a greater condition if(isset($_POST['my_submit']) && $_POST['my_submit'] == "runPHP"){ //code to run if ALL the CONDITIONs are met } else { //what to do if conditionS are NOT met echo "Sorry, the button was not clicked"; } //end the conditions statement ?> Hope this helps. You can research ISSET and see other examples online. Edited May 25 by phppup 1 Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/#findComment-1625284 Share on other sites More sharing options...
dave_w Posted May 25 Author Share Posted May 25 Oops! Sorry, I won't make that mistake again! OK, I understand your hint. I've seen similar examples and just didn't understand until now. Thanks for your help (and for correcting me about uploading code). Dave Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/#findComment-1625331 Share on other sites More sharing options...
gizmola Posted June 1 Share Posted June 1 This is a common pattern, where you have a script that renders a form and also processes it. phppup provided a few great examples of how to handle it. Sometimes people will also choose to use the ability of PHP to provide you the HTTP method, given that you only want to process the form when the HTTP method was a POST. if ($_SERVER['REQUEST_METHOD'] === 'POST') { // This was a POST request. } However, with all that said, looking at your actual code, which I have put in the code block below, your code already should have been working, because it already evidently did what phppup demonstrated: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Untitled 1</title> </head> <body> <form method="post"> <input type="text" name="firstName" placeholder="First Name" value="first name"> <br> <input type="text" name="lastName" placeholder="Last Name" value="last name"> <br> <input type="submit" name="submit" value="Submit"> </form> <?php echo "running script"; if(isset($_POST['submit'])){ $firstName = "First Name:" . $_POST['firstName']. ""; $lastName = "Last Name:".$_POST['lastName'] . ""; $file = fopen("file.txt", "a"); fwrite($file, $firstName); fwrite($file, $lastName); fclose($file); } ?> The ONLY issue here, is that your script echos out "running script" regardless. If you moved that echo statement inside the if loop, you would perhaps not be fooled into thinking the code that you did not want to be run was running. In summary, your code already worked, but your debugging statement displayed even when the processing was not being run. One thing I would like to suggest to you, is that you can take advantage of variable interpolation. It is one of the things that makes PHP very nice to work with, not unlike the introduction of template literals in javascript. You have this concatenation: $firstName = "First Name:".$_POST['firstName'].""; But with interpolation, you can use the much more natural and simpler to read, debug and modify: $firstName = "First Name:{$_POST['firstName']}"; Interpolation is done anytime you utilize double quotes. It's good practice (although a micro optimization) to use single quotes anytime you want a string constant. When PHP sees double quotes around a string it will try to interpolate. With single quotes, it will not. $name = 'Gizmola'; echo "Hello $name <br>"; \\ output: Hello Gizmola <br> echo 'Hello $name <br>'; \\ output: Hello $name <br> I'm not sure why you originally had the extra "", which essentially does nothing, as the code is saying "add nothing to the end of this string." You can add things like newlines using escape characters. A newline character can be added using "\n". $firstName = "First Name:{$_POST['firstName']}\n"; Similar escape characters like tab can be inserted using this technique (in an interpolated string). Last but not least, you only need to enclose the variable inside a block ie, {variable}, when the variable is an array element, as in the case of the $_POST. Without putting the { .. } around the array variable, PHP is not able to parse the string properly, and you get a syntax error. Putting the block around array variables solves the problem. With simple php variables like "$name" you can just use them inside the double quoted string, and PHP will interpolate them into the resulting string variable. One of the strengths of PHP for web development is its HTML/PHP block modality, which you are using here. Before long, however, you likely want to have something like a header.php you include in scripts, so you aren't cutting/pasting the same HTML block into each script. Along these lines, PHP also has HEREDOCS which support interpolation. So you could move all of the your HTML boilerplate into a PHP script. In your case, at least trivially, you would want to have the page title be a variable, in this case $title. //htmlHead.php <?php $htmlHead = <<<HEADER <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>$title</title> </head> HEADER; Note a few things here: You do not ever need to have an ending PHP tag in your scripts, class files or function collections. The only time you need to use a php end tag (?>) is if you are dropping in and out of PHP mode. So now we can rewrite your original script this way: <?php $title = 'Name File Processing'; require_once('htmlHead.php'); echo $htmlHead; ?> <body> <form method="post"> <input type="text" name="firstName" placeholder="First Name" value="first name"> <br> <input type="text" name="lastName" placeholder="Last Name" value="last name"> <br> <input type="submit" name="submit" value="Submit"> </form> <?php if(isset($_POST['submit'])){ echo "running script<br>"; $firstName = "First Name: {$_POST['firstName']}"; $lastName = "Last Name: {$_POST['lastName']}"; $file = fopen("file.txt", "a"); fwrite($file, $firstName); fwrite($file, $lastName); fclose($file); } ?> </body> 1 Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/#findComment-1626505 Share on other sites More sharing options...
gizmola Posted June 2 Share Posted June 2 One last very opinionated take, but in my experience, the best practice for HTML element naming is to use all lower case names, rather than camel case. It also helps to differentiate between php variables in camelcase and corresponding html elements. If you feel strongly you want to have a separator in your html names, then use underscore between words. It's best not to use dashes, as this will interfere/complicate using the very useful data-* feature of html/javascript integration, where data-* names will be turned into javascript camelcase equivalent values. I'm also a believer in using BEM when integrating your css. I find that, by following conventions, it gives you underlying best practices to guide you in variable naming. PHP has a community coding standard PSR-12 that is a best practice to follow. So your html form, would be translated to: <form method="post"> <input type="text" name="first_name" placeholder="First Name"><br> <input type="text" name="last_name" placeholder="Last Name"><br> <input type="submit" name="submit" value="Submit"> </form> Notice that I removed your value assignments. It's a bad idea to set the values of the form fields in advance like that, as submitting the form will have those values unless the user enters something into them. Then your processing becomes: function postTrim($formVariables) { foreach ($formVariables as $name) { if (isset($_POST[$name]) { $_POST[$name] = trim($_POST[$name]); } } } if(isset($_POST['submit'])){ $formVariables = ['first_name', 'last_name']; postTrim($formVariables); $message = ''; foreach ($formVariables as $name) { if (empty($_POST[$name]) { $message .= 'You must provide a value for ' . implode(array_map('ucfirst', explode('_', $name))) . '<br>'; } } if ($message) { // Invalid Form Post echo $message; exit; } echo "running script<br>"; $firstName = "First Name: {$_POST['firstname']}"; $lastName = "Last Name: {$_POST['lastname']}"; $file = fopen("file.txt", "a"); fwrite($file, $firstName); fwrite($file, $lastName); fclose($file); } So I added a quick helper function that will use a whitelist of your form element names, to make sure that each element has been trimmed of whitespace before/after the variable. It also will eliminate a field that just has spaces in it, but is otherwise empty. Then I added a check loop that goes through the whitelist and makes sure there were actual values posted. If not it displays an error message, and does not add to the file. I hope these examples will help you on your way to PHP based web development mastery. These are just simple examples, and I often don't actually check that the code is entirely valid, so there might be some bugs in there, but I encourage you to experiment, and read about any of the functions or things I've tried to demonstrate. Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/#findComment-1626512 Share on other sites More sharing options...
dave_w Posted June 8 Author Share Posted June 8 Wow Gizmola. <insert exploding head emoji here> Thanks! You've given me some really good ideas and a lot of information for me to investigate and learn. Greatly appreciated! 1 Quote Link to comment https://forums.phpfreaks.com/topic/321021-stop-php-script-running-on-page-load/#findComment-1627332 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.