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];
}
}
Related
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>';
}
}
?>
I have that code and it work fine:
if (isset($_POST['submit1']))
{
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
include_once('./token.php');
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php'); //**PAGE WITH SUBMIT1**
}
token.php
$form_token = uniqid();
$_SESSION['user_token'] = $form_token;
The form in my1page.php contains:
<input type="hidden" name="user_token" value="<?php echo $_SESSION['user_token'];?>">
Now i need to nest a second if isset submit (token must be unset in the last submit).
WHAT I TRIED WITHOUT SUCCESS
if(isset($_POST['submit'])){
$_SESSION['submit']=true;
}
if (isset($_POST['submit']) || ( isset($_SESSION['submit']) && $_SESSION['submit'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit1'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
$_SESSION['submit']=false;
include_once('./script/token.php');
include_once('./my3page.php');
} else {
header("location: ./3.php");
}
}
include_once('./my2page.php');
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
HTTP works stateless. That means that what is happening here is the following:
User calls this page for the first time. He sends a GET request so isset($_POST['submit1']) is false.
Now he clicks on submit and sends the first POST request. (I assume that you set a value for submit1 there.) isset($_POST['submit1']) is true and my2page.php gets returned.
He sends the third request. Again a POST request, but this time with a value for submit2. Your server template engine starts evaluating the php. isset($_POST['submit1']) is false, so it returns the old my1page.php
Basically, don't nest your checks, but use a it else instead. (Think of it as a switch/case
isset($_POST['submit1']) → ./my2page.php
isset($_POST['submit2']) → //end page
none → ./my1page.php
You can't have 2 submits in the same time so what happens here is
if(condition){
if(!condition){
//do somthing
}
}
this will never works try to use another page or i advice to save the first submit in the $_SESSION;
ADD this lign
$_SESSION['submit1'] = (isset($_POST['submit1']))? true: false;
than change the first condition
if (isset($_POST['submit1']) || $_SESSION['submit1']) {
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit2'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
$_SESSION['submit1']=false; //or unset($_SESSION['submit1']);
//DO SOMETHINGS
} else {
header("location: ./index.php");
}
}
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
This is how it should be;
if(isset($_POST['submit1'])){
$_SESSION['submit1']=true;
}
if (isset($_POST['submit1']) || $_SESSION['submit1']) {
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit2'])) {
if($_SESSION['user_token'] == $_POST['user_token']) {
unset($_SESSION['user_token']);
$_SESSION['submit1']=false; //or unset($_SESSION['submit1']);
//DO SOMETHINGS
} else {
header("location: ./index.php");
}
}
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
Your close you could possible just change this
if (isset($_POST['submit1'],$_POST['submit2'])) { //check isset on both
if($_SESSION['user_token'] == $_POST['user_token']) {
if (isset($_POST['submit2'])) {
// if($_SESSION['user_token'] == $_POST['user_token']) { <--redundant check
unset($_SESSION['user_token']);
//DO SOMETHINGS
}
include_once('./my2page.php'); //**PAGE WITH SUBMIT2**
} else {
header("location: ./index.php");
}
} else {
include_once('./token.php');
include_once('./my1page.php');
}
Depending on if you want an AND or an OR the above is equivalent to this
if (isset($_POST['submit1']) && isset($_POST['submit2'])) {
Obviously if you want an or then just put it here
if (isset($_POST['submit1']) || isset($_POST['submit2'])) {
It's not clear if you are talking about 2 POST's that are separate or concurrent
I', trying to update a row on parse using PHP. I'm using this function:
if (isset($_GET['updateHistory']))
{
updateHistory($_GET['updateHistory']);
}
if (isset($_GET['yesNo']))
{
yesNo($_GET['yesNo']);
}
function updateHistory($obId,$yesNo) {
$bool = "";
if ($yesNo == "YES") {
$bool = true;
} else {
$bool = false;
}
$query = new ParseQuery("TestObject");
try {
$history = $query->get($obId);
$history->set("isHistory", $bool);
$history->save();
} catch (ParseException $ex) {
echo "Error Updating History";
}
reload();
}
The problem now is I can't pass the 2nd variable which is $yesNo using
<a href='?updateHistory=$obId&yesNo=YES'>YES</a>
How can I pass the 2nd variable? thanks!
try
if (isset($_GET['updateHistory'], $_GET['yesNo'])) {
// you should sanitize your $_GET values before using them
updateHistory($_GET['updateHistory'], $_GET['yesNo']);
}
Since your function depends on both variables being set, combine the if-statement to check both fields and do a single call to your function:
if (isset($_GET['updateHistory']) && isset($_GET['yesNo'])) {
updateHistory($_GET['updateHistory'], $_GET['yesNo']);
}
You can then drop this part altogether:
if (isset($_GET['yesNo']))
{
yesNo($_GET['yesNo']);
}
im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
I have the following code which checks the post for a "no" and if it exists prints and error or if not it redirects. It currently redirects everytime regardless of the fact the post array has 'NO' as a value.
if($_POST["minRequirementsForm"] == '1') {
foreach($_POST as $key => $value) {
if ($value == 'no') {
$error = 1;
} else {
header('Location: mysite.com/app-stage1.php');
}
}
//print_r($_POST);
}
Just use the header call after the loop, and check for $error:
$error = false;
if($_POST["minRequirementsForm"] == '1') {
foreach($_POST as $key => $value) {
if ($value == 'no') {
$error = true;
}
}
}
if (! $error) {
header('Location: mysite.com/app-stage1.php');
}
Notice that this uses the type boolean instead of an integer for the variable $error, which is more appropriate.
Don't use it as you did. Just write:
if (in_array('no', $_POST)) { $error = true; }
if (!$error) { header('Location: mysite.com/app-stage1.php'); }
It's better to use an already existing functions in php than reinvent the wheel.
Or use the following, which is more appropriate:
if (!array_search('no', $_POST)) { header('Location: mysite.com/app-stage1.php'); }
It redirects because of the subsequent values of non "no" strings. It echos the error, but due to next value, it redirects. Try exiting in the if(no) condition and you will see the error.