PHP - How To Make A Form-action Run A Function?
Hi,
I'm creating a PHP application to handle my SQL server and I've run into a bit of a problem; I have two files atm: mainClass.php and testSite.php My mainClass.php looks like this: Code: [Select] class mainClass { private $host = 'localhost'; public function createDb($user,$pass,$dbName) { $con = mysql_connect($host, $user, $pass); if (!$con){ die('Could not connect: '.mysql_error()); } $sql = "CREATE DATABASE `$dbName`;"; if (!mysql_query($sql)){ die('Error 1: '.mysql_error()); } mysql_close(); } }and testSite.php looks like this: Code: [Select] <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <h1>testSite for my PHP app</h1> <?php function __autoload($className){ require_once "./classes/{$className}.php"; } $test = new mainClass(); ?> <form name='createDb' method='post' action=''> User: <input type='text' name='user'><br> Password: <input type='password' name='pass'><br> dbName: <input type='text' name='dbName'><br> <input type='submit' value='Create DB'> </form> </body> </html> What I'm asking is if it is possible to make the form-action from testSite.php run the createDb function from mainClass.php I have pretty much no idea how to do it but I tried like this: Code: [Select] <form name='createDb' method='post' action="<?php $test->createDb($_POST['user'],$_POST['pass'],$_POST['dbName']); ?>"> User: <input type='text' name='user'><br> Password: <input type='password' name='pass'><br> dbName: <input type='text' name='dbName'><br> <input type='submit' value='Log in'> </form>But that just made the whole form disappear so now I'm completely lost, any help greatly appreciated. PS: I'm doing this to get better at PHP so please don't come with advice like "use a framework" or "there already are applications that handles this", I know there is. Similar TutorialsHow do you have an HTML form process a function for an action? I tried what I have below, but i just can't get it to work right. Any ideas? Thanks for your help. For example: Code: [Select] <?php function UserLookup(){ $searchfield = $_POST['searchfield']; $client = new SoapClient("http://www.domain.com/webservice.asmx?WSDL"); $result = $client->UserLookup(array('searchfield'=>$searchfield)); echo json_encode($result); } if (isset($_GET['submit'])) { UserLookup(); } else { ?> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" > <input name="searchfield" type="text" size="45" /> <input type="submit" value=" Search " /> </form> <?php } ?> Hi I am in the process of converting to Object Oriented from Procedural. To cater for this I have built an admin_login function, contained within a class: 'siteFunctions'. However, I am having trouble pointing the admin form to the function correctly. Every time I click 'submit', the form does not process anything. It doesn't even 'think' about it i.e. show the egg timer.... I have built this script heaps of times using the procedural method, so I guess I am somehow doing something wrong with respect to referencing the action attribute of the form (due to my new approach). I am very new to OO so please go easy on me: I know the script isn't particularly advanced. I just want to get used to putting functions into classes, and then calling the code, before I move onto more advanced stuff. I have placed all of the files within the same folder in order to rule out driectory path issues. Here are the three scripts that I think are relevant (login, functionsClass, and the mysql connection script): Login $pageTitle = "Admin Login"; include("admin_header.php"); include_once("sitefunctions.php"); new siteFunctions(); echo '<div class="admin_main_body">'; <form action="<?php echo htmlentities($_SERVER["PHP_SELF"]);?>" method='post'> <input type="text" name="username" id="username" size="20"> <label>Username</label><br /> <input type="password" name="password" id="password" size="20"> <label>Password</label><br /> <input type="submit" name="submit" id="submit" value="submit"> </form> echo '<div>'; include("includes/admin_footer.php"); sitefunctions.php //$page = "admin_index.php"; class siteFunctions { var $message; function admin_login() { echo '<div class="admin_main_body">'; $message = NULL; if (isset($_POST['submit'])) { require_once ("mysql_connect.php"); if (empty($_POST['username'])) { $u = FALSE; $message .= '<p> Please enter your username </p>'; } else { $u = escape_data($_POST['username']); } if (empty($_POST['password'])) { $p = FALSE; $message .= '<p>You forgot to enter your password </p>'; } else { $p = escape_data($_POST['password']); } if ($u && $p) { // If everything's OK. $query = "SELECT * FROM admin WHERE username= ('$u') AND password=('$p')"; $result = @mysqli_query($GLOBALS["___mysqli_ston"], $query); $row = mysqli_fetch_array($result, MYSQLI_BOTH); if ($row) { session_start(); $_SESSION["admin_id"] = $row[0]; //header("$page"); //Redirects user to admin_index.php //header('location: "$page"'); header ("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "admin_index.php"); //echo '$_SESSION["admin_id"]'; } else { $message = '<p> The username and password combination are incorrect.</p>'; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } else { $message .= '<p>Please try again.</p>'; } } if (isset($message)) { echo '<font color="red">', $message, '</font>'; } //$adminLogin = 'admin_login'; } //Closes function } //Closes class Connection Script // This file contains the database access information. This file also establishes a connection to MySQL and selects the database. // Set the database access information as constants. DEFINE ('DB_USER', 'atkinson'); DEFINE ('DB_PASSWORD', 'XYZ111WA'); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'practicesite'); if ($dbc = @($GLOBALS["___mysqli_ston"] = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD))) { // Make the connnection. if (!((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . constant('DB_NAME')))) { // If it can't select the database. // Handle the error. my_error_handler (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_errno($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)), 'Could not select the database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); // Print a message to the user, include the footer, and kill the script. echo '<p><font color="red">The site is currently experiencing technical difficulties. We apologize for any inconvenience.</font></p>'; include_once ('includes/footer.php'); exit(); } // End of mysql_select_db IF. } else { // If it couldn't connect to MySQL. // Print a message to the user, include the footer, and kill the script. my_error_handler (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_errno($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)), 'Could not connect to the database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); echo '<p><font color="red">The site is currently experiencing technical difficulties. We apologize for any inconvenience.</font></p>'; include_once ('includes/footer.php'); exit(); } // End of $dbc IF. // Function for escaping and trimming form data. function escape_data ($data) { global $dbc; if (ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } return mysqli_real_escape_string( $dbc, trim ($data)); } // End of escape_data() function. Any help would be appreciated. Cheers Will This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=359130.0 When I click the save changes button, I want the user to be brought back to profile.php. Right now they are being brought to editprofile.php. I currently have the form action set to editprofile.php . When the I change it to profile.php my fields won't update. Any thoughts as to where I went wrong? Here is the editprofile.php code. <form action='editprofile.php' method="POST" id="form"> I've heard multiple recommendations when a form needs to post to itself. Some say use PHP_SELF, others say leave it blank (even though it doesn't validate), etc. Please provide the best practice, and reasons why. Thank you
echo("<form method='post' action='{$_SERVER['PHP_SELF']}'>"); echo("<form method='post' action=''>"); how do I put a get id into this form, or use $myvar?: Code: [Select] <form action='read2.php?id=' method="post" name='myForm' id="myForm"></form> Im having some problems with my PHP program... Im trying to get the imformation send to my inbox, but when i push the submit button; i get no email and the "thank you message" is incomplete.. (see attachement: thankUmessage.png) I have to say, im not really a PHPfreak , I understand this language a little.. I hope someone can help me first the codes: HTML: (see attachement: form.png) Code: [Select] <!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 http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>contactformulier</title> <style type="text/css"> <!-- body,td,th { font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #FFFF00; } body { background-color: #CCCCCC; } .style2 {font-size: 16px} --> </style> <script type="text/javascript"> <!-- function MM_validateForm() { //v4.0 if (document.getElementById){ var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]); if (val) { nm=val.name; if ((val=val.value)!="") { if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@'); if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n'; } else if (test!='R') { num = parseFloat(val); if (isNaN(val)) errors+='- '+nm+' must contain a number.\n'; if (test.indexOf('inRange') != -1) { p=test.indexOf(':'); min=test.substring(8,p); max=test.substring(p+1); if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n'; } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; } } if (errors) alert('The following error(s) occurred:\n'+errors); document.MM_returnValue = (errors == ''); } } //--> </script> </head> <body> <form id="form1" name="form1" method="post" action="contactafhandeling.php"> <table width="400" cellpadding="0" cellspacing="0" bordercolor="#CCCCCC" bgcolor="#000000"> <!--DWLayoutTable--> <tr> <td height="39" colspan="6"><div align="center" class="style2">Contact formulier<br /> </div></td> </tr> <tr> <td height="21"><div align="right">Aanhef:</div></td> <td width="4" rowspan="7"> </td> <td colspan="4" valign="top"> <select name="aanhef" id="aanhef"> <option value="dhr" selected="selected">Dhr.</option> <option value="mvr">Mvr.</option> </select> </td> </tr> <tr> <td width="72" height="20"><div align="right">Voorletters:</div></td> <td width="42" valign="top"><div align="left"> <input name="voorletters" type="text" id="voorletters" size="5" maxlength="40" /> </div></td> <td width="120" valign="top"><div align="center">Achternaam: </div></td> <td colspan="2" valign="top"><div align="left"> <input name="achternaam" type="text" id="achternaam" size="20" maxlength="40" /> </div> <div align="left"></div> </td> </tr> <tr> <td height="20"><div align="right">Adres:</div></td> <td colspan="2" valign="top"><div align="left"> <input name="adres" type="text" id="adres" size="20" maxlength="40" /> </div> <div align="center"></div> <div align="left"></div></td> <td width="79" valign="top"><div align="center">Postcode:</div></td> <td valign="top"><div align="right"> <input name="postcode" type="text" id="postcode" size="10" maxlength="7" /> </div></td> </tr> <tr> <td height="20"><div align="right">Woonplaats:</div></td> <td colspan="4" align="right" valign="top"><div align="left"> <input name="woonplaats" type="text" id="woonplaats" size="20" maxlength="40" /> </div> <div align="left"></div> <div align="left"></div> <div align="left"></div></td> </tr> <tr> <td height="20"><div align="right">Tel:</div></td> <td colspan="4" valign="top"><div align="left"> <input name="tel" type="text" id="tel" size="20" maxlength="10" /> </div></td> </tr> <tr> <td height="20"><div align="right">Email:</div></td> <td colspan="4" valign="top"> <div align="left"> <input name="email" type="text" id="email" size="40" maxlength="40" /> </div></td> </tr> <tr> <td height="20"><div align="right">Interesses:</div></td> <td colspan="4" valign="top"><div align="left"> <label></label> <label> <input type="checkbox" name="badkamer" id="badkamer" /> Badkamermeubels</label> <label> <br /> <input type="checkbox" name="kantoor" id="kantoor" /> Kantoormeubels</label> <label> <br /> <input type="checkbox" name="kasten" id="kasten" /> Kasten</label> <label><br /> <input type="checkbox" name="keukens" id="keukens" /> Keukens <br /> </label> <label> <input type="checkbox" name="tafels" id="tafels" /> Tafels</label> <br /> </div></td> </tr> <tr> <td height="21" colspan="5" valign="top"><input type="reset" name="reset" id="reset" value="Reset" /></td> <td width="83" height="21" valign="top"><input name="verzenden" type="submit" id="verzenden" onclick="MM_validateForm('voorletters','','R','achternaam','','R','tel','','RisNum','email','','RisEmail');return document.MM_returnValue" value="Verzenden" /></td> </tr> </table> </form> </body> </html> Looks like: afbeelding 1.png Then the PHP code: Code: [Select] <!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 http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Contactafhandeling</title> </head><body> <? $aanhef = $_POST['aanhef']['dhr']; $aanhef = $_POST['aanhef']['mvr']; $voorletters = $_POST['voorletters']; $achterNaam = $_POST['achterNaam']; $adres = $_POST['adres']; $postcode = $_POST['postcode']; $tel = $_POST['tel']; $email = $_POST[email]; $interesses = $_POST['badkamer']['kantoor']['kasten']['keukens']['tafels']; $formsent = mail('sven_jcvd@hotmail.com', 'Gegevens afkomstig van contactformulier.html', "Naam: $aanhef $voorletters $achterNaam\r\n Adres: $adres\r\n Postcode: $plaatst\r\n Telefoonnummer: $tel\r\n Emailadres: $email\r\n Interesse in: $interesses", "From: $email\r\nBounce-to: sven_jcvd@hotmail.com"); if ($formsent) { echo "<p>Beste $achternaam,<br><br> Bedankt voor uw bericht, we zullen zo snel mogelijk contact met u opnemen.\n\r Met vriendelijke groet, JPS</p>"; } else { echo "<p>Sorry, er gaat iets fout met het formulier, probeer het later nog eens a.u.b.</p>"; } ?> </body> </html> It has been brought to my attention that $_SERVER['PHP_SELF']; can be easily hacked. In this code... Code: [Select] <form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Do I even need anything in the Action attribute if I am redirecting the form to itself?! Please advise... Debbie is there anyway to hide the action URL from html form example: <form name="afrom" action="hide.php" method="post"> so it end up from the user side: <form name="afrom" action="" method="post"> Thanks! Hi there, I was wondering if it was possible to change a forms action field with PHP. Basically, if there are several checkboxes for the user to select and a specific checkbox was selected, how would I redirect users to an alternative webpage on submit? I've been playing around with several methods, and one of them was: Code: [Select] <?php if(isset($_POST['Example']) && $_POST['Example'] == 'FormValueGoesHere') { echo ('./page1.php'); } else { echo ('./page2.php'); } ?> But the form action would only display page1.php even with nothing selected. Maybe I'm just being stupid because it's getting late, but I'd appreciate any assistance. Thanks Hi, I want to make a checkbox that will store the value as the user's database table ID and when the records are checked, I will have a delete, update link to delete/update those records that have their checkbox checked. I know I would need two submit buttons (one for delete and one for update), but the form tag only takes one action attribute, right? So does anyone know what I should do??? Le me know, thanks Hi guys, I want to create a piece of script that takes my users to a website based of there input in a form. Basiaclly what they input into a text field will become part of the URL used in action at the top of the form. So it would look like this: http://www."their input from form".mydomain.com does anyone have any suggestions on how to accomplish this? Thanks My question is, when someone make same html form with action that goes on same php file on my server, so i need to know, can my site be hacked in that way ? I mean if i have form that goes on file /sources/add_user.php and when someone make same html form that goes on www.my-site.com/sources/add_user.php and in that way to add users on my baze ? Hi, I am newbie to PHP. If any one explain me with a simple example, it would be really great. I have a form page "queue_info.php". After user hits SUBMIT, this page will redirect to an action page "queue_action.php". from form page data are passed using "$quests=$_POST['quests'];" to this action page. Now i need to resend this same data back to the form page "queue_info.php" from action page. How to do this? Appreciate your inputs on this. thanks, prakash Hi there, I am having some issues with a page failing security tests because of a form. The form's text input files is getting sanitized when posted but the only thing I can think is that the form action="" is $_SERVER['REQUEST_URI'] and this then includes anything that is within the URL. <form name="zipcode" id="zipcode" action="<?php echo htmlentities($_SERVER['REQUEST_URI'], ENT_QUOTES, "UTF-8"); ?>" method="post"> <label for="zip" class="smalllbl">Zipcode: </label> <input type="text" class="smallzip" name="zip" id="zip" value="" /> </form> Has anyone else experienced this when running PCI Compliance style security tests? And if you have, why would this happen as the same form action is used elsewhere with no issues. Many thanks in advance Simon I have this form action that checks for errors, if none are found it should go to the confirmation page. Works well in Firefox, however Chrome stays perpetually on the register page. Is there any way to make this work in Chrome as well? Does anyone have any explanation? Thank you very much for your time. Code: [Select] <form action="<?php if(!empty($errors)){ echo "confirmation.php"; } else { echo "register.php"; } ?>" method="POST"> I have a html form that submits to another website. Everything works fine in firefox and chrome however the data is duplicated in IE. Is there some quirk in IE when submitting a form to a different website? This works: Code: [Select] form action="http://localhost/mysite/css/screen.css" method="post"> This does not work: Code: [Select] <?php $link_1 = "http://localhost/mysite/css/screen.css" ; $link_2 = '"' . "http://localhost/mysite/css/screen.css" .'"' ; ?> <form action=<?php echo $link_1;?> method="post"> <form action=<?php echo $link_2;?> method="post"> Why do neither of the PHP variables work? Thanks! $to=sammieave@ave.com,samuel@ave.com; $subject = "New Event Logged"; $message = "Test"; $headers = "From: Samuel<sammieave@ave.com>;\r\n"; $headers .= "Content-Type: text/html"; mail($to,$subject,$message,$headers); I am having the above code but unfortunately the error I am getting is: Warning: mail() [function.mail]: SMTP server response: 550 Requested action not taken: mailbox unavailable or not local in C:\xampp\htdocs\CRM\support\mailer.php on line 139 You would think the answer would be all over the Internet and easy to find, but it’s not. I have searched many times, and in all the multitude of search results I have still never found an adequate usable answer. The MOST you ever find is someone saying how easy it is with PHP, but they don’t tell you how, even when the person they are answering asks them (odd). You can be that one in a billion person who finally answers it for real and helps someone out. I have a simple HTML form with data fields first_name, last_name, email, phone, country, a few hidden inputs, and a single submit button, like so: (Please note: the method is GET, not Post.) <form action="https://MyDomainOnMyServer.com/MyPHPScript.php”> <input type="text" name="first_name" value="" /> <input type="text" name="last_name" value="" /> <input type="text" name="email" value="" /> <input type="text" name="phone" value="" /> <input type="hidden" name="type" value="type123"> <input type="hidden" name="project" value="new123"> <select required name="country"> <option value="">Choose your country</option> <option value="US">United States</option> <option value="CA">Canada</option> <option value="GB">United Kingdom</option> <option value="Many More">Many More Countries</option> </select> <input type="submit" value="Submit Form" /> </form> NOTE: Originally, the form action would have been: action="https://TheirExampleDomainOnTheirRemoteServer.com/TheirRemotePHPScript.php" name="form1234" Upon clicking the single submit button only, what I need to have happen is this: 1. Send me an email to whatever@whatever.tld containing all the form submission data 2. Place the form submission data into a MySQL database having the corresponding data fields 3. Send the form submission contents including the hidden input values to "https://TheirExampleDomainOnTheirRemoteServer.com/TheirRemotePHPScript.php" name="form1234" AS IF that had remained set as the original form action to begin with So basically what I’m trying to obtain is the cleanest possible PHP script that will do those three things, which is essentially what others have asked for over the years in search results I have found, but no one has ever provided it in a clear instance that works. If I can just see such a script, I should be able to see how it works and then do what I need. Thanks. Reply |