In this case, I am going to echo/print two different page view in the same page, which it depends on whether the user has logged-in or not.
If the users are logged in, they can find all the menus in the page. However, if the user are not logged in, there would be some views I want to hide from them.
The method that I am going to use is:
First: check if the user has login or not (with session),
Then: show the page based on the result of the check of session.
And I will use this code:
<?php
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
?>
YOUR HTML CODE
<?
} else {
?>
YOUR HTML CODE
<?}
?>
My question actually is very simple, I just want to make sure, if I use this method, won't it make the page to load slow?
If this will make the page to load to slow, is there a good method for I to achieve this?
Thanks
It won't make your page slow (any code in the if-else block that isn't processed won't make any difference to the load time).
You might, however, wish to include a separate PHP file with the information you want to display, rather than code it directly into the if-else block. For example;
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
include 'loggedin.php';
}
else {
include 'notloggedin.php';
}
Hope this helps.
Your page load is really going to depend more on the html then this php switch. I have dealt with pages with 30 switches like this on one page load. While not the best practice anymore you likely wont even notice.
Related
I’ve been battling with this for hours, I wonder if anyone can help.
I want to make a redirect script which first actions a link. I have a link generated by php which deletes the current user’s avatar. This link works (user avatar is deleted) however the link itself doesn’t lead anywhere, it just reloads whichever page it is launched from (I haven’t quite worked out how yet, I presume this is a feature of wordpress/buddypress which I am using). My aim is that on arrival to a particular page (page1.php), the delete avatar link is automatically actioned, and then the user is redirected to another page. So:
1) User arrives at page1.php
2) Script fires this link :
<a href="<?php if ( bp_get_user_has_avatar() ) : print 'mysite.net/members/'; echo userpro_profile_data('user_login', $user_id2); print '/'; bp_avatar_delete_link(); else : 'something-else.php'; endif; ?>"></a
3) User redirected to page2.php
I guess there may be some way to do this in javascript/ajax but I hardly use it so not really sure how. I’m struggling to get it to work in php also. Any help would be really appreciated.
Thanks.
You can redirect the page via Javascript using Location API:
<script type="text/javascript">
window.location = <?= $new_location ?>;
</script>
Or you can do it in PHP after performing required operations using code like this:
header("Location: {$new_location}");
But notice that if you redirecting via headers you should not echo enything to the page before it.
Or you can use wp_redirect() if youre doing it in Wordpress.
I'm trying to create a link that takes the user to two different pages depending is the user logged or not. Problem is I'm still new to programming and this is quite big bite for beginner like me but its something I have to do. I created something like this so far but either way I suck at searching or there just isnt specific information for what I need
<?php if($userLogged){
echo '<a href="index.php" class="stylelink">';
}
else
{
echo '<a href="index1.php" class="stylelink">';
}
echo "Etusivu</a>";
?>
I'm also using Dreamweaver's login function that creates the MM_Username session and such, and Im not sure how to make the condition. userLogged is still an empty variable. Id appreciate any advice.
Thanks
-John
well, instead of using echo statements in the php tag you can write html and use php for outputting the value of the page like this
Etusivu
The $_SESSION['MM_Username'] works if you have included session_start(); at the beginning of the page and you can use the condition as above instead of $userLogged.
I want to show different div with different contents in different condition.
If customer is logged in, then show content A,
If customer is not logged in, then show content B,
This is the script I have, not sure it is correct or not.
<?php if (!$logged) {
$disp_div=1;
} else {
$disp_div=0;
} ?>
This is the jQuery
<script type="text/javascript" >
$(document).ready(function(){
var show=<?php echo $disp_div; ?>
if(show==1)
{
$('#div_logged_in').show();
$('#div_not_logged_in').hide();
}
else if(show==0)
{
$('#div_logged_in').hide();
$('#div_not_logged_in').show();
}
});
This is the HTML
<div id="div_logged_in">
Content A
</div>
<div id="div_not_logged_in">
Content B
</div>
A: Why !$logged is wrong:
You use a local variable. Next time your user refreshes the page he won't be logged in anymore. For that you can store variables in a array called $_SESSION . This array is saved for a client session on you webserver. As longs as the user stays there it will always remain the same (until YOU change it). For that you need a session_start(); in the first line of you main PHP script.
B: Why the javascript part is a security leak:
Your website is designed not to filter the content that is sended to the user. Every user gets the whole content, just the visibility is changed. In this way every advanced user can just look into your code and see all the secrets you want to hide.
C: What is the right way?
It just some PHP that echos HTML without Javascript and uses $_SESSION:
<?php
if($_SESSION["loggedIn"] == "yes") { //You have to set that somewhere else just like $logged
?>
<p> You ARE logged in. </p>
<?php } else { ?>
<p> You ARE NOT logged in. </p>
<?php
}
?>
I don't know what is $logged. If it is the variable to find whether the user is logged in, then your condition is just opposite of your requirement. You are showing div_logged_in when the user is not logged in from this condition.
if(show==1)
{
$('#div_logged_in').show();
$('#div_not_logged_in').hide();
}
The value of show will be 1 when $logged is false. So change the condition and you will get it. In this scenario, i would suggest you to go with SESSIONS. You can use anywhere to check whether the user is logged in or not.
First off, you need to start reading about sessions and the $_SESSION superglobal.
After that, throw that script away, and look for a proper tutorial, I found a very nice one here: http://net.tutsplus.com/tutorials/php/a-better-login-system/ - though it may be a bit advanced since it talks about ACL, which you probably won't need.
But if you can try and understand the rest of the tutorial, you should be fine. Good luck!
Please do not depend on client-side validation because its a security flow within your application, what if the customer viewed the source code for your page? then they see hidden contents.
Your approach is correct but you have to use $_SESSION or $_COOKIE not if (!$logged) and as I said, do not out put the content totally.
use
if($_SESSION["username"])
you can set it in the login.php file
and destroy it by using session_destroy() on the logout.php
In the settings.php i have some input for the realname,hobby,city and select tag for the languages
The html form is easy and i'm not going to copy it :)
This is the php code for the form
<?php
if(isset($_POST['submit'])){
if($this->edit->process()){
$s = 1;
}
}
if($s){echo '<p id="success">Success</p>';}
?>
This is in the view file and when the form is submit the $this->edit = the model for the updating the user data.
Everything work really good but in head.php there is this code
<?php $lang = $this->lange('global',$this->getUser->language($_SESSION['userID']));?>
With him this get the user current language and after that load the file with lange()
So if the submit is like this,the inputs and select tag are changing with what the user have choicen but the to see the new language they have to refresh the page. This is not good,because the user may be confuced that they did something wrong.
But if the form with method="POST" the page is refreshing and still with the old language
It is going to be quite hard to change all the texts in the DOM model to make the language change without redirect. I doubt it's really your desire.
You ought to make a GET method redirect after processing any POST form. So, instead of printing whatever "success" messages you have to reload the page.
Using session to store the language is not good method, the language have to be set by means of the page address - a subdomain (preferable) or a virtual directory.
I have a php file that contains a HTML form, then PHP logic, then an HTML footer...in that order.
I am trying to get the values from the form into some php validation logic in the botton of the page (but before the footer) using <?php VALIDATION LOGIC HERE ?>.
the problem is when the validation finds an error, the php logic will die() and hence, my HTML footer will not be executed.
is there a way to get my HTML footer to execute despite my php die();? ...or is there a better overall way to integrate my HTML and PHP? Thanks! Anyhelp would be much appreciated.
EDIT:
I actually have die() almost everywhere in my code where I am about to connect to a database. If the user credentials are correct, they connect..if credentials are wrong then it will die()..
Is this good practice and use of die()? it seems the solution to my problem is to use return() INSTEAD OF die()...in order to continue processing the HTML footer.
Also, I have situations such as mysql_connect() or die(). How can i would continue processing the remaining HTML page when die() is executed before the HTML is processed? ..i don't think mysql_connect() or return; is good practice right?
Thanks so much again in advance! The feedback has been very helpful!
As other states, you should have multiple files; header.php, index.php, footer.php, formvalidator.php.
In your index.php file, you should include header.php and footer.php.
In the form tag, action is sett to load formvalidator.php
In the form validator script, you could have something like this:
// All form fields are identified by '[id]_[name]', where 'id' is the
// identifier of the form type.
// The field identifier we want to return is just the name and not the id.
public function getFormData() {
$formData = array();
foreach ($_POST as $key => $value)
{
// Remove [id]_
$name = preg_replace('!.*_!', '', $key);
if (is_array($value)) {
$formData[$name] = implode(',', $value);
} else {
$formData[$name] = $value;
}
}
return $formData;
}
Now you can loop through the array and validate each field.
If you find an error, echo an error message, otherwise process the form.
Update
Answer to your update.
You should "never" use die(). Instead, exit thefunction you are in and return an error message. If you simply die(), you never know what went wrong where.
It is not possible to do server validation of a form unless you click the submit button.
You can put the code I gave you in the same PHP file as the form, and when you submit, you simply reload the same page (just set action="<?= $_SERVER['PHP_SELF'] ?>")
If you want to validate fields before submit, you must to this using javascript, like e.g. jQuery.validate.
Hmm... seem like you need some more knowledge of how to mix PHP with HTML.
Take a look at this beginners guide on how to work with forms in PHP.
I would use an external file for form processing and validation, then redirect back to the form page on error/success, displaying an error/success message.
I just make one header.php and one footer.php file. If there is an error just return instead of die.
This way at the top of your page you can just put:
<?php include('header.php');?>
///put in whatever html there may be
<?php
/// put your form and processing info here
///just return if you need to prevent further processing
?>
///put in whatever html there may be
<?php include('footer.php');?>
there are many better ways to do what you are doing. but to answer your first question, you can create a function called footer that returns a string with html needed to be displayed in the footer and call the die(footer()); but... why do you use die ? can't you just count the errors and display them somewhere in the result ? you should not kill the script that way.
And for the second question. you can use as BenTheDesigner said, a html page with the form action pointing to a php script that validates and either returns to the form if something went wrong or go somewhere else if not. but there too, you should remove the die() function and call something else to redirect you. you can use a template system like smarty to separate your logic from your html presentation. you can write it all in a single file but try to write you're entire logic at the top of the file and all the html at the bottom. and use <?=$var?> to display php stuff, or simple conditionals for diferent html results. but don't use die(). it just complicate things I guess.
Using die() is not a good practice because it will not show a friendly message to the user visiting your site. You should be absolute sure you want to use die. For example, you may use it in procedures when you suspect there is a hacking attempt. Instead try to use if else structure to show or hide things. Here is the possible prototype that you may want to implement:
// if there is a validation error, show it, otherwise not
if ($error == true)
{
// show footer
}
<!-- Your footer goes normally here -->