I have some code written in php to validate a postcode field in my form. The code is meant to check that the field is not empty (mandatory) and matches one of 5 usable postcodes, if not it displays an alert. The problem i am having is that when i leave the field empty and hit the submit button the proper alert is show but if i enter a wrong value and hit submit the form just loads to a blank screen, can anyone spot a mistake in my code? :
<?php
if (isset($_POST['submit'])) {
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "";
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
return true;
}
$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
return false;
} else if(empty($post)) {
$msgp = '<span class="error"><b>Please enter postcode</b></span>';
}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post" /><?php echo $msgp; ?>
</form>
return? Return where?
When you return in your main code, it's (nearly) the same as die()'ing.
So when you return, the remaining PHP won't be executed anymore.
I'd consider to set some variable like $success = true/false; instead of returning.
You return false after $msgp = '<span class="error"><b>Please enter correct postcode</b></span>'; therefor you do not continue to the form below... remove the returns from your code to be able to handle and show an error.
You are using return. Are you in a function() {} ? If so, all your variables are in function scope. You could do global $msgp; to make the variable accessible outside of the function.
If not... then you shouldn't use return.
Change php code to
<?php
if (isset($_POST['post'])) {
$post = intval($_POST["post"],0);
$words = array(2747,2750,2756,2760,2777);
$msgp = '<span class="error"><b>'.in_array($post,$words) ? "Please enter postcode" : "Please enter correct postcode" .'</b></span>';
}
There are a lot of things that can be simplified. For example codes as int array and using in_array() function. Return statement should be used to return something from method/function using it in global scope then execution of the current script file is ended. There is no need for it here. If there are more $words values you should consider using simple REGEX /[0-9]{4}/ and preg_match()
You want to display $msgp right? Use echo $msgp;. But you can return to nowhere in your code. (put it in a function).
Try this
<?php
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "<span class='error'><b>Please enter correct postcode</b></span>";
function check($post){
global $words;
$return=true;
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
//$return=true;
}
} else if(empty($post)) {
$return=false;
}
return $result;
}
$return=check($post);
if($return === true){
// echo you are right!
}
else {
echo $msgp;
}
Related
Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php
i'm trying to use strpos or some sort of method to search for the word 'validated' within a textarea known as $likes and it'll return an error if not found. I wasn't sure how to get around validating two conditions (the textfield 'likes' cannot be empty and it must contain the word 'validation') so I kind of threw another if statement which didn't work and now I am desperately plugging it into my html..
Here's my basic php validation, I removed all my other error handling and left the textarea one.
<?php
// define variables + initialize
$nameErr = $likesErr = $placesErr = $thingsErr = $emaiLErr = $shopErr = $emailyesErr= "";
$name = $likes = $places = $email = $emailyes = $shops = $things = "";
$shops = array();
$things = array();
$likesErr2 = "Your likes must include the word 'validated'!";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//textarea likes
if (empty($_POST["likes"])) {
$likesErr = "Please tell me what you like about hiking! :(";
}
else {
$likes = $_POST["likes"];
}
}
?>
Here is my attempted us at strpos: :(
<label>What do you like about hiking?</label><span class = "error">* <?php echo $likesErr;?></span><br>
<textarea rows="4" cols="50" input type="text" id="likes" name="likes">
<?php echo $likesErr2 (if ((strpos($likes, "validated") === false)?></textarea>
My current setup is resulting in a 500 error so I feel like I'm definetly doing something wrong with the php.
EDIT
I have updated my php to this:
//textfield likes
if (empty($_POST["likes"])) {
$likesErr = "Please tell me what you like about hiking! :(";
}
else if ((strpos($likes, "validated") === false){
$likesErr2 = "Please include the word 'validated' in your likes textarea!";
}
else {
$likes = $_POST["likes"];
}
and html portion
<div>
<br><br>
<label>What do you like about hiking?</label><span class = "error">* <?php echo $likesErr; echo $placesErr2;?></span><br>
<textarea rows="4" cols="50" id="likes" name="likes"></textarea>
<br><br>
</div>
And I'm still getting a 500 error ):
Here's an example use of strpos:
<?php
$str = 'Time spent with cats is never wasted.';
if (strpos($str, 'dog') === FALSE) {
echo 'no dog';
}
echo (strpos($str, 'dog') === FALSE) ? 'no dog' : 'hot dog!';
// Outputs: 'no dogno dog'
I have a textarea in my html named add-list. I want to get the value of the textarea per line break and then save it to my database. The problem is, when it saves the input to the database, the second and succeeding entries have a whitespace before the input.
Here is my function for getting the value:
public function add(){
$checker = false;
$names = $this->input->post('add-list');
if (strpos($names, "\n") == TRUE ) { //newline found
$names = nl2br(trim($this->input->post('add-list')));
$namesArray = explode('<br />', $names);
foreach($namesArray as $name) {
$checker = false;
$checker = $this->checkDatabase($name); //check if name already exists in database
if ($checker) {
echo "<script type='text/javascript'>alert('A site in your list already exists. Duplicate sites are not allowed.');</script>";
}
if (!$checker) {
$this->data_model->addCommunity($name);
}
}
$this->index();
redirect(base_url());
}
else if (strpos($names, "\n") == FALSE) {
$checker = $this->checkDatabase($names);
if ($checker) {
echo "<script type='text/javascript'>alert('" . $names . " already exists. Duplicate sites are not allowed.'); window.location.href='".base_url()."'</script>";
}
if (!$checker) {
$this->data_model->addCommunity($names);
$this->index();
redirect(base_url());
}
}
}
What I get in my database is like this:
firstName
secondName //there's a whitespace before 's'
Help me please!!!
Why do you go all the way through nl2br and then explode instead of using explode with a line break? But just use the search or a search engine, e.g. Explode PHP string by new line (long time no PHP, so I might not be quite right).
I'm using an old random() function for creating a validation code for an AJAX commenting system I found on the web (source code at LINK ).
The idea behind is pretty simple:
function Random()
{
$chars = "ABCDEFGHJKLMNPQRSTUVWZYZ23456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 4)
{
$num = rand() % 32;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_code = Random();
and then in the form, just before the SUBMIT button:
<label for="security_code">Enter this captcha code: <b><? echo $random_code; ?></b></label>
<input type="text" name="security_code" id="security_code" />
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>">
My AJAX commenting system uses something like this for checking if a field is blank (ie. if there are any errors):
$errors = array();
$data= array();
[...]
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}
if(!empty($errors)){
[...]
}
so I wrote this:
if(!($data['security_code'] = filter_input(INPUT_POST,'security_code',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['security_code'] = 'You did not enter the validation code.';
}
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
However when I click on the SUBMIT button after having inserted a random text in the validation code textfield ( test it by yourself at LINK ) I always get the "You entered the validation code incorrectly." message.
print_r($_POST) gives an empty array and then the script hangs after I click on submit:
Array
(
)
What am I missing? The original captcha code gets lost at some point in the validation process (the 3rd and 4th blocks of code).
Thanks in advance
After seeing your code here, I see that the static function validate doesn't know the variable $randomness! From your submit.php, you are making the following call:
$arr = array();
$validates = Comment::validate($arr);
The function validate doesn't know anything about the variable $randomness unless you pass such a thing to it - it is in a different scope.
Try modifying the above mentioned code as such:
$arr = array(); // no change here
$randomness = isset($_POST['randomness']) ? $_POST['randomness'] : '';
// Check for empty randomness before you validate it in Comment::validate
// so that you donot verify for '' == '' there.
$validates = Comment::validate($arr, $randomness);
And alter the validate function as follows:
public static function validate(&$arr, $randomness)
{
I know its not the elegant solution - that would require few more things that you'd learn well for yourself, this is just to show you the way...
Let me know how it goes.
instead of:
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>">
write:
<input name="randomness" type="hidden" id="randomness" value="<?php echo $random_code; ?>">
also instead of:
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
maybe this:
elseif($data['security_code'] != $randomness) {
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
also, from where $data get its values? $_POST, $_GET?
print_r() it and also the $_REQUEST to light up.
I'm trying to create a function that searches through the user input to see if they have
entered the name of a day. For some reason, this function only seems to return true if any two day names have been entered. This could be something simple, but I can't seem to figure it out.
Here is my code:
<?php
if(isset($_POST['query']))
{
$query=$_POST['query'];
$dow=array('monday','tuesday','wednesday','thursday',
'friday','saturday','sunday');
foreach($dow as $day)
{
if(stripos($query, $day)==FALSE)
{
}
else
{
echo"hurray";
}
}
}
?>
<html>
<form action="datefunctiontester.php" method="post">
<p>Search</p><input type="text" name="query">
<input type="submit">
</form>
</html>
=== not == see the stripos manual entry
You should use
if (stripos($query, $day) === FALSE){
and not
if (stripos($query, $day)==FALSE){
This is because, if the name is found in the starting of the query, it will return '0' because the position of first character will be 0 which is false. To check if it exists use === which checks the type and not the value.
Also, you can use the in_array function instead of for loop.
if (isset($_POST['query']))
{
$query = $_POST['query'];
$dow = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');
if (in_array($query, $dow)
{
echo"hurray";
}
}
Try this:
if (isset($_POST['query']) {
$dow = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');
if (in_array(trim(strtolower($_POST['query'])), $dow) echo"hurray";
}
There's no need to use stripos() in this case.
// Force lower case for comparisons
$query = strtolower( $_POST['query'] );
$dow = array('monday','tuesday','wednesday','thursday',
'friday','saturday','sunday');
$found = in_array($query, $dow, true);
if($found)
{
// do something
}