PHP - If Statement Always Returning True When It Shouldn't
I have an IF statement that is constantly returning TRUE, even when it shouldn't be. Basically it checks if an array is empty.
Code: [Select] <?php $error = array(); //No blanks if ($street_addr == "" || $city == "" || $state == "" || $zip == "" || $phone1 == "" || $phone2 == "" || $phone3 == "" || $county == "") $error[] = "You left something blank!"; //validate zip if(!preg_match("/^[0-9]{5}$/", $zip)) $error[] = "The ZIP code must be a 5-digit number."; //validate phone number if (!is_numeric($phone1) || !is_numeric($phone2) || !is_numeric($phone3)) $error[] = "Phone can only contain digits"; if (strlen($phone1) < 3 || strlen($phone2) < 3 || strlen($phone3) < 4) $error[] = "Invalid phone number"; $count_errors = count($error); if ($count_errors > 0){ echo "ERROR:<br />"; foreach ($error as $err){ echo "-$err<br />"; } } else { //Other code } ?> So the first part of the IF statement is always executing. $count_errors DOES return 0 when printed out. Any help would be greatly appreciated. Thanks! Similar TutorialsI have a statement $account = $_SESSION['account_id']; $postedby = $account_id; /*both echo out to the same number*/ if($account == $postedby){ echo "DELETE BUTTON"; } i echo'ed out both $account and $postedby and both return 1 but the if statement fails to read as true. HELP!!! thanks in advance! when the page loads it is showing "Registration Successful" under the form, even when nothing has yet to be submitted Code: [Select] <script language='javascript'> function verifyMe(){ var msg=''; if(document.getElementById('username').value==''){ msg+='- User Name\n\n';} if(document.getElementById('password').value==''){ msg+='- Password\n\n';} if(document.getElementById('userid').value==''){ msg+='- Eve User ID\n\n';} if(document.getElementById('api').value==''){ msg+='- Eve API\n\n';} if(msg!=''){ alert('The following fields are empty or invalid:\n\n'+msg); return false }else{ return true } } </script> <form name='Sign Up' action='signup.php' method='POST' onsubmit='return verifyMe();'> <table class='table_form_1' id='table_form_1' cellspacing='0'> <tr> <td class='ftbl_row_1' ><LABEL for='username' ACCESSKEY='none' ><b style='color:red'>*</b>User Name </td> <td class='ftbl_row_1a' ><input type='text' name='username' id='username' size='45' value=''> </td> </tr> <tr> <td class='ftbl_row_2' ><LABEL for='password' ACCESSKEY='none' ><b style='color:red'>*</b>Password </td> <td class='ftbl_row_2a' ><input type='password' name='password' id='password' size='45' value=''> </td> </tr> <tr> <td class='ftbl_row_1' ><LABEL for='userid' ACCESSKEY='none' ><b style='color:red'>*</b>Eve User ID </td> <td class='ftbl_row_1a' ><input type='text' name='userid' id='userid' size='45' value=''> </td> </tr> <tr> <td class='ftbl_row_2' ><LABEL for='api' ACCESSKEY='none' ><b style='color:red'>*</b>Eve API </td> <td class='ftbl_row_2a' ><input type='text' name='api' id='api' size='45' value=''> </td> </tr> <tr> <td class='ftbl_row_1' ><LABEL for='email' ACCESSKEY='none' ><b style='color:red'>*</b>E-mail </td> <td class='ftbl_row_1a' ><input type='text' name='email' id='email' size='45' value=''> </td> </tr> <tr> <td colspan='2' align='right'><input type='submit' name='submit' value='Sign Up'> <input type='reset' name='reset' value='Reset'><br /> </td> </tr> </table> </form> <?php $username = $_POST['username']; $password = $_POST['password']; $userid = $_POST['userid']; $api = $_POST['api']; $email= $_POST['email']; mysql_connect("x", "x", "x"); mysql_select_db ("evepay")or die(mysql_error()); $check = "select username from users where username = '".$_POST['username']."';"; $qry = mysql_query($check) or die ("Could not match data because ".mysql_error()); $num_rows = mysql_num_rows($qry); if ($num_rows != 0) { echo "Sorry, there the username $username is already taken. "; echo "Try again"; exit; } else { $query="insert into users (username, password, userid, api, email) values ('$username', '$password', '$userid', '$api', '$email)"; mysql_query($query); if($query) { echo "Registration Successful"; } else { echo "error in registration".mysql_error(); } } ?> How do I make it only show the successful message after the user fills out the form? I am trying to take all the information from $results and input it into a text file, sometimes we get duplicates in $results so I want to check the text file for the entry before writing it in so we don't get duplicates in the text file. However inarray keeps returning false, even when I echo out the two arrays and they match? Code: [Select] $myfile = "complete.txt"; foreach ($results['info'] as $data) { $output=$fields['firstname']."|".$record['lastname']."|".$record['address']."|".$record['number']."\n"; $handle = fopen($myfile, "r"); $contents = fread($handle, filesize($myfile)); fclose($handle); $list = array(); $list = explode("\n",$contents); $list = array_map("trim", $list); $current = $output; echo in_array($current,$list) ? $current.' exists' : $current.' does not exist'; if (in_array($current,$list)) { print "duplicate"; } else { if($file=fopen($myfile, "a")) { //open file for writing fwrite($file, $output); //write to file } } } I had some code that I'm pretty sure used to work, basically something like the below. Code: [Select] if (preg_match("/[a-zA-Z0-9]+/", $_POST['title'])) { echo $_POST['title'];exit(); } Now i just don't get why it always returns true, even when entering special characters like "!#%?".. The only thing which comes to mind, is that i recently made a move to UTF-8.. *delurk! It had to happen sooner or later!* OK, I am totally and utterly stumped. I have this script: $this->clear_cache ($this->cache_dir, $this->cache_time); if ($this->cache_time > 0) { $current_page = $_SERVER ['REQUEST_URI']; $current_page_encoded = base64_encode($current_page); $current_page_path = $this->cache_dir . $current_page_encoded; if (file_exists($current_page_path)) { // see if there is still a file with the name of the current request URI after cache cleared $content = file_get_contents ($current_page_path); return $content; } } Basically, it is for checking if there is a cached version of the page before running the rest of the script, using the REQUEST_URI as the identifier. So it calls a function to clear the cache, which works fine (and I've tried just deleting the cache files manually anyway). Then it checks if we are even caching, i.e. if cache time is greater than 0. Then it uses the BASE64-encoded REQUEST_URI (under which name the file would have been cached previously) to check if a file with that name still exists in the cache dir, and if so loads it. Now, this works perfectly with a url like: mysite/myscript/mysubpage But when the page has parameters, like: mysite/myscript/mysubpage?search=widgets the file_exists function returns TRUE, even though the directory is empty. I did do a clearstatcache(); but it made no difference and anyway, it wouldn't explain why the URI with query string would fail while the regular one would not. And even if something is wrong with my code elsewhere, the fact is it is returning TRUE for a non-existent file. Can someone prevent my slide into insanity?! Hey here is my code im trying to redirect the index.php to index.php?id=1 the way i have done it doesn't look really good is there a better way to do it please? im trying to redirect to id=1 because otherwise i wont be able to echo out anything... id 1 is default category so is there a way to tell it if $id is empty echo from id 1? <?php $id = $_GET['id']; if($id == ''){ echo "<meta http-equiv=Refresh content=0;url=index.php?id=1>"; } $result = mysql_query("SELECT * FROM pages WHERE id='$id' ",$connect); while($row = mysql_fetch_assoc($result)) { echo $row['anything1']; echo $row['anything2']; } ?> I'm pulling my hair out trying to figure out a simple problem. I've got the following PHP code in an HTML page: $shutoff_date = strtotime($wkend_start_date) - 259200; if ($shutoff_date > $todays_date) { $current_month = date("m"); $current_year = date("y"); $freshman_eligible = 0; if ($current_month >= 2 && $current_month <=7) { $freshman_eligible = 1; } if ($current_month <= 7) { $seniors = $current_year ; } else {$seniors = $current_year + 1; } $juniors = $seniors + 1; $sophomores = $seniors + 2; $freshman = $seniors + 3; echo "HTML Stuff blah, blah, blah"; if ($freshman_eligible = 1) { echo "<option value=\"$freshman\">$freshman</option>";} } The last test to see if $freshman_eligible is equal to 1 is always testing true, and it's actually resetting $freshman_eligible to whatever I put inside the IF statement. No matter what the variable is set to previously, it will reset to whatever I test for in the last section, and hence always tests true. I thought maybe it was an issue with scope, but I'm not sure what the issue would be or how to resolve it. What am I missing??? Hi. I have a simple change password form, when checked and verified and submitted the user is directed to a different web page. I'm getting all the true statements echoed out, but it doesn't go to the go to the next web page. // Thank you Page $insertGoTo = "changepass.php"; header(sprintf("Location: %s", $insertGoTo)); My thought was ounce you get through the while statement without errors you should be able to move to the next check of the actual database... which it does, and it updates the database with the new values. It also echos out Continue 6.... echo "True - Continue 6 GO TO HEADER PAGE"; // Thank you Page $insertGoTo = "changepass.php"; header(sprintf("Location: %s", $insertGoTo)); What am I missing here? Code: <?php session_start(); ?> <?php $submit = $_POST['submit']; // Form Data $email = $_POST['email']; $password_old = $_POST['password_old']; $password_new = $_POST['password_new']; $password_new_con = $_POST['password_new_con']; $errorcount = 0; // Edit anything inbetween the " " for the display error message $errormsg['Email'] = "Email Entered is not in our database"; $errormsg['OldPass'] = "Old Password Entered is Incorrect. Please check your Email"; $errormsg['NewPass'] = "New Password must be between 6 and 32 characters"; $errormsg['NewPassCon'] = "New Passwords do not match."; $errormsg['SecCode'] = "Security Code is Invalid"; $errormsg['dbPass'] = "Invalide Email or activation code. Please Contact <a href='mailto:webmaster@fusionfashionhair.com?subject=Fusion Fashion Hair - Member Activation Error%20Request'>Admin</a>"; $errormsg['NoErr'] = "No Errors, Continue"; $errormsg['PlaceHold'] = ""; $errortrack[] = $errormsg['PlaceHold']; if ($_POST[submit]){ if ($errorstop = "go") { $errorstop="go"; while ($errorstop<>"stop") { //Check for security code if ($_SESSION[key]==$_POST[user_code]){ echo "True - Continue 0"; echo "<p>----------</p>"; $_SESSION[key]=''; } else { echo "False - Stop 0"; $errortrack[] = $errormsg['SecCode']; $errorcount++; $errorstop="stop"; } // check for existance if (!checkEmail($email)) { echo "False - Stop 1"; $errortrack[] = $errormsg['Email']; $errorcount++; $errorstop="stop"; } else { echo "True - Continue 1"; echo "<p>----------</p>"; } // check for existance if (strlen($password_old)>5) { echo "True - Continue 2"; echo "<p>----------</p>"; } else { echo "False - Stop 2"; $errortrack[] = $errormsg['OldPass']; $errorcount++; $errorstop="stop"; } // check for existance if (strlen($password_new)>32||strlen($password_new)<6) { echo "False - Stop 3"; $errortrack[] = $errormsg['NewPass']; $errorcount++; $errorstop="stop"; } else { echo "True - Continue 3"; echo "<p>----------</p>"; } // check for existance if ($password_new_con==$password_new) { echo "True - Continue 4"; echo "<p>----------</p>"; $errorstop="stop";//Get Out of loop } else { echo "False - Stop 4"; $errortrack[] = $errormsg['NewPassCon']; $errorcount++; $errorstop="stop"; } }//End While Loop // Check database require('dbConfig.php'); // Encrypts old password to check with Database Encryped Password $password_old = md5($password_old); $check = mysql_query("SELECT * FROM {$usertable} WHERE email='$email' AND password='$password_old'"); $checknum = mysql_num_rows($check); if ($checknum==1) { echo "True - Continue 5 Set password"; echo "<p>----------</p>"; // Encrypts new password $password = md5($password_new); //run a query to update the account $acti = mysql_query("UPDATE {$usertable} SET password='$password' WHERE email='$email'"); } else { echo "False - Stop 5"; $errortrack[] = $errormsg['dbPass']; $errorcount++; $errorstop="stop"; }//End if checknum echo "True - Continue 6 GO TO HEADER PAGE"; // Thank you Page $insertGoTo = "changepass.php"; header(sprintf("Location: %s", $insertGoTo)); } else { while($errorcount>=0) { // Test display all error messages echo "<p>----------</p>"; echo "<p>Error Count = '$errorcount'</p>"; } die ("PLEASE FILL IN ALL FIELDS"); } } ?> <?php // LINUX PLATFORM OPTION 3 // checkEmail function checks standard email format same as preg_match() // checkEmail function checks DSN records using checkdnsrr Use list() to seperate name and domain using split function // checkdnsrr ONLY WORKS on LINUX PLATFORM // Check to see if domain and username is active // uses fsockopen() to check if its in use using port 25 function checkEmail($email) { // checks proper syntax if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email)) { // gets domain name list($username,$domain)=split('@',$email); // checks for if MX records in the DNS if(!checkdnsrr($domain, 'MX')) { return false; } return true; } return false; } ?> Hi I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated. $looponce = 1; foreach ($this->info as $k => $v) { if ( (($k == 'subject') && ($v['required'])) && (!$this->settings['customSubject'])) { for ($i = 0; $i <= 0; $i++) { $output[] = $this->display_errors('error_system_subject'); } } if ( (($k == 'name') && (!$v['required'])) || ((!array_key_exists("name", $this->info)) && ($looponce == 1)) ) { $output[] = $this->display_errors('error_system_name'); $looponce++; } } That is my loop that i check things in. What i'm more interested in is the name if statement. If currently checks for a name key in an array(below) and makes sure that it is set to required. If it's not set to required, print out a system error and die()'s. I'm looking for ways to remove the need for program errors and just change them to what is needed to run. What i know how to do is, get into the inner array, what i don't know is how to edit the data and put it back exactly as it was given to me. The inner array data can be put back in any order, but the outer array must be in exact order as it was given. above code $this->info = $formdata; $formdata = array( 'name' => array('name'=>"Full Name", 'required'=>false, 'type'=>'text'), # This needs to be required=>true, but i can't trust the user, which is why i have the error. 'telephone' => array('name'=>"Telephone", 'required'=>false, 'type'=>'phone'), ); Any help is greatly appreciated, also am i doing the foreach loop in the code above in an efficient manner or is there another way? The below scenario works fine but why shouldnt you do this? Why can I not just run the mysql_connect and mysql_select_db at the top of each page and then run my queries under all of this. What I have read is that the mysql_connection will die after the script finishes (at the end of the page) any way so why do people create mysql_connection objects as php is stateless so it doesnt save this any way. Code: [Select] <?php mysql_connect('localhost', 'user', 'pass'); mysql_select_db('test'); ?> <html> <body> <?php $query = mysql_query("Select * from data"); while($row = mysql_fetch_array($query)) { echo $row['name']."<br />"; } ?> -------------- OTHER HTML HERE --------------- <?php $query = mysql_query("Select * from addresses"); while($row = mysql_fetch_array($query)) { echo $row['postcode']."<br />"; } ?> </body> </html> I have a function with a query and then a while loop and then an if file_exists with an image path. I am getting the image path displayed as text. Would this be because I am running the query through json encoding? Hello there, I have a problem where the following code is running the query before it should. private function isAccountRegistered($AccountUsername, $AccountEmail) { global $Class; if($Class['MySQL']->currentRows("SELECT * FROM xhost_accounts WHERE account_username = '".$Class['MySQL']->parseClientInput($AccountUsername)."'") == 1) { return USERNAME_REGISTERED; } else if($Class['MySQL']->currentRows("SELECT * FROM xhost_accounts WHERE account_email = '".$Class['MySQL']->parseClientInput($AccountEmail)."'") == 1) { return EMAIL_REGISTERED; } } public function createClientAccount($AccountUsername, $AccountPassword, $AccountEmail, $AccountRealname) { global $Class; if($this->isAccountRegistered($AccountUsername, $AccountEmail) == USERNAME_REGISTERED) { echo("<div class=\"warning\">Unfortunately this username is in use by another member!, please select another!.</div>"); } else if($this->isAccountRegistered($AccountUsername, $AccountEmail) == EMAIL_REGISTERED) { echo("<div class=\"warning\">Unfortunately this email address is in use by another member!, please select another!.</div>"); } else { if($Class['MySQL']->Query("INSERT INTO xhost_accounts (account_username, account_password, account_email, account_realname, account_regdate, account_regtime, account_level, account_balance, account_notifications) VALUES('".$Class['MySQL']->parseClientInput($AccountUsername)."', '".md5($Class['MySQL']->parseClientInput($AccountPassword))."', '".$Class['MySQL']->parseClientInput($AccountEmail)."', '".$Class['MySQL']->parseClientInput($AccountRealname)."', '".date("d/m/y")."', '".time()."', '0', '0.00', 'Enabled')")) { $Class['Core']->refresh('index.php'); } else { echo("<div class=\"warning\">Unfortunately something went wrong there, please try again!.</div>"); } } } For some reason when the code above is run it executes if($Class['MySQL']->Query("INSERT INTO xhost_accounts (account_username, account_password, account_email, account_realname, account_regdate, account_regtime, account_level, account_balance, account_notifications) VALUES('".$Class['MySQL']->parseClientInput($AccountUsername)."', '".md5($Class['MySQL']->parseClientInput($AccountPassword))."', '".$Class['MySQL']->parseClientInput($AccountEmail)."', '".$Class['MySQL']->parseClientInput($AccountRealname)."', '".date("d/m/y")."', '".time()."', '0', '0.00', 'Enabled')")) Before it runs: if($this->isAccountRegistered($AccountUsername, $AccountEmail) == USERNAME_REGISTERED) { echo("<div class=\"warning\">Unfortunately this username is in use by another member!, please select another!.</div>"); } Causing it to say that the username is registered every time yet still inserting the account into the database, its returning that its registered because it inserts it before doing the check, does anybody have any idea why, this really has confused me, thanks for your time. Ok all I need some help with this. I have been stuck for two days. Basically I have a form that asks a registrant their gender and age, then my script spits out a list of race categories they qualify for. The situation calls for the registrant to be able to register for any category YOUNGER than them, but not older. Screen Shot #1 shows my database setup (this can be changed if you have any better ideas...) that holds the race category information. Here is the sql statement I am using to pull a female racer information, where $race_age is their submitted age. "SELECT * from counts where female=1 and $race_age < age_end and $race_age > age_start" This works, but doesn't pull any categories YOUNGER Than their age. I'm stumpped Thanks for any help in advance. I'm working on a fairly straight forward facet of an image gallery application where the client can upload a zip file full of photos and it extracts them one by one to a temp folder, resizes it and moves it to the pic folder, creates a thumbnail, then deletes it from the temp folder All that works fine, but I'm testing it in a situation where I'm uploading a 56 MB zip file, my max_file_size is 128 MB, and it gives me the 'max_file_size' error. Anyone else ever have this problem or have any ideas on how to solve it? Say a script has ignore_user_abort(true); set. If the user aborts the connection and print is called, the buffer doesn't get written anywhere. So shouldn't print() return false in this case? To clarify, I know it doesn't, but shouldn't it? If not, why not? Is there any reason why I would want to use this... Code: [Select] $_SESSION['loggedIn'] = TRUE; versus this... Code: [Select] $_SESSION['loggedIn'] = 1; (The first one is easier to read...) Debbie I am wondering if these "true" values are the same to PHP... Code: [Select] <a href="' . BASE_URL . 'members/log_in.php?addComment=true">Log In</a> Code: [Select] if (isset($_GET['addComment']) && ($_GET['addComment']==TRUE)){ Debbie Apart from the fact this can cause an infinite loop is it OK to use? $user->reset_token = $user->generate_password(32); // Make sure the token is unique while(TRUE) { $count = ORM::factory('manager')->where('reset_token', '=', $user->reset_token)->count_all(); if($count < 1) break; $user->reset_token = $user->generate_password(32); } Or would you approach the logic for this differently? Thoughts appreciated. Cheers <?php $id1 = '5' ; $id = array(1,2,3,4,5,6,7); foreach($id as $value){ if($id1==$value){ echo 'One of them matches, ' ; echo 'Do not execute command <BR>' ; } ////// if ends here } ////// loop ends here ?> How to do something if all statements are false ? like when id $id1 = '10' , ? |