PHP - If Statement (validating Character)
i'm trying to an if statement so that a piece of code is only executed if a returned variable equals a letter in the alphabet(any letter)
the variable is from a $_GET, and all i want to check is if the variable contains a letter. This is what i have so far, but it doesnt work $sort=$_GET[orderby]; if ($sort=="[A-Z]") { $read=mysql_query("SELECT * FROM films WHERE title LIKE '".$sort."%'") or die(mysql_error()); $result=mysql_num_rows($read); } else { $read=mysql_query("SELECT * FROM films ORDER BY title") or die("query failed"); $result=mysql_num_rows($read); } Any help would be great. Similar TutorialsI'm having issues with the following: Code: [Select] <?php session_start(); $_SESSION['username']=$_POST['username']; $_SESSION['password']=$_POST['password']; if($_SESSION['username']=="username" && $_SESSION['password']=="password"){ if($_GET['product']=="add"){ $content.=' <p><label>Product Name:</label> <input type="text" name="product_name" size="30" /> <label>Product Price:</label> <input type="text" name="product_price" size="5" /> </p> <p><label>Product Category:</label> <input type="text" name="product_category" size="30" /></p> <p><label>Product Link:</label> <input type="text" name="product_link" size="30" /></p> <p><label>Product Image:</label> <input type="text" name="product_image" size="30" /></p> <p><label>Product Tag:</label> <input type="text" name="product_tag" size="30" /></p> <p><label>Product Keywords:</label> <input type="text" name="keyword" size="30" /></p> <p><label>Product Features:</label><br /> <textarea name="product_features" rows="10" cols="60"></textarea> </p> <p><label>Product Pros:</label><br /> <textarea name="product_pros" rows="5" cols="30"></textarea> </p> <p><label>Product Cons:</label><br /> <textarea name="product_cons" rows="5" cols="30"></textarea> </p> <p><label>Product Description:</label><br /> <textarea name="product_description" rows="10" cols="60"></textarea> </p> <p><label>Product Notes:</label><br /> <textarea name="product_notes" rows="5" cols="30"></textarea> </p> '; $logout='<div><a href="./acp_admincp.php?log-out">Log-Out</a></div>'; } elseif($_GET['product']=="view"){ } else{ $content.=' <a href="./admincp.php?product=add">Add New Product</a> <br /> <a href="./admincp.php?product=view">View Products</a> '; } } elseif(isset($_GET['log-out'])){ session_start(); session_unset(); session_destroy(); header("Location: ./admincp.php"); } else{ $content=' <form action="./admincp.php" method="post"> <p><label>Username:</label> <input type="text" name="username" size="30" />'; $content.='</p> <p><label>Password:</label> <input type="password" name="password" /></p>'; $content.='<p><input type="submit" value="Submit" name="Submit" /></p> </form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <base href="http://ghosthuntersportal.com/" /> <title>Ghost Hunter's Portal - Admin Control Panel</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="verify-v1" content="" /> <meta name="keywords" content="ghost, hunters, hunter, ghosts, spirit, spirits, paranormal, investigation, investigator, investigators, k2, emf, meter, kii" /> <meta name="description" content="Ghost Hunters Potal. Parnormal research equipment store." /> <meta name="author" content="Andrew McCarrick" /> <meta name="robots" content="index, follow" <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <img src="./logo.png" alt="Ghost Hunter's Portal Admin Control Panel" /> <br /> <div style="color: #AA44AA; font-size: 26px; margin-top: -30px; margin-left: 125px;">Admin Control Panel</div> <?php echo $logout; echo $content; ?> </body> </html> I can log-in, and get to the page with the two links on it. However, once I click one of the links it falls back to the log-in page, and it ends up being a never ending loop. It's doing this: Log-In --> Page with links ---> Log-In page again Should be doing this: Log-In --> Page with links --> Add Product page or View Products page I can never get into the the actual sub page. Just to be clear, the address bar actually shows product=add or product=view, but it still shows the log-in page. How much should you validate a First Name? This is my code... // Validate First Name. if (empty($trimmed['firstName'])){ $errors['firstName'] = 'Please enter your First Name.'; }else{ if (preg_match('#^[A-Z \'.-]{2,20}$#i', $trimmed['firstName'])){ $firstName = $trimmed['firstName']; }else{ $errors['firstName'] = 'First Name must be 2-20 characters (A-Z \' . -)'; } } I did this for fear if I left things wide-open it would be a security risk. And in the U.S. at least, the above would really cover all valid First Names. Thoughts? Debbie Hi, I have a user system where people login to my site with their emails. The thing I am after is when a person is registering I want to validate that they have entered a valid email with @.com in the string and not just some repetitive characters e.g. wwwwwww. Could some one guide me what is the best way to check for a valid email and for repetive characters in any given field examle firstname. One last thing I would also like to check that a person only enters Alphabets for name and stuff. Hello all, I need your help again. I have this page where the user inputs data: <?php include "include/dbc.php"; include "include/header.inc"; #error checking will go here ?> <style type="text/css"> .mydate{ color:#00F; text-decoration:underline; cursor:pointer; } </style> <script type="text/javascript"> function displayDate(d){ var date=new Date(); var D=date.getDate(); date.setDate(D+d); var YYYY=date.getFullYear(); var MM=date.getMonth()+1; MM<10?MM='0'+MM:null; var DD=date.getDate(); DD<10?DD='0'+DD:null; var span=document.getElementById('date'); span.innerHTML= 'Entries for '+MM+'/'+DD+'/'+YYYY; } onload=function(){displayDate(0)}; </script> <h1>Food Diary</h1> <div class="full"> <center><div><span class="mydate" onclick="displayDate(-1)"><img src="images/left_arrow.png" border="0">Yesterday</span> <span id="date" style="font-size:2em;"></span> <span class="mydate" onclick="displayDate(1)">Tomorrow<img src="images/right_arrow.png" border="0"></span></div><br /> <a href="#" onclick="displayDate(0);return false;">Today</a> </center> <div class="full"> <form name="exercise" id="exercise" method="GET" action=""> <center><table> <tr> <td><h3>Add an Activity</h3></td> </tr> <tr> <td><input name="NewSearchString" style="width: 100px" type="text"/> <input type="submit" value="Search" /> </td> </tr> <tr> <td> <select name="activity"> <option value="_">Activity Browse...</option> <option value="all">All Activities</option> <option value="biking">Biking</option> <option value="condition">Conditioning</option> <option value="dancing">Dancing</option> <option value="fish">Fishing & Hunting</option> <option value="Home">Home Activities</option> <option value="misc">Miscellaneous</option> <option value="music">Music Playing</option> <option value="occupation">Occupation</option> <option value="running">Running</option> <option value="sports">Sports</option> <option value="walking">Walking</option> <option value="water">Water Activities</option> <option value="winter">Winter Activities</option> </select> <input type="submit" value="Submit" /></td></tr></table></center></form> </td> </tr> </table> </center> <table width="100%"> <tr bgcolor="#66CC33"> <td><div>Activity</div></td> <td><div>Specific Activity</div></td> <td><div>Time (hh:mm)</div></td> <td><div>Distance</div></td> <td><div>Units</div></td> </tr> <tr bgcolor="#66CC33"> <td><div></div></td> <td><div></div></td> <td><div></div></td> <td><div class="Float"></div></td> <td class="cp_Distance"><div></div></td> </tr> <?php if(isset($_GET[activity])) { $category=$_GET[activity]; $result = mysql_query("SELECT * FROM exercise WHERE type='$category'"); ?> <form action="add_activity.php" method="POST"> <?php while($row = mysql_fetch_array($result)) { echo '<tr><td><div>'.$row[Type].'</div></td>'; echo '<td><div>'.$row[Name].'<input type="hidden" name="exerciseid[]" value="'.$row[Name].'"></div></td>'; echo '<td><div><input type="text" name="duration['.$row['Name'].']"></div></td>'; echo '<td><div><input type="text" name="distance['.$row['Name'].']"></div></td>'; echo '<td><div><select name="metric[]"> <option value=""></option> <option value="mile">mile</option> <option value="Km">km</option> <option value="M">m</option>; <option value="Yard">yrd</option> <option value="Feet">ft</option> </select></div></td></tr>'; echo'<input type="hidden" name="submitted" value="1">'; } mysql_close(); ?> <tr><td colspan="6" align="center"><input type="submit" name="submit" value="Add Activities" onClick="return confirm( 'Are you sure you want to submit the activities?');"></td></tr> </form> <?php } ?> <tr bgcolor="#66CC33"> <td><div></div></td> <td><div></div></td> <td><div></div></td> <td><div class="Float"></div></td> <td class="cp_Distance"><div></div></td> </tr></table> <div></div> <?php include "include/footer.inc"; ?> I want to validate that the user enters data for at least one of all the fields provided (distance, duration, metric). If someone could help me get started I'd greatly appreciate it. Hi all, Hi have a bit of a problem that I am completely stuck on. I have a form on a website that needs checkboxes to be processed by PHP, but i have no idea how to implement them. I have found examples, but my knowledge of php is exactly zero, so its confusing the hell out of me. The website is: http://www.geelongnannies.com.au/test/employment.html http://www.geelongnannies.com.au/test/freecontactformprocess3.php http://www.geelongnannies.com.au/test/freecontactformsettings.php if anyone can have a look and give me an example of how to change the php to process the checkboxes when submitted, I will be very grateful cheers! I have the following code below to validate a date that the user types in. But I am getting the following error: "Warning preg_match() [function.preg-match]: Unknown modifier '('" Code: [Select] if(!empty($_POST['exp_date'])) { $pattern = '(^[0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,4}$)'; // 1 to 4 digits $exp_date = trim($_POST['exp_date']); if(preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([a-zA-Z]{1,})' // 1 or more alpha .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,4}$)'; // 1 to 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[a-zA-Z]{1,})' // 1 or more alpha .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,4}$)'; // 1 to 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[a-zA-Z]{1,})' // 1 or more alpha .'([0-9]{2})' // 2 digits .'([0-9]{4}$)'; // 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{4})' // 4 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2})' // 1 or 2 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2}$)'; // 1 to 2 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{2})' // 2 digits .'([0-9]{2})' // 2 digits .'([0-9]{4}$)'; // 4 digits if (preg_match($pattern, $exp_date)){ $pattern = '(^[0-9]{4})' // 4 digits .'([^0-9a-zA-Z])' // not alpha or numeric .'([a-zA-Z]{1,})' // 1 or more alpha .'([^0-9a-zA-Z])' // not alpha or numeric .'([0-9]{1,2}$)'; // 1 to 2 digits } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please enter a valid expiration date.'; } } else { $errors[]= 'Please input an expiration date.'; } This topic has been moved to Other Programming Languages. http://www.phpfreaks.com/forums/index.php?topic=347582.0 Hello.. I have Two HTML form and one is a Check boxes form that enable users to select their category. Then I need to display second form according to the categories they selected in first form. I use this code in first form to validate form submission.. if ( isset( $_POST['category']) && sizeof( $_POST['category']) <= 3) { $category = $_POST['category']; } else { $errors[] = 'Please select atleast 1, not more than 3 categories'; } If errors array is empty I did this.. if ( empty( $errors )) { // If everything's OK $_SESSION = $category; $url = 'http://localhost/lanka_institute/tutorsignup/select_subjects.php? // Define the URL. ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } Can I know and is this correct? I display category list from mysql category table, it has category name and category id this is my html part from first page echo '<td width="50%"><input type="checkbox" name="category[]" vlaue="' . $info['category_id'] . '" /> ' . $info['category_name'] . '</td>'; any help appreciated. Thanks in advance.. I know via firebug that the correct parameters were passed to my process page and the parameter being passed that in caused issues on the process page is $characterIDList. What's causing the issue is that its not inserting the value into the insert query. The rest of the insert query works fine. process page $characterIDs = explode(',', $_POST['characterIDList']); foreach($characterIDs as $itm){ $id = (int)$itm; } $defaultcharid = (int)$characterIDs[0]; $query = "INSERT INTO `handlers` (username, password, firstname, lastname, email, status_id, isadmin, default_character_id, creator_id, datecreated) VALUES ('$username','$password','$firstname','$lastname','$email','$status','$admin', '$defaultcharid', 1, NOW())"; Hello, I am trying to validate my form using php and would like some advice as this is the first time I have attempted this. I have a script which runs when the user clicks the submit button. What I am trying to do is validate the user input before inserting it into the database. This is the script: [font=monospace]<?php session_start(); $dbhandle = mysql_connect('localhost', 'root', '') or die("Unable to connect to MySQL"); $selected = mysql_select_db("commentdatabase",$dbhandle) or die("Could not select the database"); $name = check_input($_POST['fname']); $loc = check_input($_POST['loc']); $com = check_input($_POST['com']); function check_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $sql = "INSERT INTO userinfo (name, location, comment) VALUES ('{$name}','{$loc}','{$com}')"; if(!mysql_query($sql, $dbhandle)) { die('Error: ' . mysql_error()); } header('Location: ../contact.php'); mysql_close(); ?> [/font] What's happening is that when it is submitted to the database, it is displaying < and > characters as < and >. Yet once being redirected with the header function the input is displayed with the < and > signs. I'm not sure if the function in the action script is in the wrong place or not. I have tried moving it around above and below the post variables. Just looking for a bit of advice really. Thank you, Regards, BuNgLe I am debugging a PHP file that validates a user registration form. I'm very confused on this error message I'm receiving. ( Parse error: syntax error, unexpected '[' in C:\wamp\www\reg.php on line 17 ) I have looked until I cross-eyed to finf the syntax error. Here is a copy of my code: <?php // Post registration to database // Connects to your Database $userName = "taft65_admin"; $passWord = "taft65_paris4505"; $host="localhost"; $dbName = "taft65_members"; mysql_connect("dbName", "userName", "passWoord", "host") or die(mysql_error()); mysql_select_db("dbn") or die(mysql_error()); //This code runs if the form has been submitted if (isset($_POST['submit'])) { [color=yellow]//This makes sure they did not leave any fields blank if (!$_POST['id'] | !_POST['userName'] | !$_POST['passWord'] | !$_POST['confpassWord'] | !$_POST['email'] ) { die('You did not complete all of the required fields'); }[/color] // checks if the userName is in use if (!get_magic_quotes_gpc()) { $_POST['userName'] = addslashes($_POST['userName']); } $usercheck = $_POST['userName']; $check = mysql_query("SELECT userName FROM users WHERE userName = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { die('Sorry, the userName '.$_POST['userName'].' is already in use.'); } // this makes sure both passWoords entered match if ($_POST['passWord'] != $_POST['ConfPassWord']) { die('Your passWoords did not match. '); } // here we encrypt the passWord and add slashes if needed $_POST['passWord'] = md5($_POST['passWord']); if (!get_magic_quotes_gpc()) { $_POST['passWord'] = addslashes($_POST['passWord']); $_POST['userName'] = addslashes($_POST['userName']); } // now we insert it into the database $insert = "INSERT INTO registration (userName, passWord, email ) VALUES ('".$_POST['userName']."', '".$_POST['passWord'].", '".$_POST['email']."')"; $add_member = mysql_query($insert); ?> <p>Thank you, you have successfully registered. <a href="memPage.html"></a>you may now login.</p> Can someone help me with this by checking the code and tell me where I wen in error. BobLan66 Hi All, I'm trying to validate file types and keep seeing an error. I only allow .gif, .jpg or .png. However, if I upload any of those file types, I get an error message.... If I echo out $filetypeCheck, I get image/png, which is corrent... Code: [Select] $filetypeCheck = $_FILES["file"]["type"]; if( ($filetypeCheck != "image/gif") || ($filetypeCheck != "image/jpeg") || ($filetypeCheck != "image/png") ) { $val_error[] = 'File Type Error! (.gif, .jpg and .png only)'; } Whats going on here? A form on my website uses several drop down boxes. One to select an id number from a list retrived by a query. The others to get a start and stop time. Using two for each, one for hours, one for minutes. I already have some validation code which works fine, however, I can't seem to be able to use > or < mathematical signs with the times (ie, the start time must be < than the stop time). Also, I have Code: [Select] value="<? echo $name; ?>" in each of the fields to re-insert the data as it gets erased if the form isn't correct. How do I do the same for the drop downs? I hope this makes sense. Code: [Select] <? // only validate form when form is submitted if(isset($Submit)){ $error_msg=''; if(trim($starttime)==(trim($stopttime))) { //drop down $error_msg.="starttime cannot equal stop time.<br>"; } if(trim($starttime)>(trim($stopttime))) { //drop down $error_msg.="starttime cannot be greater than stop time.<br>"; } if(trim($startfuel)<(trim($stopfuel))) { //text field $error_msg.="Departure fuel cannot be less than arrival fuel<br>"; } if(trim($id)=="sca") { //query powered drop down (this one works, but doesn't re-select the option $error_msg.="Please select the id number.<br>"; } http://southerncrossairlines.ausvirtual.com/New%20Site/Complete/validation/Untitled-1.php Hi, what is they best way to validate user input of strings? A couple of examples would be : 1> If i wanted to check for the existance on the coma ',' character in a string and replace it with a dash '-' character? 2> To check wether a user has entered a valid ip address in the form of x.x.x.x where x can range from 0-255? I think i may need ereg/preg to do this but i have no idea about how to layout the syntax. Thanks for looking. This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=310792.0 OK, so one of my cameras includes a "Copyright" field in the array returned from the exif data and one doesn't. Does anyone have any ideas how one would test for this field, and if it doesn't exist fill the relevant variable with the copyright info. I have been trying to solve this for a couple of hours now without a great deal of success, what I have is:- Code: [Select] $exif = exif_read_data('thistle.jpg', 'EXIF'); $name = $exif['FileName']; $height = $exif['ExifImageWidth']; $width = $exif['ExifImageLength']; $copy = $exif['Copyright']; $model = $exif['Model']; $exposuretime = $exif['ExposureTime']; $fnumber = $exif['COMPUTED']['ApertureFNumber']; $iso = $exif['ISOSpeedRatings']; $date = $exif['DateTime']; echo "File Name: $name<br />"; echo "Comment: " . $exif['COMMENT'][0] . "<br />"; echo "Height: $height<br />"; echo "Width: $width<br />"; echo "Copyright: $copy<br />"; echo "Camera: $model<br />"; echo "Shutter Speed: $exposuretime<br />"; echo "F number: $fnumber<br />"; echo "ISO: " . $iso . "<br />"; echo "Date & Time: $date<br /><br />"; Whatever I try always seems to end with "Notice: Undefined index: Copyright in C:\wamp\www\php\exif-read.php on line 11" it is obviously Code: [Select] $copy = $exif['Copyright'];that is causing the problem, and I can't work out just how to test for the existence of "Copyright" and head this problem off... Hi Guys Can anyone tell me why this doesn't work? Code: [Select] <?php $form = "<form action='test.php' method='POST'><input type='text' name='test' /> <input type='submit'>"; echo $form; $name = $_POST['test']; class validate { function check_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } } $z = new validate(); echo $z->check_input($name); ?> Also, when it comes to validating POST data that's input via a form and retrieving it is it secure to set a variable for the Post i.e. Code: [Select] $name = $_POST['test']; or is more secure to pass Code: [Select] $_POST['test'] straight into the validation? It just occurs to me if you pull the post into a variable then you're inviting insecure code into your script. Though i am a complete noob at this so might be talking rubbish! Any light you can shed on why my little script isn't working would be appreciated and any tips on the best method for validating data securely would also be welcome Thank you Drongo Hello Everyone, I have to change the if statements to a switch statement, in this game. Can anyone help? Thanks. var checkKeyPressed = function (e) { // Press key A or key D to make dog run to the left or right // The running speed is specified by the step variable, 10 by default. // If you replace 10 with a larger integer, the dog will run faster. //press A, dog runs left if (e.keyCode == "65") { if (prex[0] > 5) { prex[0] = prex[0] - step; } } //press D, dog runs right if (e.keyCode == "68") { if (prex[0] < right) { prex[0] = prex[0] + step; } } }; all i want is for when their is a _ to be replaced with a space so i tried these and neither worked Code: [Select] <?php $pmod = str_replace("_"," ",$p); $pmod = preg_replace("_"," ",$p); ?> so i was wondering if because this was in a while statement, is this the reason its not working, and if so how should i fix it (this is the while) Code: [Select] <?php while ($z <= $w){ $p = $multi[$z]; $pmod = str_replace("_"," ",$p); echo "<a href='tag.php?tag=$p'" . $p . ">" . $pmod . "</a> "; $z++; } ?> Hi, does anybody know why I get a question mark inside a diamond shape where a pound sign should be when i retrieve data from a mysql database? I have tried using latin1_general_ci and utf8_general_ci and they both do the same, don't know whether that is anything to do with it or not? Any help would be greatly appreciated. |