PHP function getting confused with a second parameter/argument - php

At the end of all of my scripts, I run a function closeConnection, i.e.:
closeConnection("success");
function closeConnection($note) {
if ($note === "success") { $append = "?success"; }
if ($note === "blank") { $append = "?blank"; }
mysql_close();
header("Location: index.php" . $append . "");
exit();
}
This runs smoothly.
However, I now want my closeConnection() function to take two arguments, so that I can choose a different page to redirect to. This is how it looks the second time around:
closeConnection("updated", "view");
function closeConnection($note, $header) {
$header = $header; // Not sure if needed, doesn't work with or without.
if ($note === "updated") { $append = "?updated"; }
if ($note === "blank") { $append = "?blank"; }
mysql_close();
header("Location: " . $header . ".php" . $append . "");
exit();
}
Desired result: Redirect to view.php?updated
Actual result: Redirect to .php?blank

In my experience, you are calling closeConnection("updated"); somewhere before the closeConnection("updated", "view"); and you forgot to remove it or something.
Make sure you didn't forget previous commands, and that you are in fact saving the right file.

Related

Cannot Redirect Using $_SERVER Variables, PHP

I have a PHP application (a request form) that first checks for an active $_SESSION before a user can access the site. Because of the timeout period set for this form there is rarely an active session. Here's the check:
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
}
...and here is the else {} that I use to grab the REQUEST_URI:
else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://myinternalwebsite.net$referer";
}
header("Location: https://myinternalwebiste.net/confirm_auth.php?sso");
}
...and last, here is what I do with the $_GET
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://myinternalwebsite.net/");
}
}
However, once my session is killed I am never properly routed back to the URL set in the ['REQUEST_URI'], I am always just dumped onto the internal site's front page. I have troubleshooted this on and off for some time over the last week, to no avail. I've tried other variables in the $_SERVER array as well, such as ['REDIRECT_URL'].
I'm at a loss, and I'm sure this fairly simple for anyone with more experience than myself... so I am all ears and eager to learn.
EDIT:
Thank you for the comments below. Per your advice I will add the entirety of my code here, removing only the unnecessary parts. (And yes, I appreciate the tip to flip the initial (isset()) to (!isset(). Thank you for that.)
<?php
session_start();
$auth = new OneLogin\Saml2\Auth($saml_settings);
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
} else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://example.net$referer";
}
header("Location: https://example.net/confirm_auth.php?sso");
}
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://example.net/");
}
} else if (isset($_GET['slo'])) {
$auth->logout();
} else if (isset($_GET['acs'])) {
$auth->processResponse();
$errors = $auth->getErrors();
if (!empty($errors)) {
echo '<p>', implode(', ', $errors), '</p>';
}
if (!$auth->isAuthenticated()) {
echo "<p>Not authenticated!</p>";
exit();
}
$_SESSION['samlUserdata'] = $auth->getAttributes();
if (isset($_POST['RelayState']) &&
OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
$auth->redirectTo($_POST['RelayState']);
}
} else if (isset($_GET['sls'])) {
$auth->processSLO();
$errors = $auth->getErrors();
if (empty($errors)) {
echo '<p>Sucessfully logged out!</p>';
} else {
echo '<p>', implode(', ', $errors), '</p>';
}
}
?>

Why can I not return a HTTP response from a private function in symfony?

I have a controller working like this'
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if($openEntries === 0) {
//do some stuff
}
elseif ($openEntries === -1) {
//Sends email to notify about the problem
$body = 'Tried to create position log entry but found more than 1 open log entry for position ' . $position->getName() . ' in ' . $position->getACRGroup()->getName() . ' this should not be possible, there appears to be corrupt data in the database.';
$this->email($body);
return new response($body . ' An automatic email has been sent to it#domain.se to notify of the problem, manual inspection is required.');
} else {
//do some other stuff
}
}
private function checkOpenEntries($position) {
//Get all open entries for position
$repository = $this->getDoctrine()->getRepository('PoslogBundle:Entry');
$query = $repository->createQueryBuilder('e')
->where('e.stop is NULL and e.position = :position')
->setParameter('position', $position)
->getQuery();
$results = $query->getResult();
if(!isset($results[0])) {
return 0; //tells caller that there are no open entries
} else {
if (count($results) === 1) {
return $results[0]; //if exactly one open entry, return that object to caller
} else {
return -1; //if more than one open entry, null will signify to caller that we have a problem.
}
}
}
But I would like to put that response-returning-business already in the private function to clean up my indexAction, but that is not possible, the indexAction will keep going past the point of
$openEntries = $this->checkOpenEntries($position);
even if checkOpenEntries attempts to return a HTTP response.
Ideally I would like it to look like this, is there a way to accomplish that:
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if($openEntries === 0) {
//do some stuff
} else {
//do some other stuff
}
}
private function checkOpenEntries($position) {
//Get all open entries for position
$repository = $this->getDoctrine()->getRepository('PoslogBundle:Entry');
$query = $repository->createQueryBuilder('e')
->where('e.stop is NULL and e.position = :position')
->setParameter('position', $position)
->getQuery();
$results = $query->getResult();
if(!isset($results[0])) {
return 0; //tells caller that there are no open entries
} else {
if (count($results) === 1) {
return $results[0]; //if exactly one open entry, return that object to caller
} else {
//Sends email to notify about the problem
$body = 'Tried to create position log entry but found more than 1 open log entry for position ' . $position->getName() . ' in ' . $position->getACRGroup()->getName() . ' this should not be possible, there appears to be corrupt data in the database.';
$this->email($body);
return new response($body . ' An automatic email has been sent to it#domain.se to notify of the problem, manual inspection is required.');
}
}
}
IMHO, it is not clean the way you mix up the type of method. However, you could do something like this, to make it work.
In addition, I think it would be better if functions and parameters have type, it would be easier to read.
public function indexAction() {
// some stuff cut out
$openEntries = $this->checkOpenEntries($position);
if ($openEntries instanceOf Response) return $openEntries;
if($openEntries === 0) {
//do some stuff
} else {
//do some other stuff
}
// you might also want to add some response here!
return new Response('...');
}

Preventing str_replace from commenting the php code that comes in the string

So I'm trying to make a website, and I'm using a php file as the index (index.php) and pretty much as the page that controls the whole website.
Since it recieves all the requests and returns the pages using str_replace, it's all working as it should (as in, it's making the web template work as it should) but the problem is I can't have php code inside the files that are part of the template, only in index.php.
So my question is, is there any way to prevent str_replace from turning the php code into comments?
Index.php:
<?php
//dirs
$pagesDir = "pages/";
$templatesDir = "templates/";
$errorsDir = "errors/";
if (isset($_REQUEST['page'])) {
if ($_REQUEST['page'] != "")
if (file_exists($pagesDir . $_REQUEST['page'] . ".html"))
$page_content = file_get_contents($pagesDir . $_REQUEST['page'] . ".html");
else
if (file_exists($_REQUEST['page'] . ".html"))
$page_content = file_get_contents($_REQUEST['pages'] . ".html");
else
echo "<h1>Page:" . $_REQUEST['page'] . " does not exist! Please check the url and try again!</h1>";
} else {
$page_content = file_get_contents($pagesDir . "home.html");
}
//PLACEHOLDER REPLACEMENT
$page_content = str_replace("!!HEAD!!", file_get_contents($templatesDir . "head.html"), $page_content);
$page_content = str_replace("!!BODY!!", file_get_contents($templatesDir . "body.html"), $page_content);
$page_content = str_replace("!!FOOT!!", file_get_contents($templatesDir . "eofScripts.html"), $page_content);
//RETURN THE CONTENT OF THE PAGE
echo $page_content;
New dispatcher after changes(this one works):
<?php
$templatesDir = "templates/";
$pagesDir = "pages/";
$loggedPagesDir = "templates/logged";
$pageExists = false;
$pageContent = null;
require_once('scripts/php/db_conn.php');
if (isset($_REQUEST['page'])) {
$page = $_REQUEST['page'] . ".php";
}
if (isset($_SESSION['redirect_reason'])) {
$dialogs->alertDialog("warningDialog", $_SESSION['redirect_reason']);
unset($_SESSION['redirect_reason']);
}
if (isset($_SESSION['user_action'])) {
$dialogs->alertDialog("infoDialog", $_SESSION['user_action']);
unset($_SESSION['user_action']);
}
if ($user->is_logged()) { //Only runs beyond this point if user is logged, if not, it will run the other one.
if (isset($_POST['logout_btn'])) {
$user->logout();
$user->redirect("pageDispatcher.php");
}
if (isset($page)) {
if ($page != "") {
if (file_exists($pagesDir . $page)) {
$pageExists = true;
$pageContent = ($pagesDir . $page);
} else {
echo "<h1>Page: " . $page . "does not exist! Please check the url and try again</h1>";
}
} else {
$pageExists = true;
$pageContent = ($pagesDir . "loggedhome.php");
}
} else {
$pageExists = true;
$pageContent = ($pagesDir . "loggedhome.php");
}
} else { //Only runs beyond this point if user isn't logged.
if (isset($_POST['login_btn'])) {
if ($user->login($_POST['email'], $_POST['password']) == false) {
$dialogs->loginFailed();
} else {
$_SESSION['user_action'] = "Welcome back " . $_SESSION['user_name'];
$user->redirect("pageDispatcher.php");
}
}
if (isset($page)) {
if ($page != "") {
if (file_exists($pagesDir . $page)) {
$pageExists = true;
$pageContent = ($pagesDir . $page);
} else {
echo "<h1>Page: " . $page . " does not exist! Please check the url and try again!</h1>";
}
} else {
$pageExists = true;
$pageContent = ($pagesDir . "home.php");
}
} else {
$pageExists = true;
$pageContent = ($pagesDir . "home.php");
}
}
?>
<html>
<?php include($templatesDir . "head.html"); ?>
<body>
<?php
if ($user->is_logged()) {
include($templatesDir . "loggedBody.html");
} else {
include($templatesDir . "body.html");
}
include($pageContent);
?>
</body>
</html>
NOTE: Do not use this method unless it's for learning purposes, its bad, can turn out to be quite hard to maintain, and probably will end up being slow since I have so many server side methods of things that I can do client side.
You read the content of page and echo it! Don't do that. Use include('file.html') instead. Just for sake of explanation, (if you have to) do sth like this:
$pages=['head.html','body.html','eofScripts.html'];
$page=$_REQUEST['page'];
if(in_array($page,$pages)) include($page);
else echo "<h1>Page: $page does not exist!</h1>";
But generally this is bad programming practice. As suggested in comments before do use a template engine.

php while loop running only once

I have a php script for check the availability of some data. I call this script from external jquery. the jquery is running fine. here is my php:
<?php
$avares = checkAva($fi_nm, $tbl_nm, $txtval);
echo $avares;
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "") or die("query failed");
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
}
?>
$curval is the variable coming from external jquery. my problem is that the while loop seems to run only once though there are lot of entries in the DB. I checked it with an integer variable and the while loop seems to run only once. can you help me to solve that?
Look at your code.
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
you have used return, if its true it returns and false then also returns change those according to your needs. The return statement immediately ends execution of the current function
It will by design as you have a return statement. From what you have said your not actually wanting it to return but to set a variable that at end of execution will return no or yes. I could be wrong on this but hey ho.
<?php
echo checkAva($fi_nm, $tbl_nm, $txtval);
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table) or die("query failed");
$noOrYes = "yes";
while ($a_row = mysql_fetch_array($avres)) {
if($curval == $a_row[$field]) {
$noOrYes = "no";
}
}
return $noOrYes;
}
?>
The possible issue that can cause Loop to iterate once are:
Error in the Variable used for the $query and $result
Same name Variable inside and outside of the Loop
Incorrect placement of Return statement
Invalid Mysql Statement
Directly put the condition in your Query like
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "
WHERE `".$field."` = '".$curVal."'");
$res = mysql_fetch_array($avres);
if(is_array($res) && count($res) > 0)
return "Yes";
else
return "No";
}
Instead of getting all the results and checking with each one of the result you directly put a condition to extract the results which satisfies your condition.This will be suggestable if you have many records.
You need to put one of the return outside of the while loop.
For example if you just wanted to check if $curval == $dbval
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
//If the condition was met return with a no
if ($curval == $dbval) {
return "no";
}
}
//If the condition was not met return yes
return yes;
That's basically what you need to do so the loop will run until your condition was met or not at all.

Javascript confirm() function cannot pass parameters properly

I'm using PHP and JavaScript, and I got a problem when deal with the confirm() function in JavaScript.
Say I have a page add.php, firstly I receive some parameters passed from another page, and I check to see if they are valid or not. If yes, I just insert the data into db and return to another page, if they are not valid, there'll be a confirm() window popped up and let the user to choose whether to continue or not. If the user still choose to continue, I want the page to be reloaded with all the parameters sent again. But the problems is that I cannot get the parameter the second time add.php is loaded.
Previously I didn't use a window.onload function and confirm() pop up, but an < a href> link instead, everything worked fine (Please see the attached code at the end). But when I tried to use the following code, the same url stopped working
echo "<script type=\"text/javascript\">";
echo "window.onload = function() {
var v = confirm(\"$name is not alive, do you want to add it into system?\");
if (v) {
window.location.href= \"add.php?type=room&name=$name&area\"
+ \"=$area&description=$description&\"
+ \"capacity=$capacity&confirm=Y\";
} else {
window.location.href= \"admin.php?area=$area\";
}
}";
echo "</script>";
Following is the previous version, instead of using window.onload(), I used < a href="..." /> link, everything worked fine at that time. get_form_var is a function in functions.inc, which is to get the parameter using $_GET arrays.
<?php
require_once "functions.inc";
// Get non-standard form variables
$name = get_form_var('name', 'string');
$description = get_form_var('description', 'string');
$capacity = get_form_var('capacity', 'string');
$type = get_form_var('type', 'string');
$confirm = get_form_var('confirm','string');
$error = '';
// First of all check that we've got an area or room name
if (!isset($name) || ($name === ''))
{
$error = "empty_name";
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
// we need to do different things depending on if its a room
// or an area
elseif ($type == "area")
{
$area = mrbsAddArea($name, $error);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
elseif ($type == "room")
{
if (isset($confirm)){
$dca_osi = getOsiVersion($name);
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
1
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
$dca_status= pingAddress($name);
$dca_osi = getOsiVersion($name);
if( $dca_status == 0){
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
0
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
print_header(
$day,
$month,
$year,
$area,
isset($room) ? $room : ""
);
echo "<div id=\"del_room_confirm\">\n";
echo "<p>\n";
echo "$name is not alive, are you sure to add it into system?";
echo "\n</p>\n";
echo "<div id=\"del_room_confirm_links\">\n";
echo "<a href=\"add.php?type=room&name"
. "=$name&area=$area&description"
. "=$description&capacity=$capacity&confirm"
. "=Y\"><span id=\"del_yes\">"
. get_vocab("YES") . "!</span></a>\n";
echo "<a href=\"admin.php?area=$area\"><span id=\"del_no\">"
. get_vocab("NO") . "!</span></a>\n";
echo "</div>\n";
echo "</div>\n";
}
}
}
function pingAddress($host)
{
$pingresult = exec("/bin/ping -c 1 $host", $outcome, $status);
if ($status==0) {
return $status;
}
else {
return 1;
}
}
function getOsiVersion($host)
{
$community = 'public';
$oid = '.1.3.6.1.4.1.1139.23.1.1.2.4';
$sysdesc = exec("snmpwalk -v 2c -c $community $host $oid");
$start = strpos($sysdesc, '"');
if ($start!==false) {
$sysdesc = substr($sysdesc, $start+1,$sysdesc.length-1);
return $sysdesc;
}
else {
return "not available";
}
}
I've solved the problem, just simply by using "&" instead of " & amp;" in the url link... it works fine now...
You try location.reload() javascript call?

Categories