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>';
}
}
?>
Related
On a blog I'm coding the admin can edit existing posts.
I want to let an error-message appear when the $_POST['title'] for e.g is empty(There will be displayed:"Your post should have a title"). I also do it if the subheading, content or category are empty.
The errors work just fine if one or some of them is/are empty. As soon I load the page to edit a post every error is displayed from the beginning.
How do I make them only appear when one or some $_POST's are empty after the <input type="submit .../> is clicked (they shouldn't be there when the site has loaded)?
This is the function in the PostsAdminController.php that checks the $_POST's and renders the site:
public function edit()
{
$error = "";
$id = $_GET['id'];
$entry = $this->postsRepository->find($id);
$categoryFId = $this->categoryRepository->getOneCatFromId($entry->c_Id);
$savedSuccess = false;
$abort = false;
if ($this->loginService->check()) {
if (!empty($_POST['title'])) {
$entry->title = $_POST['title'];
} else {
$error .= "Your post should have a title.";
$abort = true;
}
if (!empty($_POST['subheading'])) {
$entry->subheading = $_POST['subheading'];
} else {
$error .= "A good subheading is nothing you should just leave out.";
$abort = true;
}
if (!empty($_POST['content'])) {
$entry->content = $_POST['content'];
} else {
$error .= "Your post should have content, you know, it wouldn't be a 'post' then.";
$abort = true;
}
if (!empty($_POST['category'])) {
$entry->c_Id = $_POST['category'];
}
if ($abort == false){
$this->postsRepository->update($entry);
$savedSuccess = true;
}
} else {
$error = "You have no permission to do this, how the hell did you get here?";
}
$this->render("post/admin/edit", [
'entry' => $entry,
'error' => $error,
'savedSuccess' => $savedSuccess,
'categoryFId' => $categoryFId
]);
}
I really hope someone can help me with this, I don't know what I could to to let them only disappear when the POSTS have already been send..
You have to check if there was a POST action use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
in your case
...
if ($this->loginService->check()) {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['title'])) {
...
}
}
}
My code in PHP is pretty long and I want to make it shorter with creating one function with different values and than I would just write one line with function name instead of many lines of code, but it doesn't seem to work.
This is that repeating code:
if (!isset($_POST['ID_user']) || empty($_POST['ID_user'])) {
$_SESSION['ID_user_missing'] = "error";
header("location: index.php");
} else {
$ID_user = $_POST['ID_user'];
}
if (!isset($_POST['meta_name']) || empty($_POST['meta_name'])) {
$_SESSION['meta_name_missing'] = "error";
header("location: index.php");
} else {
$meta_name = $_POST['ID_user'];
}
if (!isset($_POST['meta_value']) || empty($_POST['meta_value'])) {
$_SESSION['meta_value_missing'] = "error";
header("location: index.php");
} else {
$meta_value = $_POST['meta_value'];
}
And this was the plan, instead of that code up ther, I would just have this down below:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
$$value = $_POST[$value];
}
}
ifIssetPost('ID_user');
ifIssetPost('meta_name');
ifIssetPost('meta_value');
But it just doesn't work, when you try to echo for example variable $meta_name it shows that it's empty. Can you help me ? Thank you very much.
NOTE: when I doesn't that function and do it the long way, everything works just fine, but the problem comes when I use that function.
The variable is in the scope of function. That's why you cannot access to it outside the function. You could return the value:
function ifIssetPost($value) {
if (empty($_POST[$value])) { // Only empty is needed (as pointed out by #AbraCadaver)
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
exit; // add exit to stop the execution of the script.
}
return $_POST[$value]; // return value
}
$ID_user = ifIssetPost('ID_user');
$meta_name = ifIssetPost('meta_name');
$meta_value = ifIssetPost('meta_value');
You can also follow your specification, using $$value:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
return $_POST[$value];
}
}
$value = 'ID_user';
$$value = ifIssetPost($value);
echo $ID_user;
$value = 'meta_name';
$$value = ifIssetPost($value);
echo $meta_name;
You can use an array to iterate over the $_POST vars. If you want to declare a variable using a string or another variable containing an string, you need to use {}. like ${$value}
$postValues = ["ID_user", "meta_name", "meta_value"];
foreach ($postValues as $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value."_missing"] = "error";
header("location: index.php");
} else {
${$value} = $_POST[$value];
}
}
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.
I've got a 'shoppingcart' page and if they modify any values there and then click on 'order' i want the session to actually store the information before i header to the next page, however it seems that the $_SESSION variable does not save it before starting.
I have tried the following:
Solution 1:
$_SESSION['winkelwagen'] = $winkelwagen;
session_write_close();
header("Location: checkout.php");
Solution 2:
$_SESSION['winkelwagen'] = $winkelwagen;
header("Location: checkout.php");
exit();
However, neither of these seem to work for me, i have tried looking at the following stackoverflow topics too:
PHP: session isn't saving before header redirect
Header Not Working With Sessions
however neither of these work, this is my code:
$header = false;
if(isset($_POST['moveForward'])) {
foreach($winkelwagen as $key => $val) {
if (isset($_POST['aantal' . $val['artnr']])) {
if (isset($_POST['verpakking' . $val['artnr']])) {
$verpakking = $_POST['verpakking' . $val['artnr']];
$aantal = intval($_POST['aantal' . $val['artnr']]);
if ($val['amount'] !== $aantal) {
$val['amount'] = $aantal;
$winkelwagen[$key]['amount'] = $aantal;
}
if ($val['verpakking'] !== $verpakking) {
$val['verpakking'] = $verpakking;
$winkelwagen[$key]['verpakking'] = $verpakking;
}
$header = true;
}
}
}
$_SESSION['winkelwagen'] = $winkelwagen;
session_write_close();
if($header) {
header("Location: checkout.php");
exit();
}
}
Any help would be appreciated!
How to add statement, when I search and it doesnt exist on the url, it will show nothing.html?
$url1 = "http://www.pengadaan.net/tend_src_cont2.php?src_nm=";
$url2 = $_GET['src_nm']."&src_prop=";
$url3 = $_GET['src_prop'];
$url = $url1.$url2.$url3;
$html = file_get_html($url);
if (method_exists($html,"find")) {
echo "<ul>";
foreach($html->find('div[class=pengadaan-item] h1[] a[]') as $element ) {
echo ("<li>".$element."</li>");
}
echo "</ul>";
echo $url;
}
else {
}
There are two ways to move to another page in PHP. you can do header("Location: http://www.yourwebsite.com/nothing.php"); or you can have PHP echo JavaScript to do a reidrect (if you already defined your headers):
if (method_exists($html,"find")) { // If 'find exist'
...
} else { // Otherwise it does not exist
header("Location: http://www.pengadaan.net/nothing.php"); // redirect here
}
Or if you already sent you headers you can get around it using JavaScript:
...
} else {
echo '<script>window.location.replace("http://www.pengadaan.net/nothing.php")</script>';
}