PHP redirect after form processing - javascript

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);

Related

Prevent Direct access to PHP file using AJAX

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";
}
?>

Variable from posted form stops or continues with php code after pop up box (javascript)

I have an issue with php and javascript included.
Sedning form from data index.php to edit.php
this is my edit.php file:
<script>
function ConfirmNull() {
if (confirm("Are You Sure?")) {
}
else {
window.history.back();
}
}
</script>
<?php
session_start();
// connect to database
include("connection.php");
// update records
if (isset($_POST['update'])) {
$chk=$_POST['chk'];
$manyids=implode(",",$chk);
//$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$user = $_POST['user'];
// if time is NULL ask if you are sure
if ($time == "") {
echo "<script type='text/JavaScript'>
ConfirmNull();
</script>";
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
else {
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
}
?>
Right now if the value time variable is NULL it should run javascript with the question: are you sure?
If YES continue with SQL and update the db.
If Cancell stop the php code and run windows.history.back and do NOT run SQL.
Unfortunately its updating the db when i hit Cancel.
PHP's job is to generate the HTML that gets sent to the browser. As far as PHP is concerned, all your JavaScript is just text. It doesn't have any meaning until it gets to the browser. As such, all your PHP will run before any of your JavaScript.
So the proper place to put your check is in a form submit handler in index.php, before the browser even fetches edit.php:
document.querySelector('#myForm').addEventListener('submit', evt => {
if (evt.target.querySelector('[name="time"]').value === '') {
if (!confirm('Are you sure?')) evt.preventDefault();
}
});
And you really do need to fix your vulnerable database code. As a general rule, $ should never appear in an SQL query string.

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

JavaScript not working in mPDF

I am using mPDF for PDF generation in PHP. It is working fine with no issue.
What I want if user is not logged in then I would like to show error in alert box and after that redirect to index.php.
But due to some reason that I don't know it is not showing any alert box nor redirect. It seems like JavaScript is not working.
Here is the code:
<?php
session_start();
$uid=$_SESSION['uid'];
if($uid== "" or $uid == NULL)
{
echo '<script type="text/javascript">window.alert("Please login first to access this page."); </script>';
echo '<script type="text/javascript">window.location.href("/index.php");</script>';
}
Above code is top of the file and now below I have these code for mPDF:
include("pdf/mpdf.php");
$mpdf=new mPDF('');
$stylesheet = file_get_contents('pdf/tablecss.css');
$mpdf->WriteHTML($stylesheet,1);
//==============================================================
//$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');
$mpdf->SetWatermarkText(' www.somewebsite.com ');
$mpdf->watermarkTextAlpha = 0.1;
$mpdf->watermark_font = 'DejaVuSansCondensed';
$mpdf->showWatermarkText = true;
$mpdf->WriteHTML($html);
$html = '
<html>
<head>
<style>
....
I fixed that. What i did is i put mPdf code inside else.
Like this and it works.
if($uid== "" or $uid == NULL)
{
echo '<script type="text/javascript">window.alert("Please login first to access this page."); </script>';
echo '<script type="text/javascript">window.location.replace("/index.php");</script>';
}else{
mpdf code goes here

Javascript not being executed

This is the top of my php file - what I am trying to achieve is, if the user ends up on this page after a failed login attempt which posts here - a message should be displayed in javascript outlining such failed login attempt and then redirect them back to the previous page.
Why does this happen and what can be done to fix it so the message box is displayed? Alternatively on the previous page - how do i stop the redirect if the login attempt failed?
Thanks
<?php
include("Application.php");
include("Member.php");
include("ContactDetails.php");
include("LoginDetails.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$value = null;
if(isset($_SESSION['url'])) {
$value = $_SESSION['url'];
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
}
if(isset($_POST['submit'])){
$username=$_POST["username"];
$password=$_POST["password"];
$loginDetails = logUserIn($username, $password);
if($loginDetails != null && $loginDetails->getUserid() > 0){
$contactDetails = getContactDetails($loginDetails->getUserid());
$member = new Member($contactDetails, $loginDetails);
//an array of applications belong to a paticular user
$applications = getApplicationsForMember($member);
printUserApplicationSelectionForm($applications);
}else{
//login attempt failed - tell the user and redirect
if($value != null){
$path = "http://localhost" . "$value";
header("Location: $path");
echo '<script type="text/javascript">alert("Login Attempt Failed!");</script>';
}
}
}
You change locations before echoing, so the alert script is never echoed:
header("Location: $path");
echo '<script type="text/javascript">alert("Login Attempt Failed!");
Switch those around and it should work.
if you send the location header, the browser won't load the response (your script) anymore from the current page but directly change to to the new location.
What you could do is to add something like &message=failedlogin to the path before sending the Location header and then display a message in the previous page. You could also store it in the session: $_SESSION['loginsuccess']=false; and then check for this value in the previous PHP page.

Categories

Resources