Handling fragment identifiers during PHP redirects - php

I have searched around (SO and Google) and can't find any proper explanation of how other people handle this situation.
In my application I am using PHP/Apache as a backend and Ben Alman's jQuery BBQ plugin for hashtag browser history. User logins are handled solely by the PHP server end using POST from a login page and state maintained using server side sessions. The problem I have is that if a user visits a URL with a fragment (hash) and they are not logged in they are redirected to the HTTPS login page. This works well in every situation except where the URL contains fragment hash. The same situation would be the case for any redirect initiated from the server side. It's not like javascript can be used in this situation to preserve the hashtag before the redirect as page load never completes before the redirect.
I realise that the fragments will be lost during the redirect (as it's client side only) and is never seen by the server end but how does everyone else handle this situation and preserve the URL originally visited so that the user can end up on the correct page after login or redirect?
Any advice appreciated. Thanks.

Populate a hidden input with the fragment using JavaScript.
<input type="hidden" name="fragment" id="fragment">
<script>
if(window.location.hash){
document.getElementById("#fragment").value=window.location.hash;
}
</script>
Then on the back end, you can redirect like this:
if(isset($_POST['fragment'])) {
$fragment = '#'.$_POST['fragment'];
} else {
$fragment = '';
}
header('Location: http://website/path'.$fragment);
exit;
You should probably urlencode the fragment.

Related

How to remember which URL the user was accessing before registration

I am developing a Laravel application and I need some suggestion.
I have a page which when a user who is not logged in access, it redirects to the login page and after authentication, he is back to the same. This works fine.
The problem is that if the user was a new user. He doesnot have a login and goes for Registration.
He then registers and the application redirects him to several other pages (like e.g.He needs to verify his email) and when all is done he will be on the dashboard page.
Now is there any way, I can save that he was on certain page and after registering and moving through all those pages come back to the same page?
Thanks,
Santhosh
Since you haven't posted any code I'd write a general explanation of how I think you should handle this.
In short - you can get the indented url and add it to the registration button as a query parameter i.e yourdomain.com/register?origin=some_route.
So assuming you have a register button/link on your login page, add the origin to the link href:
<a href="register?origin=some_route">Register<a>
This way, when you finish the registration, you can simply access the origin by using \Input::get('origin').
Now, to actually get the intended url you can either try and get it from the Session by using:
\Session::get('url.intended', url('/'))
or you could use \Redirect::intended(url('/'))->getTargetUrl();
In both cases url('/') is used as a fallback url to the homepage and you could replace it with any other url you wish.
Hope this helps!
I imagine you could do something like this for one page:
return redirect()->intended('/dashboard');
which would the the same as
return \Redirect::intended('/dashboard');
As per docs: https://laravel.com/docs/5.2/authentication#authenticating-users
The intended method on the redirector will redirect the user to the URL they were attempting to access before being caught by the authentication filter. A fallback URI may be given to this method in case the intended destination is not available.
Alternately, if you're going through a multi-page login 'wizard' type deal, I'd personally store the initial value of redirect()->intended in a Session or Cookie, and redirect to the value of the session / cookie once your registration process is complete.
Instead of intended redirect function you can print the HTTP referer in a hidden field in the form, then after login redirect to that URL.
<input type="hidden" name="redirect" value="{{URL::previous()}}">
Controller:
if(Input::get('redirect') && (Input::get('redirect') != url('/path/to/login/'))){
return redirect(Input::get('redirect'));
}
else{
return redirect('/alternative/page');
}

PHP redirect when URL is not requested through ajax (when on a wordpress page)

I have a Wordpress website with Domain: Hello.com which is "ajaxified".
what I want to know is how to redirect user back to Hello.com if they visit Hello.com/ask, Hello.com/cake or anything deeper using the browser address bar.
Even if they go 2 degrees deeper like Hello.com/cake/make, I want them to stay at the root of my website.
I am using Wordpress and my first Idea was to put redirect script at header, but ended up making an infinite redirect loop.
How can I redirect users to homepage without redirecting my ajax requests to the homepage as well?
[If you ask why I would disallow them to go deeper, the answer is: I
am using ajax to load deeper pages and everything else into a div]
By adding a short PHP script somewhere before everything else, I was able to check how my pages were loaded using the condition below.
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
It allowed me to check through PHP if it was through Ajax or not.
The value of $_SERVER['HTTP_X_REQUESTED_WITH'] is xmlhttprequest when the request was an ajax request.
For my case, this is how I used it:
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
header("Location: http://". $_SERVER['HTTP_HOST']."/");
}
Which would check if the request was done through ajax, and redirect to the homepage/Main Screen of the website/web App if not.
I got the idea after reading this post
Note: Usage of HTTP_X_REQUESTED_WITH depends on the JavaScript framework you are using, if it sets that header. I am using jQuery and it does it for you.
Also $_SERVER is not entirely a part of PHP so it also depends if your server passes that variable to PHP.
If you are on a Nginx Server and it doesn't work for you, you can try this:
Passing HTTP_X_REQUESTED_WITH from nginx to php
Hope this helps others!

How to hide HTML Page Source in php by detecting the URL

I do not care about people viewing my source code, however, I want Bots to avoid coming on to my site and getting through my security. I was hoping to disable page source viewing. To do this, I am using this code:
$url= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$needle = "view-source:";
if (strpos($url,$needle)) { echo "You can not see me";}
else {
//The rest of my index page
}
The objective here is that if someone tries to view my page source or if a bot tries to, that rather than being able to see it, the code will detect that the page URL is view-source:www.yoururl.com and will display a "Nice try" message in the source instead of the page source. The code above in theory should have worked, but didn't. Any other idea's to try and make this work?
This cannot be done, the HTML source code is passed to whoever requests it. You should probably redesign your captcha, as it is not secure from how you described it. Use session variables to store the data and to check against the submitted value on the form processor script.
you could use mod_rewrite and a permanent 301 redirect in your .htaccess to hide the ?captcha=xxxx part of your url, if it is your sole concern.

(A|B) testing Google Analytics, remove utm_expid from URL

Im new to this and im trying to rewrite URL so that utm_expid is hidden so if my url is:
http://www.myweb.com/?utm_expid=67183125-2
how would i make it so when user visits
myweb.com
it does not show utm_expid in url
Is this possible using PHP/JS?
NOTE: i cant use RUBY or any other languages except PHP/JS/HTML
There is a way. Just redirect the page to base url once the utm_expid=67183125-2 is got. ie,
if($_GET['utm_expid']) { //header to redirect to myweb.com }
Its a tricky way. Hope you are permitted to use it.
Just start a session and store value in session variable. you can regain it even page is re directed.
ie
<?php
session_start();
if($_GET['utm_expid']) {
$_SESSION['variable_name']=$_GET['utm_expid']
//header to redirect to myweb.com
}
?>
Let me add this Javascript trick that is server agnostic.
if (location.search.indexOf('utm_expid') > -1) {
history.replaceState('page', 'Title', '/')
}
I recommend you to place it at the end of the body.
If you wanted a clean URL (as you do for branding and manual sharing purposes), I'd script it so that you load a full page iFrame which loads the gA test queried URL. That way the user see s the clean URL in the address bar and still see the experiment.
You could use PHP to set up your index page (or any server side, or even client side script).

How can I deny users access to parts of my Backbone App if they have not logged in?

So I've got a Backbone application + web homepage. Right now, if you login to my website, I create a global object with your user details from the database. However, you can still just hit one of the routes in the application directly.
How should I handle users who are not "logged in" and redirect them to a "you must login page"?
Is this a standard operation? Basically, I have a REST url setup that returns just
{ sessionId: [php-session-id-here] }
If they are logged in, it would return something more like this:
{
sessionId: [php-sess-id],
userId: [user-id-from-db],
firstName: [f-name],
lastName: [l-name]
}
Ideas? Thanks!
What I've done in the past is to include on every page along with jQuery (actually, added to the jQuery file) an extension on the AJAX method to check for a custom code that I send when a user isn't logged in. When that value was seen it redirected the user to the login page regardless of what was going down.
This was because that site had a time out on login, so a user could get logged out while sitting on a page and then the AJAX request would just fail. If you don't have a timeout on the login the odds of ever seeing this issue are slim. Just ignore requests that come from users that aren't logged in.
If you need help coding this, start here: Extending Ajax: Prefilters, Converters, and Transports.
Really shouldn't require anything as complex as pseudo-code:
JS needs to do some AJAX, so JS talks to server
PHP checks for login if needed
If not logged in, send back the abort message (I used a converter to catch a "notLoggedIn" dataType. However this could also be done with a transport, they are just more complex.)
JS sees the abort message and does a window.location redirect rather than return AJAX message.
If you want, you could load a lightbox with a login form and send that via AJAX to PHP where a re-login can take place, if you remember the AJAX attempt that failed you can send it again after login. Then the user doesn't even need to leave the page to log back in.
If you're using jQuery, you can set a global ajaxSetting that allows you to do certain things upon certain http codes. Some pages I read recommend adding to your JSON a url field to point to where to login, but I figure that's just up to you. So the only modifications you'd need to implement what I've mentioned is 1. change the http code to something reasonable like 401 (unauthorized) and implement the http code handler. But I wouldn't call this standard, I'd just say that's what several people have done (including myself).
<?php
function IsLoggedIn()
{
if(isset($_SESSION['id'])) // Change that to what you want
{
return 1;
}
else
{
return 0;
}
}
?>
Then in your code, you could use something like:
if(isLogged()){ header('Location: http://google.com'); }

Categories