PHP - Help With Giving Error Codes On Form Submission
hey guys. Right now upon form submission, I do an error check that puts all the errors into an array, then will display them at the top of the form. What I want to do though is break up the array, and be able to give each error msg in its indivdual table row in the html. Right now, my coding is
if($lname == '') { $errmsg_arr[] = 'You must enter your last name'; $errflag = true; } if($email == '') { $errmsg_arr[] = 'You must enter your email address'; $errflag = true; } if($city == '') { $errmsg_arr[] = 'You must enter your city'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: signup_artist.php"); exit(); } thats in form2.php form 1.php has the following snipet of code <?php if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) { echo '<ul class="err">'; foreach($_SESSION['ERRMSG_ARR'] as $msg) { echo '<li>',$msg,'</li>'; } echo '</ul>'; unset($_SESSION['ERRMSG_ARR']); } ?> so basically would I would like to be able to do is identify each error as for instane $fname_error $lname_error etc and then load them into my html appropriately, as opposed to just an array listing them Similar TutorialsHello Everyone, I have created a form for a personal project that I am working on. I have some error checking and stuff in the form but what I would like to happen is when an error has occurred for the page to reopen the form with the error message. I know that this can be done with the header function. But how do I get the form to display the error. Here is the block of code that I am working with Code: [Select] if ($file_error > 0) { header ('Location: add_category.php'); echo "There was an error uploading file."; } else { if ($file_type != $image_array) { header ('Location: add_category.php'); echo "Invalid Image Type"; } if ($file_name == FALSE) { header ('Location: add_category.php'); echo "Please choose a image for your category"; } if ($file_size > 5000000) { header ('Location: add_category.php'); echo "File size is to large. Images must be smaller than 5MB."; } if (str_word_count($description) > 300) { header ('Location: add_category.php'); echo "<p>category description must be less than 300 words<br />You have '.str_word_count($description).' words</p>"; }This is the form code that I am working with Code: [Select] <div id="content"> <form id="add_cat_form" name="add_cat_form" action="do_category.php" method="post" enctype="multipart/form-data"> <fieldset> <legend><p>Add Category</p></legend> <p> <label for="cat_name">Category Name:</label> <input class="input_box" type="text" name="cat_name" id="cat_name" /> </p> <p> <label for="cat_image">Category Image:</label> <input class="file" type="file" name="cat_image" id="cat_image" /> </p> <p> <label for="cat_desc">Description:</label><br /><textarea class="cat_desc" name="cat_desc" id="cat_desc"></textarea><br /> <span id="word_count">300 words Max</span> </p> <input class="submit_button" type="submit" value="Add Category" /> </fieldset> </form> </div> My code looks as follows: include('connectvars.php'); /* REGISTER FORM */ // check if submit button has been clicked if (isset($_POST['submit_signup'])) { // process and assign variables after post submit button has been clicked $user_email = strip_tags(trim($_POST['email'])); $firstname = strip_tags(trim($_POST['firstname'])); $lastname = strip_tags(trim($_POST['lastname'])); $nickname = strip_tags(trim($_POST['nickname'])); $password = $_POST['password']; $repassword = $_POST['repassword']; $dob = $_POST['dob']; $find_us_question = strip_tags(trim($_POST['find_us_question'])); // connect to database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $check_query = "SELECT * FROM users WHERE nickname = '$nickname'"; $check_connect = mysqli_query($dbc, $check_query); $check_count = mysqli_num_rows($check_connect); echo $check_count; die(); It's a register (sign up) page, and it's the beginning of the script, the rest of the script is just checking if all fields are a empty and if the input is in the allowed character length etc. I could it off at die(); because the rest doesn't matter. I want the script to check if the username already exists in the database, so I want mysqli_num_rows to tell me how many rows are already there with the same username, and then I want to continue doing an if statement saying if ($check_count != 0) { echo "Username already exists!" } But the mysqli_num_rows doesn't even print out how many rows there are availible, it gives me an error saying: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in... The num_rows function worked in the login script the same way, but for some reason it's not working in the register script. Any ideas, what I'm doing wrong? For testing purposes I just want it to print me "1" when I'm entering a username that's already in the database. All, I'm getting the following error when I work with a class: Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /webspace/httpdocs/offers/form_key.php on line 5 The complete code for this is class is: <?php class Form_Key { protected $oldKey; public function __construct() { // Ensure we have an available session if ( NULL == session_id() ) { session_start(); } // Grab our former key for validation if ( isset( $_SESSION['form_key'] ) ) { $this->oldKey = $_SESSION['form_key']; } // Assign the new key $_SESSION['form_key'] = md5( uniqid( mt_rand(), TRUE ) ); } public function isValid() { return 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['form_key'] ) && '' != trim( $_POST['form_key'] ) && '' != trim( $this->oldKey ) && $_POST['form_key'] === $this->oldKey; } public function getKey() { return $_SESSION['form_key']; } public function getOldKey() { return $this->oldKey; } public function render() { return '<input type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />'; } public function __toString() { return $this->render(); } } ?> The line that is giving the issue is this line: protected $oldKey; Is it ok just to remove this line?? If I comment it out it gives me the same message but for line 7, which is this one: public function __construct() Anyone have any ideas? Thanks in advance. Hi,
I have a text area field on one of my forms in order for people to post articles, however, it doesn't work when I try and post HTML through it. It works if I post normal text. Also, PHP won't give me an error, it just doesn't insert it?
<?php if ($_POST['add']) { $title = addslashes($_POST['title']); $image = htmlspecialchars($_POST['image']); $source = mysql_real_escape_string($_POST['source']); $active = $_POST['active']; $feature = $_POST['feature']; $cat_id = $_POST['cat_id']; $content = htmlspecialchars($_POST['content']); $months = array( "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ); $date = date('d', time()) . ' ' . $months[date('n', time())] . ' ' . date('Y', time()); if ($title == NULL || $image == NULL || $content == NULL) { echo '<br /><br /><center>Please, fill all inputs</center><br /><br />'; } else { $add = "INSERT INTO `news` cat_id='$cat_id', title='$title', image='$image', content='$content', date='$date', author='".$user['admin']."', authorid='".$user['id']."', source='$source', active='$active', twitter='".$user['twitter']."', featured='$feature'" or die(mysql_error()); $sql = mysql_query($add); $addgrowl = "INSERT INTO `growl` (toid, message) VALUES ('$id', 'Your article is now online!')"; $sql = mysql_query($addgrowl); echo '<script type="text/javascript"> window.location = "articles.php" </script> '; } } ?>Help :-( I am using a sloppy 3rd party API that doesn't return error codes, just error messages. See below Code: [Select] $err = $object->getErrorMessage(); if( strlen($err) > 0 ) { header("Location: step1.php?err=$err"); } As you can see this is sloppy because anyone can just modify the address bar of step1.php and inject their own error message, or javascript or their own HTML buttons, etc. As a work around, I thought maybe I could use POST instead of GET... At least then the "err" variable would be hidden for the most part Any ideas how I can work around this? Thanks! got this function in php.net i guess function mywordwrap($string) { $length = strlen($string); for ($i=0; $i<=$length; $i=$i+1) { $char = substr($string, $i, 1); if ($char == "<") $skip=1; elseif ($char == ">") $skip=0; elseif ($char == " ") $wrap=0; if ($skip==0) $wrap=$wrap+1; $returnvar = $returnvar . $char; if ($wrap>8) // alter this number to set the maximum word length { $returnvar = $returnvar . "<wbr>"; $wrap=0; } } return $returnvar; } after using this when i try to validate my page in http://validator.w3.org i get this error Line 124, Column 38: end tag for "wbr" omitted, but OMITTAG NO was specified <td width="15%">sdfasdfsdfadfddfdfsafasd<wbr>a</td> ✉ You may have neglected to close an element, or perhaps you meant to "self-close" an element, that is, ending it with "/>" instead of ">". what is the fix for this? Hello everyone. I am wondering how can i give different id's to a html form? Code: [Select] <?php ... if ($numrows!=0) { // fetching data from the database to variable while ($row = mysql_fetch_assoc($query)) { $view_jam = $row['jamname']; $view_recipe = $row['jamrecipe']; $view_rating = $row['jamrate']; $view_owner = $row['owner']; $view_comments = $row['comments']; $view_count = $row['count']; $view_id = $row['id']; $view_count2 = $row['count2']; echo "Jam name: <b>" . $view_jam . "</b><br />"; echo "Jam recipe: " . $view_recipe . "<br />"; echo "Owner: " . $view_owner . "<br />"; echo "Comments: " . $view_comments . "<br />"; echo "Jam Rating: " . $view_rating . "<br />"; [b]echo '<form action="main.php?id=jams" method="POST">[/b] Choose rating <input type="text" name="jamrate" /> <input type="submit" name="submit1" value="Rate"> </form><br /><br />'; ... ?>As you can see, the form is inside a loop. I am trying to build a rating system. When there is only one row in a database then everything goes smoothly, but if there are more, then the rating applies to all rows. I suppose i need to give different id's to the form. How? Thank you Where should my Form go once it is submitted? I am reading through some old code, and I was using some pretty convoluted programming to get everything (e.g. error and success messages after form submittal) to work. Basically what I would do was... Code: [Select] HTML to Open Page PHP to Handle Form If Data Okay... Success Message (e.g. "Your account was created!") HTML to close out Page If Data Invalid... Failure Message (e.g. "A System Error occurred. Please contact the Administrator.") HTML to close out Page HTML Form HTML to Close Page I have heard that you should always put your PHP first in the script and then follow it up with your HTML Page and Form. But where should you go once the form is submitted? My second attempt at things - to fix the mess above - was to REDIRECT the user to a "Handling Page" which basically was a large case statement that would read a "processing code" and display the right message. But that seems kind of hokey too?! Can someone help me come up with a more professional and scalable solution?? Thanks, Debbie
Hi All, ## First Document if(!empty($_FILES["dc1"])){ $fileName1 = htmlspecialchars_decode((basename($_FILES["dc1"]["name"]))); $fileTypeA1 = pathinfo($fileName1, PATHINFO_EXTENSION); $targetFilePath1 = $uploadDir . $uID . '-' . $randnum . '.' .$fileTypeA1; if(move_uploaded_file($_FILES["dc1"]["tmp_name"], $targetFilePath1)){ $uploadedFile1 = $targetFilePath1; } } ## Second Document if(!empty($_FILES["dc2"])){ $fileName2 = htmlspecialchars_decode((basename($_FILES["dc2"]["name"]))); $fileTypeA2 = pathinfo($fileName2, PATHINFO_EXTENSION); $targetFilePath2 = $uploadDir . $uID . '-' . $randnum . '.' .$fileTypeA2; if(move_uploaded_file($_FILES["dc2"]["tmp_name"], $targetFilePath2)){ $uploadedFile2 = $targetFilePath2; } } Edited October 13, 2020 by SH1989 Clean code up I'm trying to figure out where my problem is. Its not submitting my form. I'm getting the alert but when it submits it does the url?variables=whatever deal. Code: [Select] <?php require ('php/eventnames.php'); ?> <script type="text/javascript" src="forms/addnew/js/eventnames.js"></script> <!-- Form --> <form action="#" id="eventNameForm" > <fieldset> <legend>Add New Event Name</legend> <div class="field required"> <label for="eventName">Event Name</label> <input type="text" class="text" name="eventName" id="eventName" title="Event Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="shortName">Event Short Name</label> <input type="text" class="text" name="shortName" id="shortName" title="Event Short Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="eventType">Event Type</label> <select class="dropdown" name="eventType" id="eventType" title="Event Type"> <option value="">- Select -</option> <?php $eventTypes = array('Singular', 'Recurring', 'Pay Per View'); foreach($eventTypes as $et): ?> <option value="<?php echo $et; ?>"><?php echo $et; ?></option> <?php endforeach; ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <input type="hidden" name="userID" id="userID" value="<?php echo $userID; ?>" /> <input type="submit" class="submit" name="submitEventName" id="submitEventName" title="Submit Event Name" value="Submit Event Name"/> </fieldset> </form> <!-- /Form --> <!-- Messages --> <div class="message message-error"> <h6>Required field missing</h6> <p>Please fill in all required fields. </p> </div> <div class="message message-success"> <h6>Operation succesful</h6> <p>Content Page was added to the database.</p> </div> Code: [Select] $(document).ready(function() { $('div.message-error').hide(); $('div.message-success').hide(); alert("Test Alert!"); ("#eventNameForm").validate({ rules: { eventName: { required: true }, shortName: { required: true }, eventType: { required: true, rangelength: [1] } }, messages: { eventName: "Please enter the event name!", shortName: "Please enter the event's short name!", eventType: "Please enter the event type!" }, submitHandler: function(form) { var userID = $("input#userID").val(); var eventName = $("input#eventName").val(); var shortName = $("input#shortName").val(); var eventType = $("select#eventType").val(); var dataString = 'userID=' + userID + '&eventName=' + eventName + '&shortName=' + shortName + '&eventType=' + eventType + '&submitEventName=True'; $.ajax({ type: "POST", url: "processes/eventnames.php", data: dataString, success: function(myNewVar) { if (myNewVar == 'good') { $('div.message-error').hide(); $("div.message-success").html("<h6>Operation successful</h6><p>" + eventName + " Page saved successfully.</p>"); $("div.message-success").show().delay(10000).hide("slow"); $(':input','#eventNameForm') .not(':submit, :hidden') .val(''); } else if (myNewVar == 'bad1') { $('div.message-success').hide(); $("div.message-error").html("<h6>Operation unsuccessful</h6><p>" + eventName + " already exists in the database.</p>"); $("div.message-error").show(); } else if (myNewVar == 'bad2') { $('div.message-success').hide(); $("div.message-error").html("<h6>Operation unsuccessful</h6><p>" + shortName + " already exists in the database.</p>"); $("div.message-error").show(); } else if (myNewVar == 'bad3') { $('div.message-success').hide(); $("div.message-error").html("<h6>Operation unsuccessful</h6><p>" + eventName + " and " + shortName + " already exists in the database.</p>"); $("div.message-error").show(); } } }); return false; } }); }); I'm not sure if this is exactly a coding help question, excuse me if its not. I want to know what is the best & secure way to submit a form to itself. I've tried to google the answer, but did not get a proper answer with explanation or may be I didnt use proper keywords to search it. Out of these which one do i use? Code: [Select] // Leave the action field empty. <form method="POST" action=""> //$PHP_SELF, also if i use echo $PHP_SELF my form does not work like it should. <form method="POST" action="<?$PHP_SELF?>"> //$_SERVER['PHP_SELF'], same problem as $PHP_SELF, it doesnt work if i use echo. <form method="POST" action="<?$_SERVER['PHP_SELF']?>"> Hi all, I am wondering if nayone can spot why more form is not processing, basically the page just loads afresh once details have been entered and submit button clicked The page is called client.php <?php session_start(); if (isset($_POST['submit'])) { include('config.php'); $username = $_POST['username']; $password = md5($_POST['password']); $query = mysql_query("SELECT email,password FROM customers WHERE email='$username' AND password = '$password'"); $count=mysql_num_rows($query); if($count==1) { $query1= mysql_query("SELECT id FROM customers WHERE email='$username'"); echo mysql_error() ; while($row = mysql_fetch_assoc($query1)) { $id = $row['id']; $_SESSION['id'] = $id; $_SESSION['logged'] = "SET"; header("Location: client.php?id=$id"); } } else { echo "<script>alert('Incorrect Login Details')</script>"; } } ?> <link href="styles/style.css" rel="stylesheet" type="text/css" /> <link href="styles/form_clean.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="scripts/pageload.js"></script> <script type="text/javascript"> function swapImages(that) { that.src = (that.src.indexOf('buttonselected')>-1) ? ("images/"+that.id+"button.gif") : ("images/"+that.id+"buttonselected.gif"); } </script> <link href="styles/form_clean.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"> <div id="links"> <a href="index.php"><img src="images/homebutton.gif" alt="Home Button" class="buttons" id="home" onmouseover="swapImages(this)" onmouseout="swapImages(this)" /></a> <a href="javascript:ajaxpage('packages.php', 'content');"><img src="images/packagebutton.gif" alt="Packages Button" class="buttons" id="package" onmouseover="swapImages(this)" onmouseout="swapImages(this)" /></a> <a href="javascript:ajaxpage('purchase.php', 'content');"><img src="images/purchasebutton.gif" alt="Purchase Button" class="buttons" id="purchase" onmouseover="swapImages(this)" onmouseout="swapImages(this)" /></a> <a href="javascript:ajaxpage('contact.php', 'content');"><img src="images/contactabutton.gif" alt="Contact Button" class="buttons" id="contacta" onmouseover="swapImages(this)" onmouseout="swapImages(this)" /></a> <a href="client.php"><img src="images/clientbutton.gif" alt="Client Button" class="buttons" id="client" onmouseover="swapImages(this)" onmouseout="swapImages(this)" /></a> </div> <div id="logobox"><img src="images/logo.png" alt="JollyHosting.com - Simplified Reseller Hosting"/> </div> <div id="content"> <img src="images/gaptop.png" alt="seperator" /> <?php if(!isset($_SESSION['logged'])) { ?> <h2> Please Login</h2> <div id="login"> <form class="clean" action="client.php" method="post"> <ol> <li> <fieldset> <legend>Login</legend> <ol> <li> <label for="username">Email Address</label> <input type="text" id="username" name="username" value="" /> </li> <li> <label for="password">Password</label> <input type="password" id="password" name="password" value="" /> </li> </ol> </fieldset> </li> </ol> <p style="text-align:right;"> <input type="submit" value="OK" /> </p> </form> </div> <?php } else { echo "loggin in"; } ?> </div> <?php include('footer.php');?> </div> </body> </html> Many thanks I am trying to process a simple registration form:- Code: [Select] <form method="POST" action="regproc.php"> <p>Choose a username:<br /><input name="nick" type="text" /></p> <p>Choose a password:<br /><input name="pwd" type="password" /></p> <p>Re-type password:<br /><input name="pwd2" type="password" /></p> <p>Sex:<br /><input name="sex" type="text" /></p> <p>Email address:<br /><input name="email" type="text" /></p> <p><input name="submit" type="button" value="Hit me NOW!" /></p> </form> but it does not call the relevant processing file "regproc.php" when the submit button is hit. I can't figure out just why this is and would appreciate any ideas. I know that the solution is probably very simple and staring me in the face if only I could see it... can someone visually just read through my code and let me know if this looks like it'll work? I'm not getting any errors in my IDE so now I want to double check the structure <?php require_once '/usr/local/cpanel/3rdparty/lib/php/Mail.php'; $db_server = 'localhost'; $db_user = '-----'; $db_pass = '-----'; $dbc = mysql_connect ($db_server, $db_user, $db_pass); if (!$dbc) { die(mysql_error()); header ('Location: /contact'); exit; } if ($_POST['contactsent'] != 'yes') { header ('Location: /contact'); exit; } else { if (is_array($_POST)) { foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string(stripslashes($value)); } } $RequestType = $_POST["RequestType"]; $ConsumerBusiness = $_POST["ConsumerBusiness"]; $GlobalLocation = $_POST["GlobalLocation"]; $FirstName = strtolower(str_replace("'","''",$_POST["FirstName"])); $FirstName = strtoupper(substr($FirstName,0,1)).substr($FirstName,1); $LastName = strtolower(str_replace("'","''",$_POST["LastName"])); $LastName = strtoupper(substr($LastName,0,1)).substr($LastName,1); $Email = strtolower(str_replace("'","''",$_POST["Email"])); $Title = strtolower(str_replace("'","''",$_POST["Title"])); $Title = strtoupper(substr($Title,0,1)).substr($Title,1); $Company = strtolower(str_replace("'","''",$_POST["Company"])); $Company = strtoupper(substr($Company,0,1)).substr($Company,1); $Address = strtolower(str_replace("'","''",$_POST["Address"])); $Address = strtoupper(substr($Address,0,1)).substr($Address,1); $City = strtolower(str_replace("'","''",$_POST["City"])); $City = strtoupper(substr($City,0,1)).substr($City,1); $State = $_POST["State"]; $Zip = $_POST["Zip"]; $Phone = $_POST["Phone"]; $F = $_POST["F"]; $ProductDesc = $_POST["ProductDesc"]; $Comment = $_POST["Comment"]; if ($GlobalLocation == "Canada"): $SendTo="canadainfo@------.com"; elseif ($GlobalLocation == "Central America"): $SendTo="customer.service@------.com.pa"; elseif ($GlobalLocation == "Europe"): $SendTo="marketing@-----.uk"; elseif ($GlobalLocation == "Mexico"): $SendTo="ventas@------.com.mx"; else: $SendTo="info@------.com"; endif; function dbSet($fields, $source = array()) { $set=''; if (!source) $source = &$_POST; foreach ($fields as $field) { if (isset($source[$field])) { $set.="`$field`='".mysql_real_escape_string($source[$field])."', "; } } return substr($set, 0, -2); } // INSERT INTO DATABASE mysql_select_db("new_contact",$dbc) or die("Could not select new_contact"); $fields = explode(" ", "RequestType ConsumerBusiness GlobalLocation FirstName LastName Email Title Company Address City State Zip Phone F ProductDesc Comment"); $query = "INSERT INTO new_contact SET ".dbSet($fields, $_POST); mysql_query($query); // SETUP EMAIL $Bodycopy = "This information was submitted via the ------.com website and sent to you because of the location identified by the user. <br>If this has reached you in error, please forward this email to info@------.com"; $Bodycopy. "<br>----------------------------------------------------------------------------------------------<br><br>"; if ($RequestType != "") $Bodycopy. "What kind of information do you need? : " .$RequestType. "<br>"; if ($ConsumerBusiness != "") $Bodycopy. "What type of customer or vendor are you? : " .$ConsumerBusiness. "<br>"; if ($GlobalLocation != "") $Bodycopy. "Global Location : " .$GlobalLocation. "<br>"; if ($Company != "") $Bodycopy. "Company : " .$Company. "<br>"; if ($FirstName != "") $Bodycopy. "First Name : " .$FirstName. "<br>"; if ($LastName != "") $Bodycopy. "Last Name : " .$LastName. "<br>"; if ($Title != "") $Bodycopy. "Title : " .$Title. "<br>"; if ($Email != "") $Bodycopy. "Email : " .$Email. "<br>"; if ($Address != "") $Bodycopy. "Address : " .$Address. "<br>"; if ($City != "") $Bodycopy. "City : " .$City. "<br>"; if ($State != "") $Bodycopy. "State : " .$State. "<br>"; if ($Zip != "") $Bodycopy. "Zip/Postal Code : " .$Zip. "<br>"; if ($Phone != "") $Bodycopy. "Phone : " .$Phone. "<br>"; if ($F != "") $Bodycopy. "F : " .$F. "<br>"; if ($ProductDesc != "") $Bodycopy. "UPC or product description : " .$ProductDesc. "<br>"; $Bodycopy. "<br>----------------------------------------------------------------------------------------------<br><br>"; if ($Comment != "") $Bodycopy. "Comments : <br>" .$Comment. "<br>"; $Bodycopy. "<br><br>"; $Bodycopy. $IP = $_SERVER["remote_addr"]; // PROCESS EMAIL // mail server info... $from = $SendTo; $to = "Do Not Reply <donotreply@------>"; $subject = "Website Contact : " . $GlobalLocation; $body = $Bodycopy; $host = "mail.------"; $port = "25"; $username = "donotreply@-------"; $password = "-------"; $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject); $smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'port' => $port, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo("<p>" . $mail->getMessage() . "</p>"); } else { echo("<p>Message successfully sent!</p>"); } // MAKE SURE DB CONN IS CLOSED mysql_close($dbc); // REDIRECT TO THANK YOU PAGE header ('Location: /index.php?option'); exit(); } ?> Okay, so I have a neat little website and I'm having some issue with some quality-of-life improvements.
Namely, the user clicks a button which starts a server-side operation that can take up to 20 to 30 seconds.
I want a little message to appear below the button that says, "Operation started. This may take upwards of 20 to 30 seconds depending on traffic."
As of now, I have the typical
<form action="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> ... <input type="submit" name="submit" value="Make PDF" /> </form> <?php if (isset($_POST["submit"])) { ... } ?>The only problem is, part of my PHP code must communicate with a Java server that I have running on the server itself. So how the site works is, there's the computer I'm renting out and it's running Apache and a custom Java server I wrote myself. Apache handles the web request and upon form submission, PHP opens a socket with the Java server and begins the task. PHP then waits for the connection to close. hi i have the following contact us form which works fine. i need lil more tweaking. Right now when i submit the form it displays the information "blah blah", "the form has been submitted successfully" and also the form. What i want to do is if the form has been submitted successfully i need not display the form again. I need to display the data before the form field: "Blah Blah"(information before the form code) "the form has been submitted successfully" I do not need to display the form if it has been a successful submission. here is my code: Code: [Select] <?php include($headerpath); //change this to use mysql count function $totalentriesrow = mysql_query("SELECT DISTINCT userid FROM user", $con); $totalentriesrow = mysql_num_rows($totalentriesrow); ?> <title><?PHP echo $site_name; ?> Advertising</title> <BR><BR> <table cellpadding="5" cellspacing="1" bgcolor="white" border="0" width="900" align="center" style='border-top: 1px; border-right: 1px; border-left: 1px; border-bottom: 1px; border-color: black; border-style: solid;'> <tr> <td bgcolor='<?PHP echo $head; ?>' align='left'><b><font color='<?PHP echo $head_font_color; ?>' size='2' face='verdana'><?PHP echo $site_name; ?> Advertising</font></b> Blah Blah Blah Blah </td> </tr> <? //echo '<center><h4><font color="blue"><br>CONTACT US<br></font></h4></center>'; // Create an empty array to hold the error messages. $arrErrors = array(); //Only validate if the Submit button was clicked. if (!empty($_POST['submit'])) { // Each time theres an error, add an error message to the error array // using the field name as the key. if (empty($_POST['first_name'])) $arrErrors['first_name'] = '<br><font color="red">Please provide your first name.</font>'; if (empty($_POST['last_name'])) $arrErrors['last_name'] = '<br><font color="red">Please provide your last name.</font>'; if (empty($_POST['business_name'])) $arrErrors['business_name'] = '<br><font color="red">Please provide your business name.</font>'; if (empty($_POST['website_url'])) $arrErrors['website_url'] = '<br><font color="red">Please provide a website url.</font>'; if (empty($_POST['street_address'])) $arrErrors['street_address'] = '<br><font color="red">Please provide your street address.</font>'; if (empty($_POST['city'])) $arrErrors['city'] = '<br><font color="red">Please provide your city name.</font>'; if (empty($_POST['state'])) $arrErrors['state'] = '<br><font color="red">Please provide your state.</font>'; if (empty($_POST['zip'])) $arrErrors['zip'] = '<br><font color="red">Please provide your zip.</font>'; if (empty($_POST['country'])) $arrErrors['country'] = '<br><font color="red">Please provide your country.</font>'; if (empty($_POST['email_address'])) $arrErrors['email_address'] = '<br><font color="red">A valid email address is required.</font>'; if (empty($_POST['phone']) || (!is_numeric($_POST['phone']))) $arrErrors['phone'] = '<br><font color="red">Phone number cannot be empty and has to be numeric.</font>'; if (empty($_POST['description'])) $arrErrors['description'] = '<br><font color="red">Description cannot be empty.</font>'; // If the error array is empty, there were no errors. // Insert form processing here. if (count($arrErrors) == 0) { $first_name=cleaninput($_POST['first_name']); $last_name=cleaninput($_POST['last_name']); $business_name=cleaninput($_POST['business_name']); $website_url=cleaninput($_POST['website_url']); $street_address=cleaninput($_POST['street_address']); $city=cleaninput($_POST['city']); $state=cleaninput($_POST['state']); $zip=cleaninput($_POST['zip']); $country=cleaninput($_POST['country']); $email_address=cleaninput($_POST['email_address']); $phone=cleaninput($_POST['phone']); $description=cleaninput($_POST['description']); $to = $advertising_contacts; $subject = "Advertisement Contact"; $message="You have a new advertising contact<br>"; $message.="<b>First name:</b> ".stripslashes($first_name)."<br><b>Last Name:</b> ".stripslashes($last_name); $message.="<br><b>Business Name:</b> ".stripslashes($business_name)."<br><b>Business Description: </b>".stripslashes($description)."<br><b>Business URL:</b> ".stripslashes($website_url); $message.="<br><b>Street Address:</b> ".stripslashes($street_address)."<br><b>City:</b> ".stripslashes($city); $message.="<br><b>State:</b> ".stripslashes($state)."<br><b>Zip:</b> ".stripslashes($zip)."<br><b>Country:</b> ".stripslashes($country); $message.="<br><b>Email:</b> ".stripslashes($email_address)."<br><b>Phone:</b> ".stripslashes($phone); $from = "webmaster@example.com"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: Admin <Admin@groupbuilder.com>' . "\r\n"; // Send email mail($to,$subject,$message,$headers); //escapeinput for inserting into database $first_name=escapeinput($first_name); $last_name=escapeinput($last_name); $website_url=escapeinput($website_url); $street_address=escapeinput($street_address); $city=escapeinput($city); $state=escapeinput($state); $zip=escapeinput($zip); $country=escapeinput($country); $email=escapeinput($email); $phone=escapeinput($phone); $description=escapeinput($description); $dateline=time(); //Insert the details into database $insert_contacts=mysql_query("INSERT INTO adcontacts(first_name,last_name,email_address,phone,business_name,description,website_url,street_address,city,state,zip,country,dateline) VALUES('$first_name','$last_name','$email_address','$phone','$business_name','$description','$website_url','$street_address','$city','$state','$zip','$country','$dateline')") or die(mysql_error()); echo "<center>Form Submitted Successfully</center><br>"; } else { // The error array had something in it. There was an error. // Start adding error text to an error string. echo "<center>There was an error in the form<br></center>"; $strError=""; foreach ($arrErrors as $error) { $strError .= $error; } } } ?> <tr> <td> <? echo "<table align= 'center' width='50%' style='border-top: 1px; border-right: 1px; border-left: 1px; border-bottom: 1px; border-color: black; border-style: solid;'>"; ?> <tr> <td> <form action="<?php echo $PHP_SELF;?>" method="post"> <tr height='40'> <td> <font color="black"><B> First Name: </B></font> </td> <td><input type="text" size ="40" name="first_name" value="<? if(!empty($strError)) {echo cleaninput($_POST['first_name']);}?>" /> <?php if (!empty($arrErrors['first_name'])) echo $arrErrors['first_name']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Last Name: </B></font></td> <td><input type="text" size ="40" name="last_name" value="<? if(!empty($strError)) { echo cleaninput($_POST['last_name']);}?>"/> <?php if (!empty($arrErrors['last_name'])) echo $arrErrors['last_name']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Email Address: </B></font></td> <td><input type="text" size ="40" name="email_address" value="<? if(!empty($strError)) { echo cleaninput($_POST['email_address']);}?>"/> <?php if (!empty($arrErrors['email_address'])) echo $arrErrors['email_address']; ?> </td> </tr> <tr height='35'> <td><font color="black"><B> Business Name: </B></font></td> <td><input type="text" size ="40" name="business_name" value="<? if(!empty($strError)) { echo cleaninput($_POST['business_name']);}?>" /> <?php if (!empty($arrErrors['business_name'])) echo $arrErrors['business_name']; ?> </td> </tr> <tr> <td><font color="black"><B> Business Description: </B></font></td> <td ><textarea rows=7 cols=31 name="description"><? if(!empty($strError)) { echo cleaninput($_POST['description']);}?></textarea> <?php if (!empty($arrErrors['description'])) echo $arrErrors['description']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Business URL: </B></font></td> <td><input type="text" size ="40" name="website_url" value="<? if(!empty($strError)) { echo cleaninput($_POST['website_url']);}?>" /> <?php if (!empty($arrErrors['website_url'])) echo $arrErrors['website_url']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Business Phone: </B></font></td> <td><input type="text" size ="40" name="phone" value="<? if(!empty($strError)) { echo cleaninput($_POST['phone']);}?>"/> <?php if (!empty($arrErrors['phone'])) echo $arrErrors['phone']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Street Address: </B></font></td> <td><input type="text" size ="40" name="street_address" value="<? if(!empty($strError)) { echo cleaninput($_POST['street_address']);}?>" /> <?php if (!empty($arrErrors['street_address'])) echo $arrErrors['street_address']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> City: </B></font></td> <td><input type="text" size ="40" name="city" value="<? if(!empty($strError)) { echo cleaninput($_POST['city']);}?>" /> <?php if (!empty($arrErrors['city'])) echo $arrErrors['city']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> State: </B></font></td> <td><input type="text" size ="40" name="state" value="<? if(!empty($strError)) { echo cleaninput($_POST['state']);}?>"/> <?php if (!empty($arrErrors['state'])) echo $arrErrors['state']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Zip: </B></font></td> <td><input type="text" size ="40" name="zip" value="<? if(!empty($strError)) { echo cleaninput($_POST['zip']);}?>"/> <?php if (!empty($arrErrors['zip'])) echo $arrErrors['zip']; ?> </td> </tr> <tr height='40'> <td><font color="black"><B> Country: </B></font></td> <td> <select name="country"> <option value="<? if(!empty($strError)) { echo $_POST['country'];}?>"><?echo cleaninput($_POST['country']);?></option> <?php foreach($array as $key=>$value){ ?> <option value="<?php echo $value; ?>"><?php echo $value; ?></option> <?php }?> </select> <?php if (!empty($arrErrors['country'])) echo $arrErrors['country']; ?> </td> </tr> <tr height='35'> <td></td> <td><input type="submit" name="submit" value="submit" /></td> </tr> </form> </tr> </td> </table> </td> </tr> </table> If I have a standard HTML form in my PHP script and the User submits the form - which resubmits to itself for processing - and then the User hits the "Back" button and then the "Forward" button, why does the Form and its data get re-submitted?! What mechanics are exactly happening? I had a "Submit Payment" page that was doing that and so people would get charged twice and that is obviously a big problem. Please help me understand what causes that issue and different ways to fix it. Thanks, Debbie ok, so how can I grab $value before the form submits and I want to put it into the image field: Code: [Select] <?php include_once "secure/connect_to_mysql.php"; function genRandomString($length = 20) { $characters = '0123456789'; $string =''; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } if ($_POST['submit']) { $name = $_POST['name']; $id = $_POST['id']; $image = $_POST['image']; $event = $_POST['event']; $template = 'Templates/index.php'; $picture = '$name.png'; $id = genRandomString(); //this could be the uploaded picture //we need just the filename - no extension $picture_name = pathinfo($picture, PATHINFO_FILENAME); $sql = "INSERT INTO pictures (name, id, image, event) VALUES('$name', '$id','$image','$event')"; $rs = mysql_query($sql) or die ("Problem with the query: $sql<br>" . mysql_error()); echo mysql_error(); $target_path = "images/"; foreach ($_FILES["uploadedfile"]["name"] as $key => $value) { $uploadfile = $target_path . basename($_FILES[uploadedfile][name][$key]); //echo $uploadfile; if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'][$key], $uploadfile)) { echo $value . ' uploaded<br>'; } } copy($template, "$name.php"); } ?> <form action="new.php" method="post" enctype="multipart/form-data"><input name="name" type="text" /><input name="id" type="hidden" value=<?php echo $id; ?> /><br /> <input name="event" type="text" /><input name="image" type="text" value="images/<?php echo $value; ?>" /><input type="hidden" name="MAX_FILE_SIZE" value="900000000000000000000000000000000000000000000000000000000000000000000000000" /> Choose a file to upload: <div id="dynamicInput"> Entry 1<br><input type="file" name="uploadedfile[]"> </div> <input type="button" value="Add another text input" onClick="addInput('dynamicInput');"> <br /><input name="submit" type="submit" value="submit" /></form> if I do it after the form submits then it shows up, is there a way to make it appear before it submits....like a second field echoing what the first field has typed it and it updates "live"? HI All - Hoping you can help me out here with an issue that's preventing me from posting a form. I am still stumbling my way through this. I have a form that submits to itself with php code that uses a $curlhandle to post to a remote server, return xml data and parse it. The submission to the remote server works perfectly and the data returned is fine. The problem I am having is that when the form page initially loads in the browser, it thinks the form is already trying to submit, and it returns an error message for the first blank field. The error message is from the remote site. There is no database involved with this and the information does not need to be saved, just displayed on the same page the form resides on. So, is there a way I can load the page with the form without getting the error message from the remote site? Hello Everybody
Im new to this forum. Im trying to submit a form to my database but it's not passing through. when I submit the form an error message. I don't know if it is because I declare the escape_data fucntion wrongly. Any help would be appreciated. Here are my codings
Thanking you all in advance
submittest.php
<?php // Include config file... require_once('./config.php'); // Declare function. function escape_data($value) { if (!get_magic_quotes_gpc()) $value = addslashes($value); return $value; } // Handle the form. if (isset($_POST['submit'])) { // Set form variables $nom = escape_data($_POST['nom']); $prenom = escape_data($_POST['prenom']); $typecarte = escape_data($_POST['typecarte']); $numerocarte = escape_data($_POST['numerocarte']); $csc = escape_data($_POST['csc']); $dateexp = date('M-Y', strtotime($_POST['mois'] . "-" . $_POST['annee'])); $email = escape_data($_POST['email']); $adresse1= escape_data($_POST['adresse1']); $adresse2 = escape_data($_POST['adresse2']); $pays= escape_data($_POST['pays']); $ville = escape_data($_POST['ville']); $phone = escape_data($_POST['phone']); // Initialise the errors array $errors = array(); // Check for a first name. if (empty($_POST['nom'])) { $errors[] = 'Veuillez entrer le nom du client.'; } else { $fn = escape_data($_POST['nom']); } // Check for a last name. if (empty($_POST['prenom'])) { $errors[] = 'Veuillez entrer le prénom du client.'; } else { $ln = escape_data($_POST['prenom']); } // Check for type of card. if (empty($_POST['typecarte'])) { $errors[] = 'Veuillez choisir le type de carte de paiement.'; } else { $ad = escape_data($_POST['typecarte']); } // Check for card number. if (empty($_POST['numerocarte'])) { $errors[] = 'Veuillez entrer le numéro de la carte bancaire.'; } else { $town = escape_data($_POST['numerocarte']); } // Check for a security code. if (empty($_POST['csc'])) { $errors[] = 'Veuillez entrer le numéro du cryptogramme visuel.'; } else { $pc = escape_data($_POST['csc']); } // Check for expiration date. if (!empty($_POST['mois']) && !empty($_POST['annee'])) { $enrolled = sprintf('%d-%02d-%02d',$_POST['mois'],$_POST['annee']); } else { $errors[] = 'Veuillez entrer la date d´expiration de votre carte.'; } // Check for an email address and that it's in the correct format. if (preg_match ('/^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$/', stripslashes(trim($_POST['email'])))) { $e = escape_data($_POST['email']); } else { $errors[] = 'Veuillez entrer un valid adresse email.'; } // Check for address 1. if (empty($_POST['adresses1'])) { $errors[] = 'Veuillez enter l´adresse du client.'; } else { $course = escape_data($_POST['adresse1']); } // Check for the country. if (empty($_POST['pays'])) { $errors[] = 'Veuillez entrer le nom du pays.'; } else { $course = escape_data($_POST['pays']); } // Check for town. if (empty($_POST['ville'])) { $errors[] = 'Veuillez entrer le nom de la ville.'; } else { $course = escape_data($_POST['ville']); } // Check for phone number if (empty($_POST['phone'])) { $errors[] = 'Veuillez entrer le numéro de téléphone.'; } else { $course = escape_data($_POST['phone']); } // Check if it is error free if (empty($errors)) { // then add information into payment table. $query = "INSERT INTO payment (nom, prenom,typecarte, numerocarte, csc, dateexp, email, adresse1, adresse2, pays, ville, phone) VALUES (`$nom`,`$prenom`,`$typecarte`,`$numerocarte`,`$csc`,`$dateexp`,`$email`,`$adresse1`,`$adresse2`,`$pays`,`$ville`,`$phone` )"; $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); echo "<h3>Merci de votre fidélité, Votre paiement a bien été recu. Veuillez cliquer sur <a href='index.php'>ce lien</a> pour retourner a la page d'accueil.</h3>"; // If there is an error. } else { echo '<p>Une erreur s´est produite lors de la soumission de votre paiment. Voulez vous bien réessayer ou cantacter notre service clientéle. Nous nous excusons d´avance.</p>'; } mysql_close(); } ?>[/code] payment.html [code] <form action="submittest.php" method="post" > <table width="600" cellspacing="10"> <tr> <td>Nom*</td> <td><input type="text" name="nom" maxlength="50" value="" size="48" /></td> </tr> <tr> <td>Prénom*</td> <td><input type="text" name="prenom" maxlength="50" value="" size="48" /> </td> </tr> <tr> <td>Type de carte*</td> <td><select name="carte"> <option value="">Choisissez</option> <option value="visa">Visa</option> <option value="mastercard">Mastercard</option> <option value="American">American Express</option> </select> <tr> <td>Numéro de carte*</td> <td><input type="text" name="numérodecarte" maxlength="50" value="" size="48" /> </td> </tr> <tr> <td>Cryptogramme visuel</td> <td><input type="text" name="csc" maxlength="20" value="" size="7" /> </td> </tr> <tr> <td>Date d'expiration*</td> <td>Mois<select name="mois"> <option value="">M</option> <option value="01">01</option> <option value="02">02</option> <option value="03">03</option> <option value="04">04</option> <option value="05">05</option> <option value="06">06</option> <option value="07">07</option> <option value="08">08</option> <option value="09">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> Année<select name="annee"> <option value="">YYYY</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> <option value="2021">2021</option> <option value="2022">2022</option> <option value="2023">2023</option> <option value="2024">2024</option> <option value="2025">2025</option> </select></td> </tr> <tr> <td>E-mail*</td> <td><input type="text" name="email" maxlength="50" size="48" /> </td> </tr> <tr> <td height="59">Adresse (ligne 1)</td> <td><input type="text" name="adresse1" maxlength="65" value="" size="48"/> </td> </tr> <tr> <td>Adresse (ligne 2)<p style="color:#CCC; font-size:9px;">(facultatif)</p></td> <td><input type="text" name="adresse2" maxlength="65" value="" size="48"/> </td> </tr> <tr> <td>Pays</td> <td><input type="text" name="pays" maxlength="50" value="" size="48" /> </td> </tr> <tr> <td>Ville</td> <td><input type="text" name="ville" maxlength="16" size="48" /> </td> </tr> <tr> <td>Téléphone</td> <td><input type="text" name="numero" maxlength="16" size="48" /></td> </tr> <tr align="right"> <th colspan=3> <div align="center"><br/><br/> <input type="submit" name="submit" style="width:75px; height:35px; margin-left:100px" value="Valider" /> <input type="reset" name="reset" style="width:75px; height:35px; margin-left:15px" value="Annuler" /> <input type="hidden" name="submit" value="TRUE" /> </div></th> </tr> </table> </form> Edited by Ch0cu3r, 06 June 2014 - 07:32 AM. |