Help with PHP if / else statement - php

On my site, forms are brought in via AJAX and checked against a sessionid. I know this is not optimal, but it's working for us. If the referrer doesn't have the session ID they are redirected back to "anotherpage". I need to allow some outside URL's access the form directly.
we set the sessionid on the page with the link to the form.
Here is what we have now on the form page:
<?php
$code = $_GET['sessionid'];
if(strcmp( $code , 'XXXXX' ) != 0) {
header("Location: http://www.domain.com/anotherpage.php");
}
?>
I need to allow some outside domains direct access to the form page and am having issues with this:
(I'm putting it above the head tag on the form page)
<?php
$code = $_GET['sessionid'];
$referrer = $_SERVER['HTTP_REFERER'];
if(strcmp( $code , 'XXXXX' ) !=0) {
header("Location: http://www.domain.com/anotherpage.php");
} else {
if (preg_match("/site1.com/",$referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
}
}
?>
this still bounces me back to "anotherpage.php" any ideas?
********EDIT*******
thx for the help, it works ad I requested. Now I see what I asked wasn't entirely correct. This appends the URL with =sessionid?=XXXXX. This isn't an issue on my site because I'm loading the content with .jquery .load so the URL doesn't change. I don't want the sessionid to be visible, and now it is. Can I either a) "trim" the url somehow or b) separate the two functions so they are exclusive?

if(strcmp( $code , 'XXXXX' ) !=0) {
if (preg_match("/site1.com/",$referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
} else {
header("Location: http://www.domain.com/anotherpage.php");
}
}

As I read your post, you want anyone from the preg_match to get the desired page regardless of sessionID status, so you don't want to test sessionID first.
Start the if block with the preg_match test.

Your first if is checking to see if they don't have the $code and redirecting them. This will always be the case. You should probably check the $referrer first and then do the $code check.

Try reverse if with else
<?php
$code = $_GET['sessionid'];
$referrer = $_SERVER['HTTP_REFERER'];
if (preg_match("/site1.com/", $referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
} else if (strcmp( $code , 'XXXXX' ) != 0) {
header("Location: http://www.domain.com/anotherpage.php");
}
?>

If I'm not misunderstanding this, the problem is in the order in which you are checking things.
If you want to allow some referrers to access the site even if they don't have the session id, you have to check for that before checking for the session id. Otherwise, they will end up being treated just like everyone else.
You can either switch the order of the conditions (first check for the referrer and then check fo the session id) or check for the referrer inside the branch in which you already know the session id is not valid.

The issue could be in your regex, it should be:
if (preg_match("/site1\.com/",$referrer))
notice escaping the dot (.)

Related

restrict page without variable , only open if coming from a page or site

page-one.php code
<?php
//page-one.php
session_start();
$_SESSION['page_one'] = time();
?>
hello this is page 1 go to page 2
Page 2
page-two.php code
<?php
//page-two.php
session_start();
//Check to see if session variable exists.
if(!isset($_SESSION['page_one'])){
//Does not exist. Redirect user back to page-one.php
header('Location: 404.php');
exit;
} ?>
this is page 2
Works perfect but I have 2 questions:
what if i delete page-one bcz i want to show page 2 to all vistors who are coming on page 2 by clicking a link
or what if user is coming on page-two through google.com , in this case how page-two will pass page_one variable
This doesn't make much sense, but for your specific questions:
if(!isset($_SESSION['page_one']) &&
strpos($_SERVER['HTTP_REFERER'], 'google') === false &&
strpos($_SERVER['HTTP_X_FORWARDED_FOR'], 'google') === false &&
file_exists('page-one.php')
{
header('Location: 404.php');
exit;
}
Check if the session variable is not set
Check if HTTP_REFERER is not google
Check if HTTP_X_FORWARDED_FOR is not google
Check if page-one.php has not been deleted
$_SERVER['HTTP_REFERER'] is not reliable as it may be wrong, a proxy server or empty and $_SERVER['HTTP_X_FORWARDED_FOR'] is not guaranteed to be set or reliable.
With the previous caveats in mind, you can see if someone came from another site by checking:
if(!isset($_SESSION['page_one'] &&
!isset($_SERVER['HTTP_REFERER'] &&
!isset($_SERVER['HTTP_X_FORWARDED_FOR'])
{
header('Location: 404.php');
exit;
}
If you add a get parameter to all links then it's easier:
Page 2
Then:
if(!isset($_SESSION['page_one'] && !isset($_GET['link'))
{
header('Location: 404.php');
exit;
}

Set referer on first visit to site

I have a site where the phone number in the header file needs to change depending on the referrer. If someone comes to the site via google, for example, the phone number is different that if they came directly to the site.
I have it working, except for when the user goes to a different page on the site. The code checks the referrer and changes the number to the direct number.
What I want is for the number to be set by the referrer the first time the user visits the site, and for it not to change. I imagine cookies or sessions are the way to go here, I"m just not sure how the code should be structured.
if (!empty($_SERVER['HTTP_REFERER'])) //user has come via search engine or a page within our site
{
$referer = $_SERVER['HTTP_REFERER'];
if (strpos($referer,'google') !== false) {
$callin_number='1-444-444-4444';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
elseif (strpos($referer,'bing') !== false) {
$callin_number='1-111-111-1111';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
else {
$callin_number='1-222-222-2222';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
}
else { //user has come directly to site
$callin_number='1-333-333-3333';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
If you want to use session or cookie:
semi-pseudo:
<?php
session_start();
if ( !isset( $_SESSION['referer'] ) )
{
put your code here, and put whatever you need to session:
$_SESSION['referer'] = ...
$_SESSION['dialin'] = ....
}
and use $_SESSION['referer etc'] in your code instead of $referer etc.
$_SESSION['referer etc'] will be available on the next page load,
the IF condition above will be false on the next page load.
Cookies are just a bit different: http://php.net/manual/en/function.setcookie.php

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

How do I redirect to referring page/url after successful login?

I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. Every page on my website requires a login, and so users are redirected to a login page on page load. At the top of each page then I have:
<?
require("log.php");
include_once("config.php");
include_once("functions.php");
?>
This redirects the user to log.php (with new code added):
<?
session_name("MyLogin");
session_start();
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");
if (!$q_user) {
die(mysql_error());
}
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
The login form is contained in login.php. The code for login.pho relevant to the PHP/log.php is:
<?
session_start();
if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>
and
<form name="login_form" id="form" method="post" action="log.php?action=login">
The answer that I came across stated that I should add:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add:
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
to my login page, and use the following URL for redirect on successful login:
header("Location: http://example.com/$url"); // perform correct redirect.
I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php.
I have tried adding it to both, but the login page is just looping once I have entered the username and password.
I wonder if someone could help me get this working?
Thanks,
Nick
It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim.
SCENARIO 1:
If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? Please do note, that the code below, is the code you've posted.
$db = mysql_select_db(""); //put your database name in here
SCENARIO 2:
The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it?
if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement
SCENARIO 3:
If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history.
if(!isset($_SESSION['internal_breadcrumbs']))
$_SESSION['internal_breadcrumbs'] = array();
$_SESSION['internal_breadcrumbs'][] = $_SERVER['REQUEST_URI'];
$max_breadcrumbs = 5;
while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
array_shift($_SESSION['internal_breadcrumbs']);
That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following
Array
(
[internal_breadcrumbs] => Array
(
[0] => /other_page.php
[1] => /other_page.php
[2] => /other_page.php
[3] => /user_page.php <-- desired page
[4] => /login.php <-- most recent page
)
)
So now... you can setup your url to be something more like the following...
// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs']))
$url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else
$url = "index.php"; // default page for
All the best, and I certainly hope this has helped in some way.
IN SCENARIO 4
From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure)
If response is right send the login password to your script server.
Stips : Encoding password is better secure !
Using header() function it's a bad idea.
Manual specification say ;
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes.
Regenerate cookie each time the loging.PHP is called !
Have a nice day

Code Help - PHP, Query String, Redirect

I'm trying to pass variables to a simple PHP script and have it redirect to different URLs depending on the values in the query string.
Here's what I have in bonus.php:
<?php
if ($_GET['pid'] == '3') {
$bonus = "copy-paste-traffic";
}
elseif ($_GET['pid'] == '5') {
$bonus = "lazy-affiliate-riches";
}
$redirect = "http://affiliatesilverbullet.com/.'$bonus'.-bonus/?mid=.'$_GET['mid']'.&pid=.'$_GET['pid']'.";
echo $redirect;
page_redirect($redirect);
?>
I want queries to redirect as follows:
asbfree.com/bonus.php?mid=dstruckman&pid=3 -> affiliatesilverbullet.com/copy-paste-traffic-bonus/?mid=dstruckman&pid=3
asbfree.com/bonus.php?mid=dstruckman&pid=5 -> affiliatesilverbullet.com/lazy-affiliate-riches-bonus/?mid=dstruckman&pid=3
But it's not working.
What am I doing wrong?
Please show me how to fix my bonus.php script to make this work.
Thanks in advance!
Dustin
I think you may change
$redirect = "http://affiliatesilverbullet.com/.'$bonus'.-bonus/?mid=.'$_GET['mid']'.&pid=.'$_GET['pid']'.";
to
$redirect = "http://affiliatesilverbullet.com/".$bonus."-bonus/?mid=".$_GET['mid']."&pid=".$_GET['pid'];
EDIT : ...change elseif to else if, page_redirect to http_redirect, and remove echo or place after redirect function.
I would use header("Location: $redirect"); instead of page_redirect($redirect);.
One of the issues may be your variable interpolation.
Replace
$redirect = "http://affiliatesilverbullet.com/.'$bonus'.-bonus/?mid=.'$_GET['mid']'.&pid=.'$_GET['pid']'.";
with
$redirect = "http://affiliatesilverbullet.com/{$bonus}-bonus/?mid={$_GET['mid']}&pid={$_GET['pid']}";
Next time you post a question it would be helpful to post the error message you are receiving.

Categories