How to combine AND and OR operators in a if statement? - php

I have the following strings that contains parts of a domain as string.
$scheme="http";
$host="example.com";
$filename="demo.php";
$request_uri="/folder/demo.php";
$host and $filename variables one of them is optional.
I am using the following code to check if strings contain the correct value, print the successful messege ,else print the error message
if($scheme ="http" OR $host ="example.com" & $filename ="demo.php" & $request_uri ="/folder/demo.php")
{echo "Sucessful";}
else
{echo "Fail";}
It doesnt work as expected, and I am getting "Successful" everytime . I think the AND oprator is being ignored in the if statement.
Any Idea?

if( $scheme == "http"
&& ($host == "example.com" || $filename == "demo.php")
&& $request_uri == "/folder/demo.php"
) {
echo "Sucessful";
} else {
echo "Fail";
}
&& and || are PHP's operators for AND and OR. Also = assigns a value to a variable, not comparing for equality. Use == or === for comparing.
Also, it seemed that your written statement of requirements did not match your code ... so I changed the logic a little and added () to group the logic. From the written it sounds like the $scheme AND $request_uri test were required and either $host or $filename were required. Your code didn't seem to match that. If I misunderstood your written requirment, change the && and || and () around as you require. Note that breaking long boolean expressions into multiple lines and the use of () to group logic often helps with getting it right.

Related

Grab portion of URL with PHP

I have the following PHP to grab a part of the URL.
I have a URL www.mysite.com/my-team2.php and it echoes my team instead of my team2.
$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos(strtolower($page),'my-team') !== false) {
echo 'my team';
} elseif (strpos(strtolower($page),'my-team2') !== false) {
echo 'my team2';
}
Why is this?
this is because it is finding the first instance first, the else if will never occur, what you should do is swap them
if (strpos(strtolower($page),'my-team2') !== false) {
echo 'my team2';
} elseif (strpos(strtolower($page),'my-team') !== false) {
echo 'my team';
}
so basically what it was doing without swapping them was finding the text 'my-team'
since the text 'my-team'is part of the text 'my-team2', it would always trigger the if without ever seeing the else if, because the if would always == TRUE.
by swapping them and putting the 2 first, 'my-team2' it will have to find that first, thus if the 2 is not in it, then the else if will trigger
That's because my-team is contained in my-team2, so the first test is already true.
Either reverse them (rather simplistic) or use another approach, such as comparing the whole string or using a regular expression match.
Because "my-team" is substring of "my-team2". It's better to use regular expressions on these kind of situtaions.
You should put the most specific match in the first
echo strpos(strtolower($page),'my-team2') !== false ? 'my-team2' : strpos(strtolower($page),'my-team2') !== false ? 'my-team' : '';

IF with multiple conditions not working

I am trying to create an if statement with multiple conditions but it won't work and perhaps it is my syntax.
I have two post variables, which both give me the value fine elsewhere on my page. They are:
$_POST['text']
$_POST['rating'] //can be G, PG or R
What I am trying to do is make my word filter code work only if the rating equals "G"
What is currently happening though is that the filter is flagging a bad word regardless of the rating and ignoring my IF rating = G part.
if (isset($_POST['text']) and $_POST['rating'] = "G") {
//give warning if bad words are used
}
<?php
if (isset($_POST['text']) && $_POST['rating'] =="G") {
//give warning if bad words are used
}?>
use it like this
You may also use the symbol version of the syntax.
&& for and
|| for or
Also, = does not mean equals in an if statement. That is the syntax for setting a variable.
You would say == (equals to).
To say "not equals" you would use != or !=
if (isset($_POST['text']) && $_POST['rating'] == "G") {
//give warning if bad words are used
}

PHP if condition doesn't work for urls matching

I am trying to match two URLs but it seems doesn't work. I have tried works fine if I put manually.
Here is the code:
$referby = $_SERVER['HTTP_REFERER'];
$link1="http://domain.com/admin/ajax/passcodev.php?order_id=".$orderid;
$link2="http://www.domain.com/admin/ajax/passcodev.php?order_id=".$orderid;
if($referby<>$link1 || $referby<>$link2)
{
header('Location:passcodev.php?order_id='.$orderid);
}
I have no idea where I am doing mistake.
if($referby<>$link1 || $referby<>$link2) means if $referby does not match $link1 or $link2, proceed. Since it can't match both it always evaluates to true.
You need to use && (and):
if($referby != $link1 && $referby != $link2)

Custom URL routing with PHP and regex

I'm trying to create a very simple URL routing, and my thought process was this:
First check all static URLs
Then check database URLs
Then return 404 if neither exists
The static URLs are easy to do of course, but I'm trying to figure out the best way to do dynamic ones. I would prefer not to have to set a static prefix, despite knowing that it would make this a lot easier to code.
This is what I currently have:
$requestURL = $_SERVER['REQUEST_URI'];
if ($requestURL == '/') {
// do stuff for the homepage
}
elseif ($requestURL == '/register') {
// do stuff for registration
}
// should match just "/some-unique-url-here"
elseif (preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) {
// query database for that url variable
}
// should match "/some-unique-url/and-another-unique-url"
elseif (preg_match("(^\/[A-Za-z0-9\-]+\/[A-Za-z0-9\-]+)/",$requestURL)) {
// query database for first and second variable
}
else {
// 404 stuff
}
My problem is that if I have "/register" URI, it will match the second elseif statement as well as the regex statement. But I want to avoid having to specifically exclude each static URL from regex statement, such as this:
// should match just "/some-unique-url-here"
elseif ((preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) &&
($requestURL !== '/register') &&
($requestURL !== '/')) {
// query database for that url variable
}
What's the easiest way to solve this problem? I'll probably have like 15-20 static URLs, so specifically excluding all of them would be very clunky.
Your problem does not exist. If the first elseif ($requestURL == '/register') matches, all subsequent elseifs on the same level won't get evaluated.
You're already doing it right, just make sure you do the string comparisons (==) first.
On another note, don't reinvent the wheel.
https://github.com/bramus/router
http://toroweb.org/
http://zaphpa.org/

Displaying code only for certain countries

So I have an affiliate program that's lately been getting a lot of bad leads from countries we don't service, which we tell affiliates will be voided. Anyways, this is going to cause our reversal rate to be through the roof. So I want to do something about it.
So I want to use geoip, which gets me the stuff as a 2 letter country code.
<?php
$output = shell_exec('geoip-lookup '.$_SERVER['REMOTE_ADDR']);
?>
So how do I put that together?
Would this be correct?
<?php
$output = shell_exec('geoip-lookup '.$_SERVER['REMOTE_ADDR']);
if($_SESSION['check']!=1) && ($output=='US' || $output=='AU' || $output=='GB' || $output=='CA')
{
$submission = $_POST['submission_id'];
$_SESSION['check']=1;
echo 'insert pixel';
}
?>
You'll want to verify $output is what you expect (i.e. a string - var_dump($output)).
However, provided it is, you'll need to quote your country codes to do a string comparison. Also, as noted by heximal, be sure to use == for comparison. Otherwise, it's an assignment.
if ($_SESSION['check'] != 1 && ($output == 'US' || $output == 'AU' ...)) {
Otherwise, the rest of you code appears correct (without knowing your exact logic).
I am not familiar with "geoip-lookup" but I have "geoiplookup" working in my Ubuntu shell. Hopefully I can assume they are the same?
Putting $_SERVER values into a shell command has the potential for disaster, because they can be spoofed, so be careful with that.
Try the following:
// Make sure that the remote address is an IP and not something harmful, like "1.1.1.1; rm ../ -rf".
$found = preg_match('/^(?:\d{1,3}\.){3}\d{1,3}$/', $_SERVER['REMOTE_ADDR']);
if($found)
{
$command = escapeshellcmd('geoiplookup '.escapeshellarg($_SERVER['REMOTE_ADDR']));
$output = shell_exec($command);
if(($_SESSION['check']!=1) && (strpos($output,'US')!==false || strpos($output,'AU')!==false || strpos($output,'GB')!==false || strpos($output,'CA')!==false))
{
$submission = $_POST['submission_id'];
$_SESSION['check'] = 1;
echo 'insert pixel';
}
}
Be careful with $output=US
if you want to compare two operands you should use == operator

Categories