I want to prevent direct access to a certain PHP file called prevented.php
My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?
Here's my code:
index.php
<?php
$_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
$.ajax({
type: "POST",
url: "def.php",
data: {
token: '<?php echo $_SESSION["token"]; ?>'
},
cache: false,
success: function(data) {
console.log (data);
if (data) {
console.log (data + ' valid');
} else {
console.log (data + ' invalid');
}
location.href = "prevented.php";
},
error: function () {
console.log('error');
}
});
</script>
def.php
<?php
session_start();
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {
echo false;
die('invalid in def');
} else {
define('_DEFVAR', 1);
echo true;
die ('valid in def');
}
?>
prevented.php
<?php
include "def.php";
if (defined('_DEFVAR')) {
die ('valid in prevented'); // instead of this I would show the content of the page
} else {
die ('invalid in prevented');
}
?>
Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.
index.php:
<?php
session_start();
$_SESSION['flag'] = true;
?>
click here for the protected page
protected.php:
<?php
session_start();
if ($_SESSION['flag'] ?? false) {
echo "you have previously visited index.php";
} else {
echo "you have not previously visited index.php";
}
?>
Related
I've been staring at code too long however when I used a simple script to save a form with:
endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>
at the end the page redirected back to itself just fine, however now I have a longer script here I can't quite figure out where or how to code my redirect:
<?php
session_start();
$directory = 'users/'.$_SESSION['username'].'/';
//here you can even check if user selected 'Delete' option:
if($_POST['Action'] == "DELETE"){
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete))
echo $file_to_delete." deleted.";
else
echo "Error deleting file ".$file_to_delete;
}
if($_POST['Action'] == "SAVE"){
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
}
?>
may be you should use querystring variable while redirecting.
if($_POST['Action'] == "DELETE") {
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete)) {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
} else {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0& file='.$file_to_delete);
}
}
In codesaveindex.php:
if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
echo "Error deleting file ".$file_to_delete;
}
You can't redirect if the page after html has been outputted.
You need to either use output buffering or redirect using javascript,
or organise it so that the redirect happens before the html is shown.
i have a class written for such thing, should be very easy to use class.route.php
simply do this where you want to redirect: route::redirect('page', http_status);
I want to make a javascript function which checks the database whether the id requested by the user is available or not. My code is:
HTML:
<button type="button" onclick="chkId()">Check Availability</button><span id="chkresult"></span>
Javascript code:
function chkId()
{
$("#chkresult").html("Please wait...");
$.get("check_id.php", function(data) { $("#chkresult").html(data); });
}
The check_id.php file:
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
echo "Available!";
}
else if ($total > 0)
{
echo "Not Available!";
}
?>
But when the button is clicked, nothing happens. I just get a 'Please wait...' message, but as expected by the code, after 'Please wait...' it should change either to Available or to Not Available. But I only get the 'Please Wait...' message, and the result Available or Not Available is not printed on the screen. Please help me what changes do I need to make in my code.
I do not see the $id variable in your PHP script that is used by your $id_query.
Try adding that above $id_query
A few things I notice:
Your javascript is not passing the id parameter to your php backend. See the documentation for the proper syntax to pass that id param.
Your PHP is calling the mysql_query method and one of the parameters that it is passing in is the $id - but $id has not been declared. Check your PHP logs and you'll see where it is choking.
Because the PHP code is likely failing due to the unresolved variable, it is returning an error code. When JQuery receives the error code, it goes to call your ajax failure handler, but you have not declared one! Try adding a .fail(function(){}); to your get call as the docs describe - and you'll likely see the php error message show up.
EDIT: Obligatory php sql injection attack warning. Make sure to escape client input!!!
$.ajax({
type: "POST",
url: "check_id.php",
data: {
id:id; //the id requested by the user.You should set this
},
dataType: "json",
success: function(data){
$('#chkresult').html(data);
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
In your php
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Available');
}
else if ($total > 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Not available');
}
?>
I checked the accepted answer of this question it but didn't help
I'm trying to make an AJAX Post Request to sumbit my signup form, the ajax.php file will check the entered information, example passwords match or not, and then attach the $_POST variable to a $_SESSION variable so that I can call the submitted data from any other page later.
Ajax.php
...
if ($everythingValid) {
// add this user to db
$_SESSION["signup_details"] = $_POST;
echo "SUCCESS#".$core->signupPaymentUrl($package); // tried without this line but didn't work
exit(); // tried without this line but didn't work
} else {
foreach ($errors as $e) print "<br>".$e;
exit();
}
...
The jquery code that I'm using to call the file is the below:
var form = $('#signup');
$("#submit").click(function() {
$.ajax( {
type: "POST",
dataType: 'html',
crossDomain: true,
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
if ("SUCCESS" === $.trim(response.split('#')[0])) {
// user created, redirect to payment page
var paymentUrl = $.trim(response.split('#')[1]);
window.location.href = paymentUrl;
} else {
$("b#signupErr").hide();
$("b#signupErr").html(response);
$("b#signupErr").fadeIn();
}
}
} );
});
After submitting the form, I successfully get redirected to the payment Url, however, after accessing the page where I want to use my session, I cannot figure out how to retrieve my session although I'm pretty sure that I have included session_start in both of ajax.php and completeOrder.php and no blank spaces before the opening php tag.
here is the line that I included in both files :
if(!session_id()) session_start();
I tried to var_dump the $_SESSION variable on ajax.php and It looks okay. However when I var_dump the session variable on completeOrder.php it shows me NULL
Finally here is the completeOrder.php content
if(!session_id()) session_start();
require_once("core.php");
$core = new coreOptions();
$email = $_SESSION["signup_details"]["email"];
$password = $_SESSION["signup_details"]["password"];
$package = $_SESSION["signup_details"]["pkg"];
$options = $core->attachOptions($package);
if ($core->registerUser($email,$password,$options,$package))
$core->redirect("registrationCompleted.php");
in the completeOrder.php file remove if(!session_id()) session_start();
and then only add session_start(); and it will do the trick!
session_id() will return an empty string in ajax.php if there was no call to session_start() before. So the in ajax.php session_start() will never be called and the content of $_SESSION won't be stored anywhere.
So just use:
session_start();
in both files.
Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail
I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}