PHP Jump Redirect - php

I'm trying to redirect users based on the query string on a php file. I created a php file go.php and pasted following code,
<?php
if ($v = 'AAAAA') {$link = 'https://example1.com/';}
if ($v = 'BBBBB') {$link = 'https://exapmle2.com/';}
header( 'Location: $link' ) ;
exit();
?>
I thought I will be able to redirect user to example1.com with mydomain.com/go.php?v=AAAAA
But it's not working. The script redirects user to mydomain.com/$link
Can anyone help me achieve this? I'm using nginx as webserver with php 7.
Thanks in advance.

You should do something like this
$v = $_GET['V'];
if ($v == 'AAAAA'){
$link = 'https://example1.com/';
}elseif ($v == 'BBBBB') {
$link = 'https://exapmle2.com/';
}else{
$link = false; //you could output an error or put a default redirect in here instead. Then you wouldn't need the second if condition ( with a default redirection )
}
if( $link ){
header( "Location: $link" ) ;
exit();
}
A few things to note:
You are using assignment = not comparison == in your if condition. In the original both conditions will pass with the end value of $link being the last one ( although its set in the first, the second replace it ), the $v variable will be set to equal BBBBB as well, nither of which is what you want.
Variable interpolation ( automatic inserting the value ) only works when using double quotes not single quotes. " $link " vs ' $link ' the first will fill in the value of $link the second will literally be $link as a string.
You have no default value if $v is not equal to either condition, what happens?
You should use an if elseif because $v cannot be equal to both. In the case it equals the first condition the rest are skipped, performance wise its better but something like that it dosn't matter so much, it's just best practice and more readable.

When you want to user variable inside header function please use double quotes
header("Location: $link") ;
Also make sure that you are getting the value of url parameter using $v = $_GET['v'];

Related

multiple !isset() with OR conditions in php

if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
My Other Tries:
(!isset($_GET['new_quiz'] || $_GET['view_quiz'] || $_GET['alter_quiz']))
( ! ) Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in
C:\wamp\www\jainvidhya\subdomains\teacher\quiz.php on line 94
(!isset($_GET['new_quiz'],$_GET['view_quiz'],$_GET['alter_quiz']))
NO
You may find than inverting the logic makes the code easier to read, I also like to have a more positive idea of conditions as it can read easier (rather than several nots means no).
So this says if anyone of the items isset() then the answer is Yes...
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo "Yes";
}
else{ echo "No"; }
Note that I've changed the Yes and No branches of the if around.
You are probably looking for
if(!isset($_GET['new_quiz']) && !isset($_GET['view_quiz']) && !isset($_GET['alter_quiz'])){
echo "No";
}
else {
echo "Yes";
}
which will print Yes if none of new_quiz, view_quiz and alter_quiz are present in the URL. If this is not your desired outcome, please elaborate on your problem.
#paran you need to set a value for view_quiz=yes for example
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
and the url
index.php?new_quiz=yes
index.php?view_quiz=yes
index.php?alter_quiz=yes
All Will return true
isset()allows multiple params. If at least 1 param does not exist (or is NULL), isset() returns false. If all params exist, isset() return true.
So try this:
if( !isset( $_GET['new_quiz'], $_GET['view_quiz'], $_GET['alter_quiz']) ) {
First, to answer your question:
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
This is becaue this
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
checks if either one of your parameter is not set, which will always be the case as long as you are not setting all three parameter simultaneously like this:
index.php?alter_quiz&view_quiz&new_quiz
As #nigel-ren stated, you may wan't to change that logic to
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo 'Yes';
which checks if at least one parameter is set.
If you wan't to check if there is only one of the three parameters set, you would have to work with XOR (which is slightly more complicated)
$a = isset($_GET['new_quiz']);
$b = isset($_GET['view_quiz']);
$c = isset($_GET['alter_quiz']);
if( ($a xor $b xor $c) && !($a && $b && $c) ){
echo 'Yes';
(based on this answer: XOR of three values)
which would return true if one and only one of the three parameters is set.
But - and this is just an assumption, please correct me if I'm wrong - I think what you are trying to achieve are three different pages (one for creating a quiz, one for viewing it and one for editing it). Therefore, you will likely run into a problem with your current setup. For example: What would happen if a user calls the page with multiple parameters, like
index.php?alter_quiz&view_quiz
Would you show both pages? Would you ignore one parameter? I would recommend to work with a single parameter to avoid this problem in the first place. For example site which can take the values alter_quiz, view_quiz or new_quiz. E.g.:
index.php?site=alter_quiz
Then you can work like this:
// check if site is set before getting its value
$site = array_key_exists( 'site', $_GET ) ? $_GET['site'] : NULL;
// if it's not set e.g. index.php without parameters is called
if( is_null($site) ){
// show the start page or something
}else{
$allowed_sites = ['new_quiz', 'view_quiz', 'alter_quiz'];
// never trust user input, check if
// site is an allowed value
if( !in_array($site, $allowed_sites, true) ){
die('404 - This site is no available');
}
// here you can do whatever your site should do
// e.g. include another php script which contains
// your site
include('path/to/your/site-' . $site . '.php');
// or echo yes
echo 'Yes';
}

storing php variable in session and calling into pagination link

At the moment i'm calling the following via GET
$RimWidth = $_GET['RimWidth'];
$TyreWidth = $_GET['TyreWidth'];
$Aspect = $_GET['Aspect'];
$TyreDia = $_GET['TyreDia'];
$TyreMan = $_GET['TyreMan'];
However in my paginiation, after page 1 it looses the variables and doesn't work. I understand i need to store them in the session. How do i do this as i've seen a few way of doing it and can't get it to work and how do i place them onto the end of the pagination links which look like this
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
thanks
If you want to just repeat the $_GET values, you can make a function to do that:
//A function to get and repeat arguments in every link
function repeatvars(){
if(isset($_GET) && empty($_GET) == false){
$variables = "?";
$arraycount = count($_GET) - 1;
$count = 0;
foreach ($_GET as $var => $value){
if(empty($value) == true){
$variables .= $var;
}else{
$variables .= $var."=".$value;
}
if ($count !== $arraycount){
$variables .= "&";
}
$count++;
}
return $variables;
}}
//Example
echo 'Next Page (Link: nextpage.php'.repeatvars().')';
You need this at the top of your PHP pages if using sessions:
session_start();
Then, you should really do this for each one:
$RimWidth = isset($_GET['RimWidth']) ? trim(strip_tags($_GET['RimWidth'])) : null;
$_SESSION['RimWidth'] = $RimWidth;
// and so on
trim() and strip_tags() removes any unwanted white-space and removes any malicious script tags being sent to your page. Never trust any POST, GET or SESSION data. They can all be compromised by hackers. If RimWidth always returns an integer, then put (int) before, like this:
(int) $RimWidth = isset($_GET['RimWidth']).............
You shouldn't need to add the session variables to the end of your pagination links, they're session variables and will be available on the next page, or any other page.
To call them on another page, do this:
echo $_SESSION['RimWidth'];

working with 3 $_GET values

I have a problem with $_GET array. On my page a value comes from URL like this.
http://localhost/search.php?subject=Mathematics
I check this $_GET value something like this..
// Check for a valid keyword from search input:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
foreach ( $_GET AS $key => $subject) {
$searchKey = $key;
$searchKeyword = '%'.$subject.'%';
}
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Now its working for me. But my problem is I am using another two variables to pass through URL on same page to filter my database values.
echo '<li>Tutor</li>
<li>Institute</li>';
This two links I used to filter my database values (clicking on this link).
$tutor = isset($_GET['institute']) ? '0' : '1';
$institute = isset($_GET['tutor']) ? '0' : '1';
My problem is when I am trying filter database result clicking on the above link its always going this code instead of displaying filtered result.
} else { // No valid keyword, kill the script.
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
Can anybody tell me how I use this 3 $_GET values.
Why not just add a clause in the else:
elseif(!isset($_GET['institute']) && !isset($_GET['tutor']))
{
echo 'This page has been accessed in error.';
include ('includes/footer.html');
exit();
}
You need to make sure the url looks like this:
http://localhost/search.php?subject=Mathematics&tutor=tutorName&institute=instituteName
A ? denotes the beginning of the URL parameters, an & marks the separation between url parameters
Your problem doesn't seem to be, that you're running into the else loop (or better said: not the only problem). It looks like your first parameter gets lost with the second link. I think, the second link should react like some kind of extended search filter, that shoud be applied to the recently displayed content, or am I totally wrong at understanding you?
Perhaps this could solve your problem for creating the follow-up URLs.
$params = array();
foreach($_GET as $key => $value) {
$params[] = '&'.$key.'='.$value;
}
$url1 = '?tutor=link'.implode('', $params);
$url2 = '?institute=link'.implode('', $params);
And when you output the links:
echo '<li>Tutor</li>
<li>Institute</li>';
Your problem is that you are only checking the $_GET['subject'] variable, which is no being passed in. You could do this in a few ways, all resulting in changing:
if ( (isset($_GET['subject'])) && (is_string ($_GET['subject'])) ) { // From SESSION
1) include all variables in the conditional string:
if ( ((isset($_GET['subject'])) && (is_string ($_GET['subject']))) || ((isset($_GET['institute'])) && (is_string ($_GET['institute']))) || ((isset($_GET['tutor'])) && (is_string ($_GET['tutor']))) ) {
2) Pass in searchKey=1 or something in all your links and use:
if ( isset($_GET['searchKey']) ) { // From SESSION
Revised links:
echo '<li>Tutor</li>
<li>Institute</li>';
If you are looking to pass in more than one variable at once, you will need to put the search keys into an array.

Php pages dependent on query string but what if there's no parameter?

I am creating pages that are dependent on a query in the url (eg europe.php?country=france). I am aware that it will be useful to re-write theses as europe.php/france with htaccess for SEO etc but what if that page is accessed without the query string?
I am using php to $_GET the query, so if I access the page without the query I get 'var=;' ie, it is empty (and retrieves an error). I'm trying to use an if statement to check if the $_GET retrieves nothing but am unsure if this is the right thing to do.
So: how do I check for an un-retrieved var so I can set a default?
Or: am I going about this the wrong way?
If you know the index into $_GET, use isset():
$country = 'default';
if( isset( $_GET['country'])) {
$country = $_GET['country'];
}
This will only test if the country parameter was passed, but it could have been set to an empty string. If this is invalid input, you can combine the check using empty():
$country = 'default';
if( isset( $_GET['country']) && !empty( $_GET['country'])) {
$country = $_GET['country'];
}
You can condense this into one line and save the result to a variable $country using the ternary operator, like so:
$country = (isset( $_GET['country']) && !empty( $_GET['country'])) ? $_GET['country'] : 'default';
Finally, you can check if you got absolutely no $_GET parameters by calling count() on $_GET:
if( count( $_GET) == 0) {
die( "No parameters - Invalid input!");
}
since isset() really tests for "NOT NULL", you should use empty() to test if an empty string was given:
if (empty($_GET['country'])) {
$_GET['country'] = "default";
}
that is, unless you expect 0 to be a valid input, in that case, you'd have to check with isset and make sure the string has at least one character:
if (!isset($_GET['country']) || !strlen($_GET['country'])) {
$_GET['country'] = "default";
}
which can be optimized into
if (!isset($_GET['country']) || !isset($_GET['country'][0])) {
$_GET['country'] = "default";
}
try using something like this:
$var = ( isset($_GET['var']) ? $_GET['var'] : 'default value' )
Try doing this
if(isset($_GET['your_variable'])) {
$variable = $_GET['your_variable'];
} else {
$variable = "not set";
}
That will set the variable if it is set in your URL - or it can set your variable to some other value if it is not set in the URL
Running a check at the start of the page to see if var is set is fine to do. If it's empty, you can redirect using something like:
header("HTTP/1.0 404 Not Found");
header('Location:YOUR PAGE NOT FOUND PAGE');
exit();
On a side note, if you're using data from $_GET, you need to make sure that this data is validated & cleaned to prevent against all sorts of security intrusions, such as XSS and, if you use a database, MYSQL injection. Running a test at the start of the page to check if it's empty can be just the start - you can also make sure that the data is something you'd expect (say, check it's alphanumeric). After, with $_GET data, anyone could fill the URL bar with whatever they like and potentially damage your website.
Hope this has helped!

Simple if() not working as expected

I am sure that I am simply overlooking something, and I spent a few days working on this and cant seem to figure it out.
after logging in on the previous page I get the username and password,
$username = mysql_escape_string($_POST['adminusername']);
$password = mysql_escape_string($_POST['adminpassword']);
and then I go to the database to pull the username and password from the database,
$sql = "SELECT username, password FROM `weaponsadmin`";
$rows = $db->query($sql); while ($record = $db->fetch_array($rows)) {
now here is the part that is confusing me, if i have the following, no matter what I use for the username or password, it will NOT allow for me to login,
if ( ($record[username]==$username) && ($record[password]==$adminpassword) ){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $adminusername;
header( "Location: admin.php" ) ;
}
else {
header( "Location: index.php?login=error" ) ;
}
however if I use the following, it will allow me to login in if the username is correct, but it allows for me to input anything for password and it works,
$adminusername = $record[username];
$adminpassword = $record[password];
if ( ($adminusername==$username) && ($adminpassword==$adminpassword) ) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $adminusername;
header( "Location: admin.php" ) ;
}
else {
header( "Location: index.php?login=error" ) ;
}
So in summary for some reason the && part doesn't seem to work correctly and if somebody could help me with the code and let me know where my code could be improved for better security and how to make this work correctly, thanks
what is the point here $adminpassword==$adminpassword :
i think it should be:
if ( ($adminusername==$username) && ($adminpassword==$password) ){
$record[username] should be $record["username"] (and so on). indexes are strings or int
You're using arrays wrong.
You expect: $record[username]; //retrieve contains of key "username"
What really happens:
$record[username];
/*
retrieves a key in the record array under the key which is a value of a
constant named "username" (if it's defined) and an empty string with
E_WARNING if it's not.
*/
You need to either single or double quote the index names, for example $records['username'].
However, you can use unquoted array indexes inside of a string (and these will work as you expect) -> $someString = "Blahblahblah, ergo $record[username] is a donkey.";.
You can use === instead of ==. Read this.
strcmp() isn't necesarry here.
To add to Michael's answer, the reason why you should not use == for string comparison (hopefully this will help you navigate similar difficulties in the future) is that when you call a simple == on an object (such as a string, or really anything other than an int, double, float, char, long, short, or boolean, in most languages), what you're really comparing is the address in memory of each object, that is, the pointer value.
This is useful if you want to know if two variables are referencing the same object, but not so useful if you want to know if two objects are identical. So this is true:
$string_a = $some_string;
$string_b = $some_string;
$string_a == $string_b;
but this is not:
$string_a = getUserInput(); # user types in "hello"
$string_b = getUserInput(); # user types in "hello"
$string_a == $string_b;
and this may be true depending on the language you're in, if it stores string literals in memory independently of the user-defined variables to which they are attached:
$string_a = "hello";
$string_b = "hello";
$string_a = $string_b;
So unless you're checking to see if two objects are in fact the same object, and not merely identical, use, as those before me suggested, a function to compare the two. Such a function usually goes down to the level of primitive types, which can be compared using == as you would expect, and returns true if all of those comparisons do.
Don't use == for string comparison. Instead, use strcmp() or === to match strings.

Categories