PHP - Simple Validation Functions
Hi Guys
Simple question. Can anyone tell me why this doesn't work please? Code: [Select] $test = "<HEELOOOO"; $test2 = filter_var("$test", FILTER_SANITIZE_STRING); echo $test2; When I run this get I get nothing echoed back, not even in the source. So can the filter function not be used like this? I thought it would encode the special character and return it but I must be missing something simple here! Thanks, Drongo Similar TutorialsHi i have a function strored in a seperate file (included in my main php page for use), my question is a simple one but i cannot seem to find the answer on the web to this: I call the function as follows passing the variable $name <?php myfunction($name) ?> The function does somehting simple such as: <?php function myfunction ($name) { if ($name = 'bob') { return true; } else return false; } ?> How do i then obtain the true or false value of the function from back with my main php page? Hello, i am trying to create a simple funtion that i can all upon to "turn off a website" i am calling the function by <?php siteonline(n); ?> and the function is function siteonline($msg){ $offlinecheck = mysql_query("SELECT * FROM acp") or die(mysql_error()); $siteoffline = mysql_fetch_array($offlinecheck); $ifsiteoffline = $siteoffline['site_offline']; $offline = $siteoffline['offline_msg']; if ($ifsiteoffline == "y") { echo("$offline"); die();} } now this will turn off the site but it shows no message what so ever and i can not figure out why can anyone help? Cheers, Hello all, I finally started learning php and with the little knowledge I have from CPP it's far simpler than it seemed years ago. I need a little bit of help with this function I followed in a tutorial and it's just not working. <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?> It just gives me a blank screen. Now, I figured #fname isnt set, so I did this: <?php $fname = "Refsnes"; function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?> Still, no go, which leads me to think I'm probably mistaking. Help? I don't want to skip out things in a tutorial. Hi, I am searching for a basic, easy to implement php form validation script that checks if the user has filled out a field, if they havent to tell them so. i have tried basic if statements but it refreshes the page and all the other fields that were filled in are clear. Anyone know of any tricks or scripts that are good? Thanks in advance. I am trying to add some simple validation to my form. I only wanter users to be able to enter 11 numbers into the number field or else it will say 11 digit numbers only. A validation to only allow users to input numbers anything else and it brings up an error. and finally i want to check the email string to make sure it has an @ and a (.) . How would i go about adding these validation techniques to this code? <?php if ($_SERVER['REQUEST_METHOD']=="POST"){ // Recipent Email $to="andrew@peppermintdigital.com"; $subject="Reply to Peppermint Invitation"; $title = $_POST['title']; $name = stripslashes($_POST['name']); $add1 = stripslashes($_POST['add1']); $add2 = stripslashes($_POST['add2']); $add3 = stripslashes($_POST['add3']); $add4 = stripslashes($_POST['add4']); $postcode = stripslashes($_POST['postcode']); $number = stripslashes($_POST['number']); $email = stripslashes($_POST['email']); $time = $_POST['time']; $from = ($_POST['name']) . "<".stripslashes($_POST['email']).">"; $subject = ($_POST['name']) . "<".stripslashes($_POST['email']).">"; // Email Message $message = "Name : $title $name. Address : $add1, $add2, $add3, $add4, $postcode. Phone Number : $number. Email : $email. Appointment Time : $time"; // Validation Begins // Add Erros To Array $errors = array(); // Check Form if (!$_POST['title']) $errors[] = "Title Required"; if (!$_POST['name']) $errors[] = "Name Required"; if (!$_POST['add1']) $errors[] = "Address Required"; if (!$_POST['add4']) $errors[] = "City Required"; if (!$_POST['postcode']) $errors[] = "Postcode Required"; if (!$_POST['number']) $errors[] = "Number Required"; if(!$_POST['number'] == 11) $errors[] = "Full Number Required"; if (!$_POST['email']) $errors[] = "Email Required"; if (!$_POST['time']) $errors[] = "Time Required"; // Display Errors if (count($errors)>0) { echo"<h1 class='fail'>"; foreach($errors as $err) echo "$err.\n"; echo"</h1>"; echo " <form method='post' action='#'> <table cellpadding='0' cellspacing='0' border='0'> <tr> <td class='form_results' colspan='2'> </td> </tr> <tr> <td class='form_left' valign='top'> <table width='200' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='title_left' valign='top'>Title</td> </tr> <tr> <td class='sname_left' valign='top'>Name</td> </tr> <tr> <td class='add_left' valign='top'>Address</td> </tr> <tr> <td class='post_left' valign='top'>Postcode</td> </tr> <tr> <td class='number_left' valign='top'>Phone Number</td> </tr> <tr> <td class='email_left' valign='top'>Email Address</td> </tr> <tr> <td class='time_left' valign='top'>Appointment Time</td> </tr> </table> </td> <td class='form_right' valign='top'> <table width='300' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='right_spacer'> <select name='title' class='select'> <option>Mr</option> <option>Mrs</option> <option>Ms</option> <option>Miss</option> </select> </td> </tr> <tr> <td class='right_spacer'><input type='text' name='name' class='field' value='$name' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add1' class='field' value='$add1' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add2' class='field' value='$add2' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add3' class='field' value='$add3' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add4' class='field' value='$add4' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='postcode' class='field' value='$postcode' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='number' class='field' value='$number' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='email' class='field' value='$email' /></td> </tr> <tr> <td class='right_spacer'> <select name='time' class='select'> <option>5.30 pm</option> <option>6.30 pm</option> <option>7.30 pm</option> </select> </td> </tr> </table> </td> </tr> <tr> <td class='form_buttom' colspan='2'> <input name='submit' type='submit' value='Submit' class='submit_button' /> </td> </tr> </table> </form> "; } else { // Build message headers $headers = "From: $from\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\""; // Send message if (@mail($to, $subject, $message, $headers)) echo "<h1 class='success'>Your message has been sent.</h1>"; else echo "<h1 class='fail'>Your message was not sent at this time.</h1>"; } } else { echo " <form method='post' action='#'> <table cellpadding='0' cellspacing='0' border='0'> <tr> <td class='form_results' colspan='2'> </td> </tr> <tr> <td class='form_left' valign='top'> <table width='200' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='title_left' valign='top'>Title</td> </tr> <tr> <td class='sname_left' valign='top'>Name</td> </tr> <tr> <td class='add_left' valign='top'>Address</td> </tr> <tr> <td class='post_left' valign='top'>Postcode</td> </tr> <tr> <td class='number_left' valign='top'>Phone Number</td> </tr> <tr> <td class='email_left' valign='top'>Email Address</td> </tr> <tr> <td class='time_left' valign='top'>Appointment Time</td> </tr> </table> </td> <td class='form_right' valign='top'> <table width='300' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='right_spacer'> <select name='title' class='select'> <option>Mr</option> <option>Mrs</option> <option>Ms</option> <option>Miss</option> </select> </td> </tr> <tr> <td class='right_spacer'><input type='text' name='name' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add1' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add2' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add3' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add4' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='postcode' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='number' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='email' class='field' /></td> </tr> <tr> <td class='right_spacer'> <select name='time' class='select'> <option>5.30 pm</option> <option>6.30 pm</option> <option>7.30 pm</option> </select> </td> </tr> </table> </td> </tr> <tr> <td class='form_buttom' colspan='2'> <input name='submit' type='submit' value='Submit' class='submit_button' /> </td> </tr> </table> </form> "; } ?> I'm having trouble with this form. I can't seem to figure out the rest of what is required I have already done most of it...I'm just stuck on these parts: Province Select : (AutoGeneration, Multiple Select, Memory) AutoGeneration using Provinces Array: The Province Select box is generated by PHP using this array: provinces.txt Cut and paste this array into your own code. Multiple Selections: Note that the province select box permits multiple values to be selected. View the HTML source to see the configuration details. Also note how $_POST delivers these multiple values as an array. Select Box Memory: The Province select box retains the user choices after a POST. For each province selected by the user, your code will generate the "selected" attribute in the <options> tag for that province. View the HTML source of the working solution to see how this works. Status CheckBoxes (Multiple Select, Memory) Multiple Selections: Note that these checkboxes have been configured in the HTML to permit multiple selections. Also note that $_POST delivers these multiple selection values in an array. Status Box Memory:The Status Box retains the user choices after a POST. Your code will need to generate the "checked" attribute in the <input> tag for each item selected. Do not generate the checkboxes with an array. Location Radio button: Do not generate the radio buttons with an array. The Location radio button retains the user choice after a POST. Validation Success Message: Where does it go - The final success message is placed within the <div class="success"></div> tags at the top of the HTML. Use a Loop: Generate the success message with a single array loop that reads the $_POST array and prints out the success message as an ordered list. Form Variables List Un-Ordered List - The form variables are displayed in an unordered list . CSS removes the bullet. Names Capitolised - The names of the form variables are capitolised ( use strtoupper() function ) . Handle Empty Values - Print "---None supplied---" if the variable is empty. Province Long Names - Print the long names of the provinces selected as comma separated string Status Choices - Print the status choices as a comma separated string. Functions I need to use: empty() - is the string empty. Unfortunately, a "0" value counts as an empty string. strlen() - returns the number of characters in a string. is_numeric() - is the string a number count() - how many rows in an array is_array() - is the variable an array isset() - does the variable or member of array exist in_array() -does this string exist in this array strtoupper() - convert string to upper case. join() - you'll want this one too. Converts an array of strings into a string with a delimiter. error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); - suppresses warning messages in your code. Place at top. foreach ($_POST as $KEY => $VAL) {} - walk through the $_POST array (or any array) My code: Code: [Select] <!--"StAuth10065: I Adam Graham, 000136921 certify that this material is my original work. No other person's work has been used without due acknowledgement. I have not made my work available to anyone else."--> <? $PROVINCES = array( "--" => "--- Please Select Provinces ---", "nf"=>"Newfoundland", "pe"=>"Prince Edward Island", "nb"=>"New Brunswick", "ns"=>"Nova Scotia", "qc"=>"Quebec", "on"=>"Ontario", "mb"=>"Manitoba", "sk"=>"Saskatchewan", "ab"=>"Alberta", "bc"=>"British Columbia", "nt"=>"Northwest Territories"); if ($_SERVER['REQUEST_METHOD'] == 'GET') { $dimwelcomeMsg = TRUE; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_POST['uname'] == ''){ $errMsgs['uname'] = "Username must not be blank!!!"; $unameInError = true; } if (empty($_POST['year']) == TRUE){ $errMsgs['year'] = "Year must not be blank!!"; } if (count($errMsg) > 0 ): $dispErrorMsg = TRUE; else: foreach ($_POST as $key => $val): $key = strtoupper($key); $successMsg[$key] = $val; endforeach; $dispSuccessMsg = TRUE; endif; } ?> <html > <head> <title>Comp10065 - Simple Form Validatioon</title> <style type="text/css"> body { margin: 0; padding: 0; font: 80%/1.5 Arial,Helvetica,sans-serif; color: #111; background-color: green; } h2 { margin: 0px; padding: 10px; font-family: Georgia, "Times New Roman", Times, serif; font-size: 200%; font-weight: normal; color: #FFF; background-color: #CCC; border-bottom: #BBB 2px solid; } h1 {color:#006600} p#copyright { margin: 20px 10px; font-size: 90%; color: #999; } div.form-container { margin: 10px; padding: 5px; background-color: #FFF; border: #EEE 1px solid; } p.legend { margin-bottom: 1em; } p.legend em { color: #C00; font-style: normal; } div.errors { margin: 0 0 10px 0; padding: 5px 10px; border: #FC6 1px solid; background-color: #FFC; } div.errors p { margin: 0; } div.errors p em { color: #C00; font-style: normal; font-weight: bold; } div.success { margin: 0 0 10px 0; padding: 5px 10px; border: #FC6 1px solid; background-color: #FFC; } div.success p { margin: 0; color:#006633} div.success li {list-style-type: none; } div.form-container form p { margin: 0; } div.form-container form p.note { margin-left: 170px; font-size: 90%; color: #333; } div.form-container form fieldset { margin: 10px 0; padding: 10px; border: #DDD 1px solid; } div.form-container form legend { font-weight: bold; color: #666; } div.form-container form fieldset div { padding: 0.25em 0; } div.form-container label, div.form-container span.label { margin-right: 10px; padding-right: 10px; width: 150px; display: block; float: left; text-align: right; position: relative; } div.form-container label.error, div.form-container span.error { color: #000; } div.form-container select.error, div.form-container div.error {background-color: #FEF;} div.form-container label em, div.form-container span.label em { position: absolute; right: 0; font-size: 120%; font-style: normal; color: #C00; } div.form-container input.error { border-color: #C00; background-color: #FEF; } div.form-container input:focus, div.form-container input.error:focus, div.form-container textarea:focus { background-color: #FFC; border-color: #FC6; } div.form-container div.controlset {margin: 3px} div.form-container div.controlset label, div.form-container div.controlset input { display: inline; float: none; } div.form-container div.controlset div { margin-left: 170px; } div.form-container div.buttonrow { padding-left: 430px; border: 1px solid #CCCCCC } div#wrapper {width: 700px ; margin-left: auto; margin-right: auto} pre {color:black; font-size: 10pt; font-weight: bold; margin-left: 30px} </style> </head> <body> <div id="wrapper"> <h1> Form Validation Lab</h1> <div class="form-container"> <? if ($_SERVER['REQUEST_METHOD'] == 'GET') : ?> <? if (displayWelcomeMsg) : ?> <p>Please fill in the form........</p> <? endif; ?> <? endif; ?> <? if ($displaySuccessMsg): ?> <div class="success"> <p>Thank you for your submission.</p> <ol> <? foreach($successMsgs as $key => $successMsg): ?> <li><?= $key ?> = <?= $successMsg ?> </li> <? endforeach; ?> </ol> </div> <? endif; ?> <? if ($dispErrorMsg) : ?> <div class="errors"> <p><em>Oops...the following errors were encountered</em></p> <ul> <? foreach ($errMsgs as $key => $errMsg): ?> <li><?= $errMsgs ?> </li> <? endforeach; ?> </ul> <p>Please correct the errors and re-submit this form.</p> </div> <? endif; ?> <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"> <input type="hidden" name="act" value="post"> <div class="buttonrow"> <input type="submit" value="Submit This Form " class="button" /> <a href="<?= $_SERVER['PHP_SELF'] ?>" >Start Again</a> </div> <p class="legend"><strong>Note:</strong> Required fields are marked with an asterisk (<em>*</em>)</p> <fieldset> <legend>User Details</legend> <div> <label for="uname" >User Name <em>*</em></label> <? if (isset($errMsgs['uname'])) echo 'class = "errors"' ?> <input id="uname" type="text" name="uname" value="<?=$_POST['uname'] ?>" /> (must be greater than 5 chars)</div> <div> <label for="email">Email Address </label> <input id="email" type="text" name="email" value="" /> </div> </fieldset> <fieldset> <legend>Submission</legend> <div> <label for="year">Year (YYYY) <em>*</em></label> <input id="year" type="text" name="year" <? if (isset($errMsgs['year'])) echo 'class = "errors"' ?> value="" size="4" maxlength="4" /> (4 digit number)</div> <div> <label for="date">Month (MM)</label> <input id="date" type="text" name="month" value="" size="4" maxlength="2" /> (number ranging from 1-12)</div> </fieldset> <fieldset> <legend>Preferences</legend> <div> <label for="type" >Province (Multiple Select) <em>*</em></label> <select name = "province[]" multiple size = "12" id="type" > <? foreach ($PROVINCES as $abbreviation => $longname); ?> <option value = "<?=$abbreviation ?> "></option> <? enfgoreach; ?> </select> </div> <div class= 'controlset' > <span class="label">Status (Mult Select)<em>*</em></span> <input name="status[]" id="approved" value="approved" type="checkbox" /> <label for="approved">Approved</label> <input name="status[]" id="pending" value="pending" type="checkbox" /> <label for="pending">Pending Application</label> <input name="status[]" id="actives" value="actives" type="checkbox" /> <label for="actives">Active Service</label> </div> <div class= 'controlset'> <span class="label"> Location <em>*</em></span> <input name="location" id="radio1" value="Garage" type="radio" /> <label for="radio1">Garage</label> <input name="location" id="radio2" value="Attic" type="radio" /> <label for="radio2">Attic</label> <input name="location" id="radio3" value="House" type="radio" /> <label for="radio3">House</label> </div> </fieldset> </form> <p>This debug info is here to help you. You are only required to display the POST array</p> <pre><?= print_r($_POST,true) ?> </pre> </div> </div> </body> </html> Not sure what I am missing. When submitted gives white page with no submission. Error check is not showing anything. global $userdata, $current_user; $tablename=kudos_table_name(); // Functions to filter user inputs function filterkudoagent($field){ // Sanitize user name $field = filter_var(trim($field), FILTER_SANITIZE_STRING); // Validate user name if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z-\s]+$/")))){ return $field; } else { return FALSE; } } function filterkudocust($field){ // Sanitize user name $field = filter_var(trim($field), FILTER_SANITIZE_STRING); // Validate user name if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z-\s]+$/")))){ return $field; } else { return FALSE; } } function filterString($field){ // Sanitize string $field = filter_var(trim($field), FILTER_SANITIZE_STRING); if(!empty($field)){ return $field; } else{ return FALSE; } } $kudoagentErr = $agentlocErr = $kudoclientErr = $kudocustErr = $kudomsgErr = $kudoadnErr = ""; $kudoagent = $agentloc = $kudoclient = $kudocust = $kudomsg = $kudoadn = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if(empty($_POST["kudoagent"])){ $kudoagentErr = "Please enter agent name."; } else{ $kudoagent = filterkudoagent($_POST["kudoagent"]); if($kudoagent == FALSE){ $kudoagentErr = "Please enter a valid agent name."; } } if(empty($_POST['agentloc'])){ $agentlocErr = "You must select a location"; } if(empty($_POST['kudoclient'])){ $kudoclientErr = "You must select a queue"; } if(empty($_POST["kudocust"])){ $kudocustErr = "Please enter customer name."; } else{ $kudocust = filterkudocust($_POST["kudocust"]); if($kudocust == FALSE){ $kudocustErr = "Please enter a valid customer name."; } } if(empty($_POST["kudomsg"])){ $kudomsgErr = "Please enter the kudos."; } else{ $kudomsg = filterString($_POST["kudomsg"]); if($kudomsg == FALSE){ $kudomsgErr = "Please enter a valid kudos."; } } if(empty($_POST["kudoadminname"])){ $kudoadnErr = "Please enter the posters name."; } else{ $kudoadn = filterkudocust($_POST["kudoadminname"]); if($kudoadn == FALSE){ $kudoadnErr = "Please enter a valid posters name."; } } if (isset($_POST['kudoagentid']) && trim($_POST['kudoagentid']) != '') { $kudoagidErr = "Enter Agent ID or leave blank"; } else { $kudoacctErr = ""; } if (isset($_POST['kudoacct']) && trim($_POST['kudoacct']) != '' && !ctype_digit($_POST['kudoacct'])) { $kudoacctErr = "Only numbers are permitted or leave blank"; } else { $kudoacctErr = ""; } if(empty($kudoagentErr) && empty($kudocustErr) && empty($kudomsgErr) && empty($agentlocErr) && empty($kudoclientErr) && empty($kudoadnErr)){ global $wpdb; $table = $tablename; $kudokey = randkey(); $kudoposted = date("Y-m-d H:i:s"); $data = array( 'kudoid' => '', 'kudomsg' => $_POST['kudomsg'], 'kudoagent' => $_POST['kudoagent'], 'kudoagentid' => $_POST['kudoagentid'], 'kudocust' => $_POST['kudocust'], 'kudoacct' => $_POST['kudoacct'], 'kudoclient' => $_POST['kudoclient'], 'kudoloc' => $_POST['agentloc'], 'kudoentry' => $kudoposted, 'kudoadmin' => $_POST['kudoadminname'], 'kudopic' => $_POST['kudobanner'], 'kudostatus' => '1', 'kudokey' => $kudokey, ); $format = array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ); $success=$wpdb->insert( $table, $data, $format ); if($success){ echo "<blockquote class=\"otro-blockquote\">"; echo nl2br($_POST['kudomsg']); echo "<span>"; echo "<b>Kudos for:</b> " .$_POST['kudoagent']. " " .$_POST['kudoagentid']. ", ".$_POST['agentloc']; echo "<br>By: ".$_POST['kudocust']. ", " . date("F j, Y g:i a", strtotime($kudoposted)); echo "<br/>" .$_POST['kudoacct']; echo "<br/> Submitted By: " .$_POST['kudoadminname']; echo "</span></blockquote>"; $urlparts = parse_url(home_url()); $kudourl = $urlparts['host']; echo "<div class='success_msg'>Kudos Submitted</div>"; } } } else { ?> <h3>Add Kudos - No Notification Sent</h3> <b>* states required</b> <form name="kudos_form" id="submitkudos" method="post" action="" enctype="multipart/form-data"> <table class="addkudotable"> <tr> <td>Agent Name *</td> <td> </td> <td><input name="kudoagent" type="text" value="<?php echo $_POST['kudoagent']; ?>"/> <?php echo "<div class='note'>".$kudoagentErr."<br/>";?> </td> </tr> <tr> <td>Agent ID</td> <td></td> <td><input name="kudoagentid" type="text" value="<?php echo $_POST['kudoagentid']; ?>" /> <?php echo "<div class='note'> </div>";?> </td> </tr> <tr> <td>Agent Location *</td> <td></td> <td><select name="agentloc" size="1"> <option value="<?php echo $_POST['agentloc']; ?>"><?php echo $_POST['agentloc']; ?></option> <option></option> <option value="Amherst Center">Amherst Center</option> <option value="Charlottetown Center">Charlottetown Center</option> <option value="Kingston Center">Kingston Center</option> </select> <?php echo "<div class='note'>".$agentlocErr."</div>";?> </td> </tr> <tr> <td>Agent Queue *</td> <td></td> <td><select name="kudoclient" size="1"> <option value="<?php echo $_POST['kudoclient']; ?>"><?php echo $_POST['kudoclient']; ?></option> <option value=""></option> <option value="AR">AR</option> <option value="Eastlink Tech Support">Eastlink Tech Support</option> <option value="PNI">PNI</option> </select> <?php echo "<div class='note'>".$kudoclientErr."</div>";?> </td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>Customer Name *</td> <td></td> <td><input name="kudocust" type="text" value="<?php echo $_POST['kudocust']; ?>"/> <?php echo "<div class='note'>".$kudocustErr."</div>";?> </td> </tr> <tr> <td>Customer Account #</td> <td></td> <td><input name="kudoacct" type="text" value="<?php echo $_POST['kudoacct']; ?>" /> <?php echo "<div class='note'>".$kudoacctErr."</div>";?> </td> </tr> <tr> <td>Kudos *</td> <td></td> <td><textarea cols="50" name="kudomsg" rows="5"><?php echo $_POST['kudomsg']; ?></textarea> <?php echo "<div class='note'>".$kudomsgErr."</div>";?> </td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>Choose Image</td> <td></td> <td><select onchange="$('#imageToSwap').attr('src', this.options[this.selectedIndex].value);" name="kudobanner"> <option value="<?php echo plugins_url(); ?>/img/kudos/1.jpeg" selected>Kudos 1</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/2.jpg">Kudos 2</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/3.png">Kudos 3</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/4.png">Kudos 4</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/5.png">Kudos 5</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/6.jpg">Kudos 6</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/7.jpg">Kudos 7</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/8.jpg">Kudos 8</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/9.png">Kudos 9</option> </select></td> </tr> <tr> <td>Agent submitting Kudos</td> <td></td> <td><input name="kudoadminname" type="text" value="<?php echo $_POST['kudoadminname']; ?>"> <?php echo "<div class='note'>".$kudoadnErr."</div>";?></td> </tr> <tr> <td> </td> <td><input type="hidden" name="action" value=""/></td> <td></td> </tr> <tr> <td><button type="submit" value="submit" class="aciformbutton" name="submit" />Submit Kudos</button> <td></td> <td><button type="reset" value="reset" class="aciformbutton">Start Over</button></td> </tr> </table> <input type="hidden" value="" name="kudoentry"> </form> <script> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <?php echo "<img id=\"imageToSwap\" class=\"profile\" src=" . plugins_url() . "/kudos/img/kudos/1.jpeg>"; }
Hi all, I have the below which is meant to check if the required fields in a form have been submitted, however when submit is clicked, even with no values in the boxes, the form submits as normal. <?php error_reporting(E_ALL); ini_set('display_errors', '1'); include_once ('formvalidator.php'); ?> <link href="../Styles/form_dark.css" rel="stylesheet" type="text/css" /> <?php $show_form=true; if(isset($_POST['submit'])) { $validator = new FormValidator(); $validator->addValidation("user_name","req","Please fill in Name"); $validator->addValidation("user_password","req","Please enter a password"); $validator->addValidation("user_email","email", "The input for Email should be a valid email value"); $validator->addValidation("user_email","req","Please fill in Email"); if($validator->ValidateForm()) { echo "<h2>Validation Success!</h2>"; $show_form=false; } else { echo "<B>Validation Errors:</B>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> <form class="dark" action="regdo.php" method="post" > <ol> <li> <fieldset> <legend>User Registration</legend> <ol> <li> <label for="user_name">Username</label> <input type="text" id="user_name" name="user_name" value="" /> </li> <li> <label for="user_email">E-Mail Address</label> <input type="text" id="user_email" name="user_email" value="" /> </li> <li> <label for="user_password">Password</label> <input type="password" id="user_password" name="user_password" value="" /> </li> </ol> </fieldset> </li> </ol> <p style="text-align:right;"> <input type="reset" value="CANCEL" /> <input type="submit" value="OK" /> </p> </form> <?php }//true == $show_form ?> Can anyone explain what the problem is? Cheers Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript, but most importantly, how to write something from scratch in PHP. So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: [Select] <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: [Select] <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. Thanks in advance, and please let me know if it'll be possible. I have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result. My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout: <?php // Error reporting error_reporting(E_ALL); // Connect DB mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error()); // Select DB mysql_select_db("wickettowicket") or die(mysql_error()); // MySQL queries to find batsmen and bowlers $array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC'); $array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2'); // Start table for data $data = '<table width="600px">'; // Create blank scorecard while ($array_bat = mysql_fetch_array($array_batsmen)) { $data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>'; } // Set up arrays for players $current_batsman = $current_bowler = array(); // Reset query mysql_data_seek($array_batsmen,0); $in_one = $in_two = $it = ''; function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs) { global $current_batsman; $current_batsman = array ( 'id' => $id, 'name' => $name, 'ability' => $ability, 'strength' => $strength, 'out' => $out, 'in' => $in, 'runs' => $runs ); echo 'set current'; } // Set up arrays of batsmen while ($array = mysql_fetch_array($array_batsmen)) { if ($it < 3 && $in_one == '') { currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_one = $array['id']; $current = $array['id']; $it++; } else if ($it < 3 && $in_two == '') { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_two = $array['id']; $it++; } else { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 0, 'runs' => 0 ); } } // Bowler Array while ($array = mysql_fetch_array($array_bowlers)) { $bowlers[] = array ( 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'] ); } // Reset both queries mysql_data_seek($array_bowlers,0); mysql_data_seek($array_batsmen,0); function changeBatsman($just_out) { global $array_batsmen, $batsmen; //Update array $batsmen[$just_out] = array ( 'in' => 1, 'out' => 1 ); while ($array = mysql_fetch_array($array_batsmen)) { if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'change batsman'; } function swapBatsman($other_batsman) { global $array_batsmen, $batsman; while ($array = mysql_fetch_array($array_batsmen)) { if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'swap batsman'; } $runs = $outs = $balls = $overs = 0; $played = array(); function selectBowler() { global $bowlers, $current_bowler; // Select random bowler $choose_bowler = array_rand($bowlers, 1); $current_bowler = array ( 'name' => $bowlers[$choose_bowler]['name'], 'ability' => $bowlers[$choose_bowler]['ability'], 'strength' => $bowlers[$choose_bowler]['strength'] ); } /* function selectBatsman(); { global $array_batsmen; while ($array_batsmen[]['out'] != 1) { }*/ function bowl() { global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs; if ($current_batsman['out'] == 0) { echo 'bowling'; // Set the initial number $number = rand(0, 190); // Ability of batsman if ($current_batsman['ability'] > 90) $number += 30; else if ($current_batsman['ability'] > 70) $number += 15; else if ($current_batsman['ability'] > 50) $number += 2; else $number = $number; // Strength of batsman if ($current_batsman['strength'] > 90) $number += 15; else if ($current_batsman['strength'] > 70) $number += 10; else if ($current_batsman['strength'] > 50) $number += 5; else $number = $number; // Depending on overs if ($balls > 270) $number += 30; else if ($balls > 120) $number -= 10; // Ability if ($current_bowler['ability'] > 90) $number -= 30; else if ($current_bowler['ability'] > 70) $number -= 15; else if ($current_bowler['ability'] > 50) $number -= 2; else $number = $number; // If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out if ($current_batsman['runs'] > 200) $number -= 70; else if ($current_batsman['runs'] > 100) $number -= 30; // Finally sort out runs if ($number > 190) $run = 6; else if ($number > 170) $run = 4; else if ($number > 160) $run = 3; else if ($number > 100) $run = 2; else if ($number > 50) $run = 1; else if ($number > 10) $run = 0; else if ($balls > 120 && $number > 0) $run = 0; else $run = -1; // Increase number of balls $balls += 1; // Are they out? if ($run == -1) { $current_batsman['out'] = 1; $played[] = $current_batsman['id']; $find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>'; $replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>'; $data = str_replace($find, $replace, $data); changeBatsman($current_batsman['id']); echo 'out'; } else { $current_batsman['runs'] += $run; $runs += $run; if ($run == 1 || $run == 3) { swapBatsman($current_batsman['id']); echo 'time to swap'; } echo $run; } // Count outs if ($current_batsman['out'] == 1) $outs += 1; } } function game() { global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman; // Check if possible while ($balls <= 295 && $outs < 10) { selectBowler(); // Actually bowl now bowl(); } } game(); echo $data; I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this: Code: [Select] class my_class { function one () { $two = two (); $three = three (); $five = $two + $three; return $five; } function two () { $two = 2; return $two; } function three () { $three = 3; return $three; } } Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()? Hi everyone, I'm trying to select either a class or an id using PHP Simple HTML DOM Parser with absolutely no luck. My example is very simple and seems to comply to the examples given in the manual(http://simplehtmldom.sourceforge.net/manual.htm) but it just wont work, it's driving me up the wall. Here is my example: http://schulnetz.nibis.de/db/schulen/schule.php?schulnr=94468&lschb= I think the HTML is invalid: i cannot parse it. Well i need more examples - probly i have overseen something! If anybody has a working example of Simple-html-dom-parser...i would be happy. The examples on the developersite are not very helpful. your dilbertone Hello, im very green to php and I am having trouble creating a simple log in script. Not sure why this is not working, maybe a mysql_query mistake? I am not receiving any errors but nothing gets updated in the members table and my error message to the user displays. any help is appreciated! here is my php: <?php session_start(); $errorMsg = ''; $email = ''; $pass = ''; if (isset($_POST['email'])) { $email = ($_POST['email']); $pass = ($_POST['password']); $email = stripslashes($email); $pass = stripslashes($pass); $email = strip_tags($email); $pass = strip_tags($pass); if ((!$email) || (!$pass)) { $errorMsg = '<font color="#FF0000">Please fill in both fields</font>'; }else { include 'scripts/connect_db.php'; $email = mysql_real_escape_string ($email); $pass = md5($pass); $sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$pass'"); $log_check = mysql_num_rows($sql); if ($log_check > 0) { while($row = mysql_fetch_array($sql)) { $id = $row["id"]; $_SESSION['id']; $email = $row["email"]; $_SESSION['email']; $username = $row["username"]; $_session['username']; mysql_query("UPDATE members SET last_logged=now() WHERE id='$id' LIMIT 1"); }//Close while loop echo "You are logged in"; exit(); } else { $errorMsg = '<font color="#FF0000">Incorrect login data, please try again</font>'; } } } ?> and the form: <?php echo $errorMsg; ?> <form action="log_in.php" method="post"> Email:<br /> <input name="email" type="text" /><br /><br /> Password:<br /> <input name="password" type="password" /><br /><br /> <input name="myBtn" type="submit" value="Log In" /> </form> Hi can someone pls help, im tryin a tutorial but keep getting errors, this is the first one i get after registering. You Are Registered And Can Now Login Warning: Cannot modify header information - headers already sent by (output started at /home/aretheyh/public_html/nealeweb.com/regcheck.php:43) in /home/aretheyh/public_html/nealeweb.com/regcheck.php on line 46 Hi, I've got 3 different upload forms in one form. I'm making a function so it just one piece of code. I'm having a bit of a problem changing some of the code so it works for all 3. Here is the function function loadImages ($action, $position) { $link = mysql_connect("","",""); if (!$link) { die('Error: could not connect: ' . mysql_error()); } $db_select = mysql_select_db("",$link); if (!$db_select) { die ("Error: database selection failed: " . mysql_error()); } $page = ($_POST["pageName"]); if ((($_FILES["bfile"]["type"] == "image/gif") || ($_FILES["bfile"]["type"] == "image/jpeg") || ($_FILES["bfile"]["type"] == "image/pjpeg")) && ($_FILES["bfile"]["size"] < 9000000)) { if ($_FILES["bfile"]["error"] > 0) { echo "Return Code: " . $_FILES["bfile"]["error"] . "<br />"; } else { $success = '<p style="font-weight: bold; color: #C00">Upload successful<br />'; // move uploaded temporary file to final destination move_uploaded_file($_FILES["bfile"]["tmp_name"], "uploads/" . $_FILES["bfile"]["name"]); // update database with new filename $filename = $_FILES["bfile"]["name"]; $sql = "UPDATE images SET filename= '$filename' where page = '$page' and position = '$position'"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } } } else { $fail = '<p style="font-weight: bold; color: #C00">Invalid file'; } mysql_close($link); } Now the $action is the bit that will determine whether it's updateTop updateMiddle or updateBottom. $position finds out if it's top middle or bottom if (isset($_POST['updateTop'])) { loadImages ($_POST['updateTop'], "top"); } Here is a sample of the html, it's in a switch case "Products": echo "<p>Image Top</p> <input type=\"file\" name=\"file\" id=\"file\" /> <input type=\"submit\" name=\"updateTop\" value=\"Update $page Top\" /> <p>Image Middle</p> <input type=\"file\" name=\"mfile\" id=\"mfile\" /> <input type=\"submit\" name=\"updateMiddle\" value=\"Update $page Middle\" /> <p>Image Bottom</p> <input type=\"file\" name=\"bfile\" id=\"bfile\" /> <input type=\"submit\" name=\"updateBottom\" value=\"Update $page Bottom\" /> "; break; What I need to do is get $_FILES["bfile" into a variable to see whether it's "bfile" "mfile" or "file" but not sure how to write it. Thanks for the help. When in OOP I have been watching tutorials and some have functions just written like Code: [Select] class user { public $user; public function __construct($u) { $this->user = $u; } } do I need to type public before the function or is it better practice to just put Code: [Select] class user { public $user; function __construct($u) { $this->user = $u; } } Thanks! Hi. I am trying to write a function but they are new to me and confusing me. On multiple pages I am requesting users details. I thought instead of writing out the query every time I want to do this I would include a functions page with the query in it. The only variable I carry from the user is the user name as a session when they log in. The user name is the email address of the person signed in. so here is my first function. As im sure you can see it doesn't work but I don't understand why or how to call it properly. Can someone please explain.... function GetUser($user = "") { $qFindUser = "SELECT * FROM members WHERE email = '$user'"; $rFindUser = mysql_query($qFindUser) or die (mysql_error()); $UserInfo = mysql_fetch_array($rFindUser); } calling the function to return all details of a member as an array. <?php $Name = $_SESSION['MM_Username']; $UserInfo = GetUser($Name); echo $UserInfo['forename']; ?> Hi, I could use a little guidance here. 1) is a function with values to be sent to 2). 1) <!-- use ajax - OnCalc function to send data to your database. --> function OnCalc(value1,op,value2,total) { 2) php file using above function values <?php header( "refresh:5;url='http://localhost/hom...lcprint.php'"); echo 'You\'ll be redirected in about 5 secs. If not, click <a href="http://localhost/hom...hp">here</a>.'; echo '<script type="text/javascript">' , 'OnCalc();' , '</script>'; No error but code not working? Hey guys. Can anyone tell me what this means? function foo { } It is basic php but I don't get it. Should it be called for execution, or does it work automatically, or both? The php manual at w3schools and php.net are too tough for me. That's why I posted here. Thanks! |