Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I wanted to thwart POST if the number of characters entered is less than 6 use this code:
<?php
if(isset($_POST['button']))
{
$id = $_SESSION['user_session'];
$u_password = $_POST['password'];
if($crud->updatePassword($id,$u_password))
{
$msg = $msgsucces;
}
else if($u_password < 6) {
$msg = "<div class='alert alert-warning'><strong>Failed!!</strong> Minimum length 6 character</div>";
return false;
}
else
{
$msg = $msgfailled;
}
}
echo $msg ;
?>
But apparently it did not work. What is wrong?
You can use your conditions as like that:
$msg = "";
if(strlen($u_password) < 6) {
$msg = "<div class='alert alert-warning'><strong>Failed!!</strong> Minimum length 6 character</div>";
}
else{
if($crud->updatePassword($id,$u_password))
{
$msg = "success message";
}
else {
$msg = "failure message";
}
}
echo $msg;
For checking length of an input you can use strlen() function.
Side note:
Note that I have remove return false from ist condition.
Also suggest you to always add error_reporting() in your file this will help you to save your time. (Only for local environment not for production).
with $u_password <6 you are not really checking length.
You need strlen function to get the length and compare to 6 so we use strlen function
Rule of thumb is you should have wrong cases before the write one.
The last else is executed if $crud->updatePassword($id,$u_password) fails ie false.
if(strlen($u_password) < 6)
{
$msg = "<div class='alert alert-warning'><strong>Failed!!</strong> Minimum length 6 character</div>";
return false;
}
else if($crud->updatePassword($id,$u_password))
{
$msg = $msgsucces;
}
else {
$msg =$msgfailled;
}
}
echo $msg ;
?>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
If the phone number matches , I am able to print "Yes". If it doesnot match , i need to print "No". But if i include else part , its executing only else part. Please guide me how and where to write else part.
<?php if($re['phone_v'] == "1"){
echo "Yes";
}else if($re['phone_v'] == "0"){
for($i=0;$i < count($crusers);$i++) {
if ($re['phone'] == $crusers[$i]['phone']) {
echo "Yes";
}
}
}
?>
I am checking condition inside table in view. small thing is making complicated.
This will help you.
$re['phone_v'] = 0;
$re['phone'] = 1;
$crusers[0]['phone'] = 1;
if($re['phone_v'] == "1"){
echo "Yes";
}else{
if($re['phone_v'] == "0")
{
for($i=0;$i < count($crusers);$i++)
{
if ($re['phone'] == $crusers[$i]['phone'])
{
echo "Yes11";
}else{
echo "No";
}
}
}
}
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.
Code:
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit)){
if ($guess/2 %0){
echo "the number you are guessing is not odd";
}elseif{
($guess<$rand)
echo "Your Guess is Smaller than the secret number";
}elseif{
($guess>$rand)
echo "Your Guess is bigger than the secret number";
}else{
($guess==$rand)
echo "you guessed currectly. now try anouthe number!";}
else
header("Location: index.php");
exit();}
?>
Can you try this?
You placed the '()' in your elseif wrong.
<?php
$rand = rand(1, 99);
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit))
{
if($guess / 2 % 0)
{
echo "the number you are guessing is not odd";
}
elseif($guess < $rand)
{
echo "Your Guess is Smaller than the secret number";
}
elseif($guess > $rand)
{
echo "Your Guess is bigger than the secret number";
}
elseif($guess == $rand)
{
echo "you guessed currectly. now try anouthe number!";
}
}
else
{
header("Location: index.php");
exit();
}
?>
I have not tested this code, so i need your feedback. Edit: You've confirmed this worked.
I'd like to provide you the manual about elseif:
http://php.net/manual/en/control-structures.elseif.php
Please consider easier/cleaner coding. Personally I like to use ':' instead of '{}', it's less code and easier to read when you use HTML mixed with PHP like:
<?php
$rand = rand(1, 99);
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit)):
if($guess / 2 % 0):
echo "the number you are guessing is not odd";
elseif($guess < $rand):
echo "Your Guess is Smaller than the secret number";
elseif($guess > $rand):
echo "Your Guess is bigger than the secret number";
elseif($guess == $rand):
echo "you guessed currectly. now try anouthe number!";
else:
header("Location: index.php");
exit();
endif;
?>
And don't forget to check the $_POST data.
Same goes for array, but thats a side note:
$arr = array(1 => 'hi', 2 => 'hello'); // old
$arr = [1 => 'hi', 2 => 'hello']; // new
That's not the correct syntax for an if-else construct in php.
The elseif part needs to have a condition right after it (before the opening brace), while else doesn't expect a condition at all.
if ($guess/2 %0){
echo "the number you are guessing is not odd";
} elseif ($guess<$rand) {
// ....
} else {
echo "you guessed currectly. now try anouthe number!";
}
Of course, before your else you have to be sure that the if and elseifs match all the "wrong" cases.
I am using the code bellow in a formmail. But i want to change the code, so user input can be both numbers and letter and others, and so it can be any lenght. Hope someone can help with the 2 changes. Thanks.
if(isset($_POST['idcode'])) {
if(strlen($_POST['idcode']) != 8 || !is_numeric($_POST['idcode'])) {
$error = "input must contain 8 numbers";
} else {
If you want to make it accepts everything do this:
if(isset($_POST['idcode'])) {
// code here
} else {
$error = "you must set the idcode"; // can be changed
}
But if you want to check for length of 8 and up do this:
if(isset($_POST['idcode'])) {
if(strlen($_POST['idcode']) >= 8) {
// code here
} else {
$error = "you need to have at least 8 chars"; // can change
}
} else {
$error = "you must set the idcode"; // can be changed
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Something I've never been sure about is how many variable checks to do in PHP. For example take the following piece of code. I am not checking any of the variables before I assign them or pass them to a function to see if they contain what I expect
$carId = '12';
$aCar = fetchCar($carId);
$make = $aCar['make'];
$model = $aCar['model'];
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
Now if I add some checks
$carId = '12';
if(is_numeric($carId))
{
$aCar = fetchCar($carId);
if(isset($aCar['make']) && is_string($aCar['make']))
{
$make = $aCar['make'];
}
else
{
//Report error
}
if(isset($aCar['model']) && is_string($aCar['model']))
{
$model = $aCar['model'];
}
else
{
//Report error
}
if(isset($aCar['year']) && is_numeric($aCar['year']))
{
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
}
else
{
//Report error
}
}
else
{
//Report errors
}
The code is now better but is it a bit too excessive and bloated? Should I be doing this many checks?
If I shouldn't be doing this many checks where do you draw the line between what you should and shouldn't check?
This is the dilemma of a dynamic type language.
It depends heavily on what fetchCar() function is doing.
The approach i would take is assume fetchCar is returning a car array or throwing exception.
If you combine this with good exception handling logic you can end up with clean and stable code.
For example:
function fetchCar($id) {
$car = queryDatabaseSomehow();
if (empty($car)) {
throw new ExceptionNotFound();
}
//eventually you can put your type checking here?
if (!isset($car['x']) || !is_string($car['x'])) {
throw new ExceptionDb();
}
}
echo fetchCar(3)['make'];
Also if you would like to do this super-proper and go fully OOP, Car should become a class with make,model and year as its members. fetchCar() would return Car or throw Exception. But this is not always desirable of course.
One issue that some people haven't noticed. Be wary of using is_string:
<?php
$var = "test";
$var['something'] = 2;
if(is_string($var['something'])) {
echo "Hello world!"; // Will echo this because $var is a string!
} else {
echo "Hello hell!";
}
echo "<br/>";
echo $var['something']; // returns 2
?>
PHPFiddle.
Compare it with this:
$var = array('something' => 2);
if(is_string($var['something'])) {
echo "Hello world!"; // $var is now an array
} else if (is_numeric($var['something'])) {
echo "Hello hell!"; // Will echo this because $var is string!
}
echo "<br/>";
echo $var['something'];
You need to check whether $var is an array, as it might give you unexpected results. isset($var['something']) will return true in the first example.
To answer your question, I don't think those are too many checks. It really depends on what fetchCar() does and how it gets the data. If you can't trust it (say, it's based on user data) then you should perform all these checks. If not, then there is no point really.
I rather turn it all into a function that can be reused for these cases.
function check_keys($arr_check, $arr_cond) {
$boo_success = TRUE;
foreach(array_keys($arr_cond) as $h)
if (in_array($arr_cond[$h], array('is_string', 'is_numeric'))) {
if ( ! isset($arr_check[$h]) or ! ($arr_cond[$h]($arr_check[$h]))) {
$boo_success = FALSE;
echo "The key {$h} is missing!";
// If run through a class, $this->errors[] = 'error message';
}
} else {
$boo_success = FALSE;
echo 'Invalid function';
}
return $boo_success;
}
$arr_keys = array('make' => 'is_string',
'model' => 'is_string',
'year' => 'is_numeric');
if (check_keys($aCar, $arr_keys)) {
// Run successful stuff
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {