Multiple PHP includes based on conditional statement - php

I want to include 2 files based on the following conditional statement
<?php
if (isset($_SESSION['name']) && $_SESSION['name'] == true) {
include 'file_a.php';
}else{
include 'file_b.php';
}
?>
Is this the correct way?

You can try next code:
if(session_id() == '') {
session_start();
include !empty($_SESSION['name']) ? 'file_a.php' : 'file_b.php';
}

It depends what you mean by 'correct':
If you mean 'is it valid' then yes, your code will work and there are no syntax errors.
If you mean 'can it be prettier', then perhaps it could, but it's personal preference whether you'd want to use ternary operators or not:
$toShow = isset($_SESSION['name']) && $_SESSION['name'] ? "file_a.php" : "file_b.php";
include $toShow;
Again, whether or not this is better or worse than your previous code, is down to your personal opinion.
TL;DR: Yes, your code is correct.

Related

PHP Sessions not keeping values

I have a problem with my PHP (version 5.6) session. They are not being kept between pages, or even when I refresh my page.
On top of all my files I have :
<?php
session_start();
(there is no space or anything before).
When the user click on link, it's calling a function to set the website language to English or French. After some verification on the $_GET["lang"] value, I create the session like that :
$_SESSION["lang"] = $_GET["lang"];
If I do
var_dump($_SESSION["lang"]);
the server return string(2) "fr" or string(2) "en" regarding to which language the user select. Until there, everything is working great ;)
Problem is if I refresh the page, or go to another one, and try to return the session value, it's always NULL...
I know i could user other ways to translate the website, but I need the sessions to work for other functionality of my application (login, ...)
Because it was working few days ago, I first supposed it was a changed on the server, so I've contact my server administrator, but they told me they didn't change anything.
I have the PHP error reporting set to E_ALL but no errors are displayed...
If someone could help me with that, it would be great, i'm stuck on this bug since 3 days now ^^.
Thanks !
EDIT :
session_start();
var_dump($_SESSION["lang"]);
if(!isset($_SESSION["lang"]) || $_SESSION["lang"] == null){
$_SESSION["lang"] = "fr";
}
if(isset($_GET["lang"]) && ($_GET["lang"] == "fr" || $_GET["lang"] == "en")){
$_SESSION["lang"] = $_GET["lang"];
}
var_dump($_SESSION["lang"]);
from the limited code you're providing, my guess is that the $_GET argument isn't always set, which would then set the session to null.
try this...
if(isset($_GET["lang"])) {
$_SESSION["lang"] = $_GET["lang"];
} else {
echo 'lang not set';
}
EDIT: OP provided additional code.
This will return 'fr' if no value, or if an acceptable value hasn't been provided in the URL arguments. it's similar to what you have, however, I've wrapped the argument check in parentheses to make it a little tighter and changed the order. Your code was returning 'en' if nothing was provided.
session_start();
if(isset($_GET['lang']) && ($_GET['lang'] == 'fr' || $_GET['lang'] == 'en')) {
if($_GET['lang'] == 'fr') {
$_SESSION['lang'] = 'fr';
}
elseif($_GET['lang'] == 'en') {
$_SESSION['lang'] = 'en';
}
} else {
$_SESSION['lang'] = 'fr';
}
var_dump($_SESSION['lang']);
I found it !
My index.php file was encoded in UTF-8, i changed it to UTF-8 without BOM and it worked !
Really weird bug, I hope it will help someone ;)

Multiple isset checks php

I'm trying to implement multiple if(isset()) statements but I can't get it to work.
example:
if (isset($_GET['a']) or isset($_GET['b'])) {
// HTML
} else {
// HTML
<a href="?link=a>LinkA</a>
<a href="?link=b>LinkB</a>
}
When I click a or b I still got the else statement executed.
I also tried:
if (isset($_GET['a'] or $_GET['b']))
but then I get a error
I'm trying to display different pages on different $_GET requests.
Can someone point me in the right direction or is this not the right way to do this?
Change if (isset($_GET['a']) or isset($_GET['b'])) To:
if ( (isset($_GET['link']) && $_GET['link'] == 'a') OR (isset($_GET['link']) && $_GET['link'] == 'b']) )
You are checking wrong variable.
You need to check $_GET ['link']

Need help deciphering PHP code

I am running through a jQuery Ajax tutorial here:
http://www.charlieperrins.com/2011/03/ajax-jquery-101/
Everything works perfectly but I have a question about this piece of code:
<?php if ($_POST['user']) : ?>
<?php
$user_id = $_POST['user'];
if (isset($db_data[$user_id])) {
$data = $db_data[$user_id];
} else {
echo 'Sorry, no user data matched your request - please try again';
die;
}
?>
I am most concerned with the very first line. What does that line do? I am trying to keep all the code in 1 set of php tags but I don't know how to do that. If I knew what the first line does, I might be able to figure it out. Any help is appreciated. I am trying to reverse engineer this to fit it into my app but can't do it without knowing what that top line does.
Thanks.
All this does is continues the if block until endif.
There is no endif, so nothing in this script runs unless there is data in $_POST['user'] that doesn't evaluate to false.
I would write this a bit differently:
<?php
if (isset($_POST['user'])) {
$user_id = $_POST['user'];
if (isset($db_data[$user_id])) {
$data = $db_data[$user_id];
} else {
echo 'Sorry, no user data matched your request - please try again';
die;
}
}
?>
The first line tests if the $_POST array has a key user, and that key contains a "truthy" (non-empty, among other things) value, indicating that a form was posted to this script. If no form data was posted, the rest of the script won't execute, such as if someone browsed directly to this PHP script without using the expected form to post to it. It is a technique often used when a form posts back to the same PHP script. Upon first arriving at the script, the $_POST will be empty. When the form is posted back to the same script, different actions can be taken when it contains values.
There need only be one <?php tag:
<?php
if ($_POST['user']) {
$user_id = $_POST['user'];
if (isset($db_data[$user_id])) {
$data = $db_data[$user_id];
} else {
echo 'Sorry, no user data matched your request - please try again';
die;
}
}
?>
This is Alternative syntax for control structures
<?php if ($_POST['user']) : ?> means if $_POST['user'] evaluates to true, execute the following code.
It can be compressed down to this:
<?php if ($_POST['user']) :
$user_id = $_POST['user'];
....
Also,
if ($_POST['user']) :
should be
if (isset($_POST['user']) && !empty(trim($_POST['user']))) :
That makes sure that $_POST['user'] has been set (generally $_POST contains variables from a form), and that it is not empty even with white-space removed.
See
Alternative syntax for control structures
$_POST
empty
trim
The if ($_POST['user']) line is saying this:
If the variable $_POST['user'] exists and is set to a non-false value.
The above condition fails if $_POST['user'] is 0, false, or '' (empty string).
It also isn't safely checking that value.
You are better off using:
if (isset($_POST['user'])) && $_POST['user'] != '')
This way no warning is output when PHP has display_errors and notices turned on.

PHP session variables change with file include

This question is based on a previous question I asked but is getting messy with edits as I was not sure where the problem could come from. (Please advise if this question needs to be closed)
I develop with PHP 5.3.3 on development environment + Apache 2 (my code works there)
The production server has PHP 5.2.6 and the same server (same code doesn't work here)
Thanks to Melsi on the other question I managed to narrow down the problem to a few lines of code.
The problem is: In an include file I start a session and check for a variable.
Depending on that session variable I include a language file.
The structure is like this:
-index.php
INCLUDE
-menus.php
-lang_fr.php
-lang_en.php
The files are as follows:
INDEX.PHP
<?php
//SET LANGUAGE
if (isset($_GET['lang']) && $_GET['lang'] == 'fr') {
$_SESSION['lang'] = 'fr';
}
else if (isset($_GET['lang']) && $_GET['lang'] == 'en') {
$_SESSION['lang'] = 'en';
}
else {
$_SESSION['lang'] = 'en';
}
include_once 'include/menus.php';
?>
<html>
<head>
<title>building...</title>
</head>
<body>
<?php
echo($links);
?>
<br><br>
print_r($_SESSION);
<br><br>
<?php
print_r($_SESSION);
?>
</body>
</html>
MENUS.PHP
<?php
session_start();
if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'en') {
include_once('lang_en.php');
}
else if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'fr') {
include_once('lang_fr.php');
}
else {
$_SESSION['lang'] = 'fr';
include_once('lang_fr.php');
}
$links = <<<EOT
English
French
EOT;
?>
LAN_EN and FR.PHP
<?php
$lang['test'] = "Test";
?>
This on my local server works and displays the correct session variables when I click on the links.
On the production server I get:
-First load: Array ( [lang] => fr ) (default, correct)
-Click on English link: Array ( [lang] => Tn )
-Click on the French link: Array ( [lang] => Tr )
If I change in the language file 'Test' to 'Pest', the results above are 'Pn' and 'Pr'
I would like to know if there's something wrong with the code or with the configuration production server (according to their support there is nothing wrong) and if so what could be the problem.
Note: The problem disappears when I remove the includes in menus.php
The problem in your code is that you as setting the Setting variables and in Index.php but Starting the Session in Menu.php file. Kindly change thing to:
Index.php
<?php
ob_start();
session_start();
//SET LANGUAGE
if (isset($_GET['lang']) && $_GET['lang'] == 'fr') {
$_SESSION['lang'] = 'fr';
}
else if (isset($_GET['lang']) && $_GET['lang'] == 'en') {
$_SESSION['lang'] = 'en';
}
else {
$_SESSION['lang'] = 'en';
}
include_once 'include/menus.php';
?>
<html>
<head>
<title>building...</title>
</head>
<body>
<?php
echo($links);
?>
<br><br>
print_r($_SESSION);
<br><br>
<?php
print_r($_SESSION);
?>
</body>
</html>
MENUS.PHP
<?php
if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'en') {
include_once('lang_en.php');
}
else if(isset($_SESSION['lang']) && $_SESSION['lang'] == 'fr') {
include_once('lang_fr.php');
}
else {
$_SESSION['lang'] = 'fr';
include_once('lang_fr.php');
}
$links = <<<EOT
English
French
EOT;
?>
I Think this would resolve your problem
If you look closely to my answearin your previous question the very first thing mentioned (written in bold) was exactly this:
Maybe a session is started from a file that is included and this should not happen!
Vineet is correct and I will expand his right answear a bit more!
When you include the file child.php into the father.php you must think of the code found in child.php as being part of father.php One of the first things you do in a father.php script (like index.php) is a session start. You do not start a session in an included script because this might create some conflict as an other session could have been started already.
And if you have many files, (even worse if some of them are both included or executed directly cause of no single entry point) then how easy is to manage all this?!
You said this:
Thanks but the problem doesn't come from the structure of my site
Well this might not be entirely true! The thing is that writing old school code (no mvc, no single entry point, not really object oriented) has the benefit that has a very easy learning curve. HOWEVER while such code is easy to write the thing is that such code requires more skills to avoid errors!
On the other hand the object oriented aproach has more difficulty to get started cause there are more things to learn (objects, prototypes, interface, relatinships (belong-to, is part of) etc etc ) and requires a different behaviour. HOWEVER you definetely will benefit more!
A last thing! Well a well structred-site makes the session manage a thing of a few lines, writen only once at the very begining and that's it all.
I am glad that you are twoards solving you problem!

php redirect based on url variable

I want to create a URL redirect based on a URL variable.
so, if student%20gender (student gender) is male then go to www.one.com, if female, go to www.two.com.
couldn't figure this one out yet. any help?
Question could use a little bit of a better explanation. Do you mean that someone is going to
http://www.yoursite.com/yourscript.php?student%20gender=male and you want them to be redirected to http://www.one.com?
If this is the case, PHP has a built in variable known as $_GET which stores the values listed after a ? in a URL. So in the above example, we'd see:
$_GET['student gender'] = male;
You can use this to access any number of parameters separated by &
So the URL http://www.site.com/index.php?val1=a&val2=b&val3=c would give us:
$_GET['val1'] = a;
$_GET['val2'] = b;
$_GET['val3'] = c;
After this, to do a redirect in PHP the easiest way is to send a Location: header. This is done like so:
<?php
header("Location: www.newsite.com");
?>
Combining this with our $_GET variable and some simple logic:
<?php
if($_GET['student gender'] == 'male'){
header("Location: www.one.com");
die();
} else {
header("Location: www.two.com");
die();
}
?>
$var = $_GET['yourvar'];
if($var == 'one'){
header("Location: http://www.one.com/");
}else if ($var == 'two'){
header("Location: http://www.two.com/");
}
then do http://www.yoururl.com?yourvar=one
You also have to make sure you look at the security aspects here, the best way yo accomplish this is
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender'] : false;
switch($gender)
{
default: //The default action
//Send back to the gender select form
break;
case 'male':
//Send to male site!
break;
case 'female':
//Send to female site!
break;
}
This should be sufficient, but please never use $_X['?'] in functions that execute either shell or database queries without sanitation.
Note: _X being (GET,POST,REQUEST,FILES)

Categories