Form not displaying for logged in users - php

Please i need your help with my script. I'm trying to post comments to news items on sections on my website only for users who are logged in. If they are not, they are shown a link to Login or Register, and the "Post A Comment" inputbox does not display.
Then when they login the form should display.
The form does not display, when they are not logged in, but it does not also show the form when they are logged in.
Please where could the broblem be.. Thank you for your time and patience. I apppreciate it.
<?php
if (!isset($_SESSION['username'])) {
echo "Login OR <a href=\"register.php\">Register</ a> to make a comment" ;
}
exit();
?>
<?php
if (isset($_POST['submit'])) {
//process form
}
?>
Post A Comment <br/>
<form action="<?php echo $_SERVER ['PHP_SELF']; ?>" method="post">
<textarea type="text" name = "comment_body" title='Post A Comment' class='OpenInput_Text' ></ textarea><br/>
<input type="submit" name="submit" value="Post Comment">
</form>
</div>
</div>

You will need to start your sessions.
Replace
<?php
if (!isset($_SESSION['username'])) {
With
<?php
session_start();
if (!isset($_SESSION['username'])) {

.. It's because you are exiting the script in with an
exit();
I think you want to push it one line up, to end the script if the user is not logged in.

Move the exit() inside if (!isset($_SESSION['username'])) { ... } instead of after it.

Related

How to redirect to "login page" or "buy page" depending on user login status

I am having a page where there is a button named buy.While clicking the buy button its suppose to goto buy page if the user is logged in or to login page if the user is not logged in. I am trying to implement this using "is_user_logged_in()". I have tried "header:location" which gives me a warning since i have written for get_header() initially. i have tried it using javascript but nothing seems to work.here is my code please help me.
<script>
function myfunction() {
location.reload();
}
function redirect() {
<?php if(!is_user_logged_in()){
?>
window.location.replace("login.php");
<?php
}else{
?>
window.location.replace("buy.php");
<?php }
?>
}
}
</script>
<?php
get_header();
?>
<form action="" method="post">
<div>
<br>
<input type="submit" name="delete" value="Delete" class="btn btn-primary" id="show" onclick="myfunction()">
<input type="submit" name="buy" value="Buy Now" class="btn btn-primary" onclick="redirect()">
</div>
Instead of using onClick, you can just put this php script on the top of the page.
if(isset($_POST['buy'])){
if(is_user_logged_in()){
header("Location:buy.php");
exit();
}
else{
header("Location:login.php");
exit();
}
}
//This code must be placed before any output is produced / Should be placed at the top
if ( !is_user_logged_in() && !is_page( 'login' ) && ! is_page('register') ) {
//redirect user, create account with them, do a hoola-hoop
}
Source: https://stackoverflow.com/a/44166973/4573789
There is no need to write a JS just to check user login status and redirect accordingly. You can do as directed below.
At top of page before get_header() you can write this.
if ( !is_user_logged_in() ) {
auth_redirect();
}
This if condition checks the user if logged in it will continue to load rest of the page and if user is not logged in it will force user to get authenticated via login page.

php page accessible only by passing through another php page

I am looking to develop a website containing stages. I want for example to pass by the stage 2 only when i click on the finish button in the page of stage 1 so the stage 2 page can't be accessible by its url or whatever only if the user pass by another page.
Is there a method to do this ??? i am a beginner in security so please try to help me, thanks in advance coders
Make use of sessions to develop this model.
index.php
<?php
#extract($_POST);
if(isset($sub))
{
session_start();
$_SESSION['authenticate']=true;
header("location:test1.php");
exit;
}
?>
<form action='' method="post">
<input type="SUBMIT" name="sub" value="Finish" />
</form>
open.php
<?php
session_start();
if(!isset($_SESSION['authenticate']))
{
echo "You are not allowed to access";
}
else { echo "You came from index.php ! so you are a valid user"; }
session_destroy(); //<-- I added this so you can test your example multiple times.
I think, this show work :)
Use can either redirect your user directly from index.php to open.php
header('Location : open.php');
Or,
in open.php, put this
if($_SERVER['HTTP_REFERER'] == 'index.php page's full link') {
//Do or Show whatever you want to show here
} else {
// Tell the user that you are not authorized
}
If that doesn't work, echo $_SERVER['HTTP_REFERER'] and see what link it gives you. And put that link where specified above.
Cool? :)
Edit (As per the comments) --
Lets say you have a form in your form in stage1.php
<form method="post" action="">
<span class="error"><?php echo $error; ?></span>
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" name="submit" value="Submit">
</form>
use this php in stage1.php
if (isset($_POST['name'])||isset($_POST['email'])) {
if (!empty($_POST["name"])||!empty($_POST["email"])) {
$error = "Please fill in all the fields correctly";
}
else {
$name = $_POST['name'];
$email = $_POST['email'];
//You can also save the above Variables Globally by $GLOBALS['name'] = $_POST['name'];
//So that you can use the details when you reach the final stage
header('Location : stage2 page's link');
}
}
?>
and in Page 2 lets say you have another form, then there also check
<?php
if(!empty($name)||!empty($email)) {
//the above is check for global variables email and name are not empty - means stage 2 was filled properly
//Do things for the second page's form like you did for stage 1
} else {
header('Location : stage1 page's link');
//redirect back to stage 1.
}
?>

Two PHP pages to pass form data to the same target file

I have a Customer Details PHP page. To get to this page, the user either signs up with new details on signup.php or they log in on login.php.
Ive been told the best way to submit data and be redirected to the correct page is to use action="details.php" in the form, and then at the start of the details.php file use the values from the $_POST array to populate my SQL database.
However, I need to do the same sort of thing with the login.php code, so at the top of details.php there will be the code to enter the form data from signup.php and the verifying code from login.php.
Surely there is a way of doing the data submission directly from signup.php so there isnt two sets of PHP in the details.php file? If not how do i differentiate so that login only uses the login code and signup uses the submit code?
Common practice is to have PHP check for form data+possible redirect and after that form print
Example: (my common usage)(i merged login&signup into one file)
<?php
$error = "";
if( !empty($_POST['signup']) ){
//do signup
//$signup = assign true/false whether sign up was successfull or not
if( !$signup ){ //if signup wasnt successfull generate error
$error = "Sign up error.";
}
}
if( !empty($_POST['login']) ){
//do login
//$login = assign true/false whether login was successfull or not
if( !$login ){ //if login wasnt successfull generate error
$error = "Log in error.";
}
}
if( empty($error) ){
//there were no errors
header("Location: details.php"); //redirect to details.php
exit(); //send nothing else!
}
?>
<div class="error"><?php if(!empty($error)){ echo htmlspecialchars($error); /*escape*/ } ?></div>
<form action="#" method="POST">
<input type="hidden" name="signup" value="yes">
<!-- ...some other input fields... -->
<button type="submit">Sign Up</button>
</form>
<br>
<form action="#" method="POST">
<input type="hidden" name="login" value="yes">
<!-- ...some other input fields... -->
<button type="submit">Log In</button>
</form>
You could set a hidden field on each page as below:
<input type=hidden name='referrerpage' value='signup'>
AND
<input type=hidden name='referrerpage' value='login'>
and do:
if ($_POST['referrerpage']=='signup'){
//do this
} else{
//do this
}

How to stop people accessing hidden pages where a login is required?

I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>

user invalid login

I am creating my own website just to get some experience. I've been working on it for 3 days and am at the point where I can sign up and sign in.
When signing in, if the combination of the username and password is not found in the database, my code displays an error message telling the user that either he didn't sign up yet or he is entering a wrong user email or password.
But, the message is displayed in a new page, instead of the sign in page.
I looked at some tutorials online, but didn't find a good explanation for it. Could someone please give me some advise?
I am using PHP for the database connection.
I just typed a very basic example:
<?php
//login.php
$msg = ''; //to store error messages
//check whether the user is submitting a form
if($_SERVER['REQUEST_METHOD'] == 'POST') //check if form being submitted via HTTP POST
{
//validate the POST variables submitted (ie. username and password)
//check the database for a match
if($matchfound == TRUE) //if found
{
//assign session variables and other user datas
//then redirect to the home page, since the user had successfully logged in
header('Location: index.php');
}
else
{
$msg = 'Error. No match found !'; //assign an error message
include('login_html.php'); //include the html code(ie. to display the login form and other html tags)
}
}
else //if user has not submitted the form, just display the html form
{
include('login_html.php');
}
//END of login.php
?>
login_html.php :
<html>
<body>
<?php if(!empty($msg)) echo $msg; ?> <!-- Display error message if any -->
<form action="login.php" method="post">
<input name = "username" type="text" />
<input name = "password" type="password" />
<input name = "submit" type="submit" value="Submit" />
</form>
</body>
</html>
This is not a complete code. But I just created it for you to understand how this can be done. :)
Good luck
Your opening form tag should look like this: <form action="" method="post">. The empty "action" attribute will cause the page to post back to itself. Just check the $_POST for username and password to determine whether to test for a match or just show the form.
And please be sure to hash your passwords and sanitize your inputs!
you can do it without going to a new page.
<?php session_start(); ?>
<?php
if(isset($_POST) && isset ($_POST["admin_login"])){
$user_data_row = null;
$sql="SELECT * FROM table_name WHERE <table_name.field name>='".mysql_real_escape_string($_POST['email'])."'
and <table_name.field name='".mysql_real_escape_string($_POST['password'])."'
;
$result=mysql_query($sql);
$user_data_row=mysql_fetch_assoc($result);
if(is_array($user_data_row)){
$_SESSION['user_id'] = $user_data_row['id'];
header("Location: <your page name>");
}else{
$_SESSION['message'] = "Valid email and password required";
}
}
?>
<?php if(isset($_SESSION['message'])){
echo "<li>{$message}</li>";
?>
<form action="" method="post" id="customForm">
<label>Email:</label>
<input type="text" id="email" name="email">
<label>Password:</label>
<input type="password" id="password" name="password">
<input type="submit" value="Login" id="send" name="admin_login">
</form>
may be its helps you....
Basically what you need to do, is post the form to the same page.
Once you have that, at the type just check for the $_POST: if($_SERVER['REQUEST_METHOD'] == 'POST')
If it is a post, check the username and password and either show an error or redirect to the signed in page. After this, display the login form.
So, if it's an error, they'll get the error and then the login form. If it's not posted, they'll get just the login form, and if it's a valid login, they'll get redirected to the proper page before the login form is shown.

Categories