stop other users to browse to some pages of my website - php

In my website i have used ajax at many places... But the problem is that the file, lets say some_ajax_file.php, is visible in the source code... I want that other users dont just type this in the url and go to this page... If they do so, they will then be redirected to another page...
I tried following code on that ajax page:
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$cur_page=curPageName();
and checked it
if($cur_page=="some_ajax_file.php")
//then redirect...
it is working if the type some_ajax_file.php in the url...but the problem is that the the ajax function where i used this some_ajax_file.php is not working....plz help me ....i m stuck....

You must have to search for $_SERVER['HTTP_X_REQUESTED_WITH']
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// I'm AJAX!
}
else
{
header();
die();
}

Create a Session at the time of Login
<?php
session_start();
// store session data
$_SESSION['Username']= Userid;
?>
and check the Session Available on that Page...
session_start();
if(empty($_SESSION['Username'])) {
//Redirect them to common page....
}
if the session availed then Show the page
Otherwise redirect them to login page....

Related

How to go back to previous page after successful login

I am working with a login system. Here is my code to redirect some other page after successful login. I just want to go back to the previous page instead of redirect some specific page.
Code: login.php
<?PHP
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("login-home.php");
}
}
?>
In the previous page
add these:
session_start();
require_once("./include/membersite_config.php");
if (!$fgmembersite->CheckLogin())
{
$_SESSION['redirect_url'] = $_SERVER['PHP_SELF'];
header('Location: login.php');
exit;
}
login page
session_start();
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
if($fgmembersite->Login())
{
$redirect_url = (isset($_SESSION['redirect_url'])) ? $_SESSION['redirect_url'] : '/';
unset($_SESSION['redirect_url']);
header("Location: $redirect_url", true, 303);
exit;
}
}
In PHP you can get the previous page using $_SERVER variable. By this $_SERVER['HTTP_REFERER'], which contains the page URL from the current page is being called.
But sometimes there is an option in the browser which some users can
disable to send this information.
So beware to use this option.
Alternate to this option is to set a value in form and send it along with other data, that is still vulnerable as this can be changed by user easily.
You can try this approach:
In your login page:
$comingFrom = $_SERVER['HTTP_REFERER'];
if(isset($_POST['submitted']))
{
//or you can store it in session also.so that you can redirect it from anywhere.
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL($comingFrom);
}
}

Open Page Only After Redirecting

My question is may be foolish. But I want to know, if there is any code that prevent the page opening if tried with link but opens only after . if it's link is from another page.
for example, if i have a form on page contact.php and user gets redirected to page contact_success.php.
Now I want, if anybody tried to open contact_success.php page directly from browser address bar, it should not be get opened. It should be get opened only after form submission from contact.php page..
A simple way is just to use an if check on the contact_success.php page like
if($_SERVER['REQUEST_METHOD'] = "POST"){
//display page
} else {
echo 'You cannot view this page.';
//add redirect, if you like
}
Set a session or a cookie for the user in the contact.php, and then in the contact_sucess.php you can check if it exists.
for exmaple:
contact.php:
<?php
$_SESSION['visited_login'] = 'yes';
?>
contact_sucess.php:
<?php
if (isset($_SESSION['visited_login']) && $_SESSION['visited_login']=="yes") {
// output tanks
} else {
echo "go away";
die;
}
?>
You can use session for that example:
let say when you submit the contact form there is a page where in you will process the user input and i will use(refer to the #1)
contact_process.php
$_SESSION['success'] = 'success';
(this code will create a session)
then once success in processing the user input there is another page like(refer to # 2)
contact_success.php
if(isset($_SESSION['success'])
{
//Output if it is success
}
else{
header('location:contact.php');
}
(this code will check if session is existing if yes the desired output will show and if not it should turn back to contact.php)
you can easily learn session here http://www.w3schools.com/php/php_sessions.asp

why my echo doesn't work before a header function header(location:home.php);

why my echo doesn't work here in this code?It goes directly to the function header().
if($result){
echo("<script> alert('User Successfull Added')</script>");
header('location:home.php');
}
In order to make your code example work, you need to put it inside an if/else condition like so, if you want it to work, but since I only see what you posted as code, am putting this in as an example:
<?php
if($result){
echo("<script>alert('User Successfully Added')</script>");
echo("<script>window.location = 'home.php';</script>");
}
else {
header('Location: elsewhere.php');
}
Actually thy echo is working. but we cant see the message because at the same time the page redirects to the home.php page.
If you want to alert to display the alert message use jquery post. or php session variable
Assuming you want to both display the alert & redirect to home.php, why don't you just try setting a SESSION (or other global variable) and then check if it's set at the start of the redirected page?
Such as:
<?php
session_start();
$_SESSION['usercreated']="Y";
header('Location: elsewhere.php');
?>
and then on home.php at the start of your php code:
<?php
session_start();
if(isset($_SESSION['usercreated'])){
echo("<script> alert('User Successfully Added')</script>");
}
//....
?>
Sorry, I can't add comment here. But I think what you want to do needs Java and replace alert() with confirm()
var r=confirm("User Successfull Added")
if (r==true) // if user click OK
{
window.location.assign("home.php")
}
else // user click Cancel
{
}

Reload page in php

While designing sign up page I wish to reload page if user has submitted anything wrong in the fill up boxes. How can I reload page after the user presses submit button with a wrong entry ? (while verifying expected content through php)
You can use header() plus some _GET variables for telling the original page there were errors.
Form submit page:
<?php
//.... lots of code validation
if ($failed) {
header('Location: http://path.com/to/your/site/original_form.php?error=1');
}
?>
Form page:
<?php
if (isset($_GET['error']) {
echo "there was an error! Please fix it!";
}
?>
Try the following -
if (validation_failed) {
header("Location: http://yourserver.com/signup.php");
} else {
header("Location: http://yourserver.com/welcome.php");
}
PHP Header function

PHP: Detect Page Refresh

I have a page action.php on which I run an SQL query through the code, so that whenever the page is viewed the query runs like its like counting page views
<?php
mysqli_query("UPDATE ****");
?>
The problem is when the page is refreshed, the query is run & PAGE REFRESH is counted as a PAGE VIEW which I want to avoid.
Question: How to avoid it ?
What I am looking for is a simple solution so that I can check
if( page was refresh ) //some condition
{
do
}
I found this snippet here, and it worked perfectly for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed ) {
//do something because page was refreshed;
} else {
//do nothing;
}
Best way to Detect Page Refresh. or Not ?(Ctrl+F5,F5,Ctrl+R, Enter)
$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' || $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache');
if($pageRefreshed == 1){
echo "Yes page Refreshed";
}else{
//enter code here
echo "No";
}
You can't directly detect a page refresh, but you can use a cookie to simulate what you want:
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again.
If you just want to run it once for a user, I would set a session cookie and then use an if() statement.
<?php
session_start();
if (!$_SESSION['loaded'])
{
// insert query here
}
$_SESSION['loaded'] = true;
?>
i have solved the problem ... HURRAHHH with no session & no cookies
the solution is a combination of PHP : AJAX : JavaScript
the query that you want to run on Page Load & not on page Refresh run it as via AJAX call lets say my function for doing that is
function runQUERY()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","doIT.php",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
and i can simply check with Javascript that the page is a fresh load or its a refresh by doing the following
<head>
<script type="text/javascript">
function checkRefresh()
{
if( document.refreshForm.visited.value == "" )
{
// This is a fresh page load
alert ( 'Fresh Load' );
document.refreshForm.visited.value = "1";
..call you AJAX function here
}
else
{
// This is a page refresh
alert ( 'Page has been Refreshed, The AJAX call was not made');
}
}
</script>
</head>
<body onLoad="checkRefresh()">
<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>
</body>
</html>
and in your doIT.php simple add your PHP code which you were going to put in the normal page
<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>
//here you get the url behind the domain.
$currentPage = $_SERVER['REQUEST_URI'];
//if the session current page is not set.
if(!isset($_SESSION['currentPage'])){
//set the session to the current page.
$_SESSION['currentPage'] = $currentPage;
}
//check if the session is not equal to the current page
if($_SESSION['currentPage'] != $currentPage){
// if it's not equal you set the session again to the current page.
$_SESSION['currentPage'] = $currentPage;
//set the query you want to use
}
This can work in your scenario:
if(isset($_GET["token"])) {
$view_token = $_GET["token"];
} else {
$new_views = $views + 1;
// UPDATE VIEWS
$view_token = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
header("Location: ?token=$view_token");
}
If the user has a token in the URL, the view count will not update. Therefore, if the user tries to refresh, it will not update the view count. When the user does not have a token in the URL, the view count updates and refreshes the page WITH a token. It is thinking outside of the box but it works!
You can save a cookie that will be associated with the present page and if any link is clicked, update the cookie with the new page name.
Assuming the above is done in Javascript, you can send this updateCookie information to the server to notify about a new page hit.
Or another approach could be, you can specify a HTTP HEADER that specifies after how much time the cache expires on a page and that way, the browser wont even send you a request about page load/refresh.
See http://www.mnot.net/cache_docs/#IMP-SCRIPT for information about CACHING
Also , check out Etag vs Expires in HTTP - ETag vs Header Expires
if( $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
{
$_SESSION['status'] = null;<br>
}

Categories