PHP redirect if statement - php

I am using this if statement to redirect a user if the values in a .txt document is 0 but if it is 1 I want nothing to happen however I'm having some issues with my code.
This is my code currently:
$setup = require('setup.txt');
if ($setup === "0") {
echo '<script type="text/javascript"> window.location = "setup.php" </script>';
}
The setup.txt document currently contains the value 0.

I'd look here as to the proper usage of the require function.
if (file_get_contents('setup.txt') == "0") {
header('Location: /setup.php');
}

Use the header function if you have not already sent output to the browser.
$setup = file_get_contents('setup.txt');
if ($setup == "0") {
header('Location: /setup.php');
}
Since all PHP is executed before the output the site. Use this option first.
You can not use include() / require() to transfer as a variable, like you have. Use file_get_contents() to achieve the results.

try this:
<?php
$setup = file_get_contents('setup.txt');
if (trim($setup) == "0") {
echo '<script type="text/javascript"> window.location = "setup.php" </script>';
}
?>

Related

PHP: Rendering included files in ajax request

I have the following files
/includes
- file_inc1.php
- file_inc2.php
ajax.php
index.php
index.php calls an ajax request to ajax.php and ajax.php has something like below code
$nextStep = $_GET["nextStep"];
if($nextStep == 1) {
include "includes/file_inc1.php";
} else if($nextStep == 2) {
include "includes/file_inc2.php";
}
With this set-up, does anyone have a clue why the returned response from ajax is empty?
$nextStep = $_GET["nextStep"];
if($nextStep == '1') {
include "includes/file_inc1.php";
} else if($nextStep == '2') {
include "includes/file_inc2.php";
}
Thanks for all your responses. I was able to solve my own problem. I need to make sure that on my includes/file_inc1.php and includes/file_inc2.php files, I use ob_start() and ob_get_clean() like so:
<?php
ob_start();
// HTML + MYSQL + OTHERS
echo ob_get_clean();
?>

php redirect_to() function undefined

I am working on a database and I need to redirect the user to another page after the login process.
I am using the redirect_to() function. After the code executes it gives me the error
Fatal error: Call to undefined function redirect_to()
Here is what I tried
if($result){
$num_rows = mysqli_num_rows($result);
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
redirect_to("main.php");
}
else{
redirect_to("index.php");
}
}
You have to define the redirect_to function before calling it. Try this code
<?php
if($result){
$num_rows = mysqli_num_rows($result);
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
redirect_to("main.php");
}
else{
redirect_to("index.php");
}
}
function redirect_to($location){
header('Location:'.$location);
}
?>
Try to use header :
<?php
/* Redirection vers une page différente du même dossier */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
redirect_to() isn't a function. You want to use header("Location: main.php");
As this is adding header information, it needs to be loaded before anything is passed to the page (I believe), so don't attempt to print anything out to the page before header() is called.
If you want to do something like that, I suggest using javascript.
redirect_to doesn't exist, or if it does, it's not been included/required correctly.
Add this;
if( function_exists('redirect_to') == FALSE ) { //Future proofing...
function redirect_to($where) {
header('Location: '. $where);
exit;
}
}
If you already have output, I would advise you looking at using output buffering.
You can easily redirect using following header("Location: ....) syntax:
header("Location: main.php");
exit;
You should equip your project with this function first as others have pointed. Alternatively refactor your code to use the builtin php function -> http://php.net/manual/en/function.http-redirect.php

Anti-CSRF not working correctly

<?php
$_SESSION['csrf_token'] = md5(uniqid(rand(), true));
?>
<?php
$csrf1 = $_POST['csrf_token'];
$csrf2 = $_SESSION['csrf_token'];
if($csrf1 === $csrf2) {
//not executing
} else {
}
?>
javascript
var csrf = "<?php echo $_SESSION['csrf_token']; ?>";
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "success"){
} else {
window.location.replace("login.php");
}
}
}
ajax.send("csrf_token="+csrf);
}
return false;
So, here's some PHP from my code that generates a CSRF token, puts it in session, then checks whether the session value and the POST value are the same. The problem is, the if statement isn't executing. When I echo out the session token right before I send off the request using ajax, the session token is the same. I'm fairly sure that the session token is changing, and I am unsure why.
Edit: I added my javascript. I removed a lot from it, so I hope I didn't mess anything up on it.
A very important piece of information OP failed to provide is that the request goes to the same script that makes his token. Therefore, what is happening is exactly what is supposed to happen. Here is a solution I provided to him on a different website.
<?php
if((isset($_SESSION['csrf_token'], $_SESSION['time']) && time() - $_SESSION['time'] > 60) || !isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = md5(uniqid(rand(), true));
$_SESSION['time'] = time();
}
?>
if($csrf1 === $csrf2) {
change so: if($csrf1 == $csrf2) {
I would echo the contents and visually compare the two to check for identical values. For what it is worth, have you tried strcmp()?
if(strcmp($csfr1, $csfr2) == 0) {
//Got a match
} else {
//No match, look at the two strings for debug purposes.
print("<pre> CSRF1: $csrf1 \n CSRF2: $csrf2 </pre>");
}

How to create a pop up window using php via echo?

Is it possible to make a pop up window in my existing script?
session_start();
$_SESSION['success'] = ($result) ? TRUE : FALSE;
header('location: inv_fc.php');
session_start();
if ($_SESSION['success'] == TRUE) {
// CREATE POP UP WINDOW SUCCESS
} else {
// CREATE POP UP WINDOW FAILURE
}
You can do it with Javascript. For nicer results, use jQuery UI.
if ($_SESSION['success'] == TRUE) {
echo "<script>alert('Success!');</script>";
} else {
echo "<script>alert('Failure.');</script>";
}
You could open a pop-up using javascript or target a's attribute, but it's impossible from PHP, which is executed at server side.
Edit: ok, as I saw the <script> things: it's not PHP, it's Javascript, from PHP it's not possible.
<?php if ($_SESSION['success'] == TRUE)?>
<script>window.open(...);alert('Your Awesome!');</script>
<?php else ?>
<script>window.open(...);alert('You Fail!!');</script>
<?php endif; ?>

Use PHP sessions with jquery

Well, my question is simple:
I wish to use my PHP sessions in jQuery, in an if statement, however I do not know how I can do this on an easy way. Am I supposed to somehow import the $_SESSION in jquery?
What I basically want to do, is open a dialog if the User_ID is the same as the $_SESSION User_ID. Also I wish to have it checked to see if someone is an administrator, shop-manager or a user, with the session. This information already exists in PHP and the User_ID only exists in jQuery.
if($admin == true || gebr_id == $_SESSION['id']){
Javascript code here?
}
I think that would be the easiest way to solve it, however that does not seem to work for me. Perhaps I am forgetting tags for the PHP to understand it's javascript?
I've figured out an easy way to come around the solution, thanks you you all!
Solution:
$('.do').click(function(){
<?php
if ($admin == true) {
echo "$('#dialog').dialog('open');\n";
echo "var cid = $(this).attr('id');\n";
echo "var datum = cid.substr(0, 10);\n";
echo "var naampos = cid.indexOf('|');\n";
echo "var gebridpos = cid.indexOf('||');\n";
echo "var naam = cid.substring(naampos+1,gebridpos);\n";
echo "var gebrid = cid.substring(gebridpos+2);\n";
echo "$.ajax({\n";
echo "type: \"POST\",\n";
echo "url: \"agenda.php\",\n";
echo "data: naam,\n";
echo "success: function(){\n";
echo "$('#gebruikerinput').html(\"<input type='text' READONLY='' size='35' value='\" + naam +\"'>\");\n";
echo "$('#gebridinput').html(\"<input type='hidden' name='gebridtextbox' value='\" + gebrid + \"'>\");\n";
echo "$('#datuminput').html(\"<input type='text' READONLY='' size='12' name='datum' value='\" + datum + \"'>\");\n";
echo "}\n";
echo "})\n";
echo "return false;\n";
}
?>
});
It seems to be working so far. The only thing left for me to do is to make so jQuery returns a User_ID variable which needs to be identical to the session ID.
if($admin == true || gebr_id == $_SESSION['id']){
$javascript = "javascript code here";
}
and then in your html
<body>
<?php echo $javascript ?>
</body>
You cannot import the $_SESSION, but you can store some of them (only those that you want) in the cookie and read it in javascript.
For example: store the user-id in the cookie and you can read the value from the cookie in javascript.
read cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Sadly that you can mix server-side script (PHP) with client-side script (Javascript). However, you can use PHP to echo Javascript, like:
if ($admin == true || gebr_id == $_SESSION['id']){
echo '<script>
alert("Admin!");
$("selector").function(); //
</script>';
}
Php is a server side language. javascript runs on the browser (client side).You can do this:
if($admin == true || gebr_id == $_SESSION['id'])
echo "<script>";
echo "here your jquery function";
echo "</script>";
}
So that you're just rendering HTML
hope it helps
<script type="text/javascript">
<?php if($admin == true || gebr_id == $_SESSION['id']){ ?>
alert('<?php print $admin; ?>');
<?php } ?>
</script>
also works.
Bypassing the apparently obvious security flaws with what you seem to be suggesting, you want to output the PHP session ID to your web page. Of course, JQuery is a client-side language, and it's pretty trivial to circumvent any client-side security of that nature.
<script type='text/javascript'>
<?php
//put in your variables from PHP
echo 'var phpId="' . $_SESSION['id'] .'";' ."\n";
echo 'var admin=' .$admin.";\n";
?>
//Back to Javascript (client side) here
if (gebr_id == phpId || admin){
...
}
</script>
You say you only have the user ID in JQuery. What you should do is code it so you have the user id available in PHP instead... Submit a form with the user id or something like that, then you can store that in the PHP session and do your authentication server-side.
If you like to get access to PHP Sessions from javascript, you can write a simple wrapper.
Somethign like this:
<?php
session_start($_GET['sid']);
echo json_encode($_SESSION);
?>
Keep in mind that this is a possible security flaw, as everyone can get access to your PHP Session variables from outside (with a valid session id).
Now you can simply use jQuery to ask the server for the current session data

Categories