Function returning boolean only returns false - php

I've a simple function that apprently puts me up with a lot of trouble. The function is:
function valid_mail($email) {
$atpointers = strstr($email, "#");
$spacepointers = count(explode(" ", $email));
$dotpointers = strstr($email, ".");
$ltpointers = strstr($email, "<");
$gtpointers = strstr($email, ">");
$illegalpts = $ltpointers + $gtpointers;
if($atpointers >= 2 || $dotpointers == 0 || strlen($email) <= 6 || $illegalpts >= 1) { return false; } else { return true; }
}
And calling it in the context:
if(valid_mail($email) === false) { // Code } else { // Code }
The problem is apparently it only returns false. Any ideas for why this happens ?

strstr returns a substr of the string being checked, not a length. Use strpos instead.

Related

preg_match - For sure there is a better way to search for these characters

So, I want to check the users-input, if it contains some of these characters:
" ' < >
I hope someone can show me a better way with less code
Thanks!
I used preg_match, but i just managed it with 4 nested if's.
/*Checks if the given value is valid*/
private function checkValidInput($input)
{
/*If there is no " */
if(preg_match('/"/', $input) == false)
{
/*If there is no ' */
if(preg_match("/'/", $input) == false)
{
/*If there is no <*/
if(preg_match("/</", $input) == false)
{
/*If there is no >*/
if(preg_match("/>/", $input) == false)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
You could create a regex class
preg_match('#["\'<>]#', $input);
Edit:
If you need to check for all characters then use strpos() with for loop
function checkInput($val) {
$contains = true;
$required = "<>a";
for($i = 0, $count = strlen($required); $i < $count ; ++$i) {
$contains = $contains && false !== strpos($val, $required[$i]);
}
return $contains;
}
var_dump(checkInput('abcd<>a')); // true
var_dump(checkInput('abcd>a')); // false, doesn't contain <

PHP Zero integer is being evaluated as false

As the title says, PHP seems to be evaluating the integer value 0 as false.
Take for example this snippet:
http://sandbox.onlinephpfunctions.com/code/13d885fb68359a3154999c2ef85db7c913c49bc5
<?php
if($exists = checkDup()){
echo $exits;
}
else{
echo "error!";
}
function checkDup ($foo = 'blah', $bar = 'blah'){
if ($foo == $bar) return (int) 0;
return false;
}
As you can see, despite casting the reply as an int PHP parsing the return as false which in incorrect.
PHP is evaluating a lot to false ;)
For example null, '', 0
You have to include a type check as well, you can do so by using === or !==
$exists = checkDup();
if($exists !== false){
echo $exits;
}
else{
echo "error!";
}
function checkDup ($foo = 'blah', $bar = 'blah'){
if ($foo == $bar) return 0;
return false;
}
You should use if($exists = checkDup() !== false)
0 == false; //true
0 === false; //false
When you don't specify the a boolean expression in the if, it will execute the == operator

Shortening an IPv6 address ending in 0's via PHP

I'm using an IPv6 class found on GitHub to do some IP manipulation but I noticed that there is an issue with shortening certain address, typically ending in 0.
When I enter the address 2001::6dcd:8c74:0:0:0:0, it results in 2001::6dcd:8c74::::.
$address = '2001::6dcd:8c74:0:0:0:0';
// Check to see if address is already compacted
if (strpos($address, '::') === FALSE) {
$parts = explode(':', $address);
$new_parts = array();
$ignore = FALSE;
$done = FALSE;
for ($i = 0; $i < count($parts); $i++) {
if (intval(hexdec($parts[$i])) === 0 && $ignore == FALSE && $done == FALSE) {
$ignore = TRUE;
$new_parts[] = '';
if ($i == 0) {
$new_parts = '';
}
} else if (intval(hexdec($parts[$i])) === 0 && $ignore == TRUE && $done == FALSE) {
continue;
} else if (intval(hexdec($parts[$i])) !== 0 && $ignore == TRUE) {
$done = TRUE;
$ignore = FALSE;
$new_parts[] = $parts[$i];
} else {
$new_parts[] = $parts[$i];
}
}
// Glue everything back together
$address = implode(':', $new_parts);
}
// Remove the leading 0's
$new_address = preg_replace("/:0{1,3}/", ":", $address);
// $this->compact = $new_address;
// return $this->compact;
echo $new_address; // Outputs: 2001::6dcd:8c74::::
To compress ipv6 addresses, use php functions inet_ntop and inet_pton to do the formatting, by converting the ipv6 to binary and back.
Sample ipv6 - 2001::6dcd:8c74:0:0:0:0
Test usage:
echo inet_ntop(inet_pton('2001::6dcd:8c74:0:0:0:0'));
Output : 2001:0:6dcd:8c74::
Without that problem line at the bottom you get 2001::6dcd:8c74:0:0:0:0.
Now, before the leading 0's are all replaced, the function checks to see if the address ends in :0 before removing all leading 0's.
if (substr($address, -2) != ':0') {
$new_address = preg_replace("/:0{1,3}/", ":", $address);
} else {
$new_address = $address;
}
Another check is added to catch other possible valid IPv6 addresses from being malformed.
if (isset($new_parts)) {
if (count($new_parts) < 8 && array_pop($new_parts) == '') {
$new_address .= ':0';
}
}
The new full function looks like this:
// Check to see if address is already compacted
if (strpos($address, '::') === FALSE) {
$parts = explode(':', $address);
$new_parts = array();
$ignore = FALSE;
$done = FALSE;
for ($i = 0; $i < count($parts); $i++) {
if (intval(hexdec($parts[$i])) === 0 && $ignore == FALSE && $done == FALSE) {
$ignore = TRUE;
$new_parts[] = '';
if ($i == 0) {
$new_parts = '';
}
} else if (intval(hexdec($parts[$i])) === 0 && $ignore == TRUE && $done == FALSE) {
continue;
} else if (intval(hexdec($parts[$i])) !== 0 && $ignore == TRUE) {
$done = TRUE;
$ignore = FALSE;
$new_parts[] = $parts[$i];
} else {
$new_parts[] = $parts[$i];
}
}
// Glue everything back together
$address = implode(':', $new_parts);
}
// Check to see if this ends in a shortened :0 before replacing all
// leading 0's
if (substr($address, -2) != ':0') {
// Remove the leading 0's
$new_address = preg_replace("/:0{1,3}/", ":", $address);
} else {
$new_address = $address;
}
// Since new_parts isn't always set, check to see if it's set before
// trying to fix possibly broken shortened addresses ending in 0.
// (Ex: Trying to shorten 2001:19f0::0 will result in unset array)
if (isset($new_parts)) {
// Some addresses (Ex: starting addresses for a range) can end in
// all 0's resulting in the last value in the new parts array to be
// an empty string. Catch that case here and add the remaining :0
// for a complete shortened address.
if (count($new_parts) < 8 && array_pop($new_parts) == '') {
$new_address .= ':0';
}
}
// $this->compact = $new_address;
// return $this->compact;
echo $new_address; // Outputs: 2001::6dcd:8c74:0:0:0:0
It's not the cleanest solution and could possibly have holes in its logic depending on what the address is. If I find any other issues with it I will update this question/answer.

Combining These Two Variables

I'm trying to combine these two:
$test1 = (isset($_GET["var1"]) && (isset($_GET["var2"]);
$test2 = test = !(strpos($_GET['var1'], '{') !== FALSE || strpos($_GET['var1'], '}') !== FALSE );
This is what I tried thats giving me an unexpected ; parse error parse error:
$test1 = (isset($_GET["var1"]) &&
!(strpos($_GET['var1'], '{') !== FALSE ||
strpos($_GET['var1'], '}') !== FALSE ) ||
(isset($_GET["var2"]) &&
!(strpos($_GET['var2'], '{') !== FALSE ||
strpos($_GET['var2'], '}') !== FALSE );
EDIT
what $test1 does is checks to see if var1 and var2 are in the url
what $test2 does is checks to see if var1= or var2= has { or } in the string. I'm just trying to put this all into 1 variable
Bad parenthesis on line 1, and I assume you want that to be '$test', not 'test' on line 2:
<?php
$test1 = isset($_GET['var1']) && isset($_GET['var2']);
$test2 = $test = !(strpos($_GET['var1'], '{') !== FALSE || strpos($_GET['var1'], '}') !== FALSE );
This code works:
$_GET['var1'] = "vvv";
$_GET['var2'] = "ddd";
$test1 = (isset($_GET["var1"]) && !(strpos($_GET['var1'], '{') !== FALSE || strpos($_GET['var1'], '}') !== FALSE ) ||
(isset($_GET["var2"]) && !(strpos($_GET['var2'], '{') !== FALSE || strpos($_GET['var2'], '}') !== FALSE )));
print $test1;
In short this is a mess. Don't do that you'll never recognize what it does after 6 month or so.
This is a little verbose, but may change the way you're thinking about this.
$test1 will have a truthy value if both vars are set. test2 will have a truthy value if the either { or } exists in the string.
function testBrackets($string)
{
$firstBracket = strpos($string, '{');
$secondBracket = strpos($string, '}');
if ($firstBracket == false and $secondBracket == false)
{
return false;
}
return true;
}
if (isset($_GET['var1']) and isset($_GET['var2']))
{
$test1 = true;
}
$test2 = 0;
if (isset($_GET['var1']))
{
$test2 = $test2 + testBrackets($_GET['var1']);
}
if (isset($_GET['var2']))
{
$test2 = $test2 + testBrackets($_GET['var2']);
}

Preg_match if a string beginns with "00"{number} or "+"{number}

I have to test if a string begins with 00 or with +.
pseudocode:
Say I have the string **0090** or **+41**
if the string begins with **0090** return true,
elseif string begins with **+90** replace the **+** with **00**
else return false
The last two digits can be from 0-9.
How do I do that in php?
You can try:
function check(&$input) { // takes the input by reference.
if(preg_match('#^00\d{2}#',$input)) { // input begins with "00"
return true;
} elseif(preg_match('#^\+\d{2}#',$input)) { // input begins with "+"
$input = preg_replace('#^\+#','00',$input); // replace + with 00.
return true;
}else {
return false;
}
}
if (substr($str, 0, 2) === '00')
{
return true;
}
elseif ($str[0] === '+')
{
$str = '00'.substr($str, 1);
return true;
}
else
{
return false;
}
The middle condition won't do anything though, unless $str is a reference.
if (substr($theString, 0, 4) === '0090') {
return true;
} else if (substr($theString, 0, 3) === '+90') {
$theString = '00' . substr($theString, 1);
return true;
} else
return false;

Categories