Passing a PHP variable - php

I have the following php code below...
if ($username == 'fredk')
{ $fname = 'Fred'; }
else if ($username == 'arbonk')
{ $fname = 'Arbon'; }
else if ($username == 'arsalana')
{ $fname = 'Arsalan'; }
else if ($username == 'minhn')
{ $fname = 'Minh'; }
else if ($username == 'nathanielg')
{ $fname = 'Nathaniel'; }
$msg = "Hi $fname, your login was successfull. <p></p>";
All i want to do is pass the $fname variable onto the next php page. On the same page I also have a form and when the submit button is clicked it goes onto the next page.
Anyone have any ideas??

Look into sessions. They're used for the exact reason in your example (persistent login credential data + more).
session_start(); // Do this at the very start of your script (on both pages).
$_SESSION['your_key_here'] = 'blah'; // value may be an object as well.
on the next page you can access it:
print_r($_SESSION['your_key_here']);

Put it into the session.

Session is the way to do that...

Or you can put the variable into the form as a hidden variable
<input type='hidden' name='who' value='$fname>
but, this is just for completeness sake,
I would probably use a session myself.

use session variable and put the fname in session.

Looks like you need to use $_POST
for example if this is your form code:
<form action="page.php" method="post">
<input name="fname" type="hidden" value="$fname" />
</form>
On page.php you would retrieve the fname variable like so:
$fname = $_POST['fname'];

Where does $username come from? Could you perhaps write a function that takes $username as a parameter and returns $fname, and call it on both pages?

Related

Where is the words in ' ' located?

I am learning php, (absolute beginner) and want to know where the words in '' are located. I downloaded a code from online for a login system and am trying to learn how it works. Here is the code portion:
<?php
// any HTML input *must* be HTML-escaped to prevent the user from injecting malicious JavaScript code
function html_escape($raw_input, $encoding)
{
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}
/* Displays user information and some useful messages */
session_start();
if ($_SESSION['logged_in'] != 1) {
$first_name = 'Guest, Please Login or Sign Up to Play!';
$last_name = '';
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
}
?>
So where it says, "if ($_SESSION['logged_in'] != 1) {", when it says logged_in, where would that be defined? Is it defined in another file with the $logged_in, or what?
Also, i found some file where it says "$_SESSION['logged_in'] = true;" but i don't know if it means something, if it does please tell me!
Thanks so much.
(i'm a beginner so go easy on me please)
You can store data in $_SESSION variables after session_start(); and assign values to it with:
$_SESSION['keyname'] = 'value';
You can write apostrophe (') or double quote (") to save string variables.
More informations here: http://php.net/manual/de/reserved.variables.session.php
Your code if ($_SESSION['logged_in'] != 1) is just a boolean check if $_SESSION['logged_in'] is set to 1 (true) or 0 (false).
So it checks your $_SESSION array with the key logged_in if 1 is set or not.
I hope I could help you with that?
In the code you shown, this is the check login step in login process. In login process, there is two step we need to do:
Check login: determine that current session is logged in or not. If not, shown/redirect to login page.
Login page: is used to input username & password and check inputed value. If username & password is correct, we save a value to $_SESSION to flag this user is logged in.
To find how the $_SESSION['logged_in'] is set, you must find in your downloaded code the check login section.
In general this can be simple as:
if ($_POST['username'] == 'abc' && $_POST['password'] == 'xyz') {
$_SESSION['logged_in'] = 1;
// some code to refresh or redirect to main content
}
I hope this will help you!
Assume you have form with field 'username' and 'password' at HTML:
<form action='login.php' method='post'>
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' value='Login'>
</form>
after clicking 'Login' button you will run login.php:
<?php
$allowedUser = 'johnny';
$allowedPass = 'mypassword';
session_start();
if (($_POST['username']!= '') && ($_POST['password'] !=''))
{
if (($_POST['username'] == $allowedUser) && ($_POST['username'] == $allowedPass))
$_SESSION['is_loged'] = 1; // session variable will be set when you have allowed credentials
}
?>

Setting a session through php and selectively loading html

I'm new to php and web server technology so please bear with me. I'm trying to have a webpage that has a form. The form is submitted and if the data is correct it reloads and loads different html. Here's my code:
<?php
session_start();
$_SESSION['user'] = "";
$_SESSION['pass'] = "";
echo "This is the front page. Please input your data";
if($_SESSION['user'] != 'asdf'){
$html = file_get_contents('scripts/login.html');
echo $html;
$_SESSION['user'] = $_POST['user'];
}
if($_SESSION['user'] == "awedes"){
$html = file_get_contents('scripts/strsd.html');
echo $html;
}
So far I think this is good. I have a form, and with a login, it says submit. I want the page to reload, but this time I want to set the SESSION['user'] = to the input. The form will look something like this:
<form action="/" method="post">
<input type="text" name="user" value=""/>
<input type="submit" value="Submit"/>
</form>
My question: How can I set the SESSION['user'] so that when I click form submit the 'user' input becomes the SESSION.
Thanks
In your code,
Please remove session initialisation lines
$_SESSION['user'] = "";
$_SESSION['pass'] = "";
Reason is, whenever you submit the form session get empty so that below condition not working and also make sure
if($_SESSION['user'] != 'asdf')
above line, will it need to work on if empty user value?,
echo "This is the front page. Please input your data";
if($_SESSION['user'] != 'asdf'){
$html = file_get_contents('scripts/login.html');
echo $html;
$_SESSION['user'] = $_POST['user'];
}
if($_SESSION['user'] == "awedes"){
$html = file_get_contents('scripts/strsd.html');
echo $html;
}

PHP: post to self, page variable not responding until a hard refresh

I'm submitting a FORM to itself using action="" but what's odd is that my variables are updating after the submission.
<form action="" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
Once this has been submitted and the user successfully logged in, the rest of the page doesn't seem to respond to the updated variables unless I hard refresh.
if ( isset($_POST['found_step_1']) ) {
global $wpdb;
// We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['username']);
$password = $wpdb->escape($_REQUEST['password']);
$remember = $wpdb->escape($_REQUEST['rememberme']);
if ($remember) {
$remember = "true";
} else {
$remember = "false";
}
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$login_data['remember'] = $remember;
$user_verify = wp_signon( $login_data, true );
if ( is_wp_error($user_verify) ) {
echo "Invalid username or password. Please try again!";
$current_step = 1;
} else {
//echo "<script type="text/javascript">window.location='". get_bloginfo('url') ."'</script>";
$current_step = 2;
}
$wpdb->flush();
}
When the page below renders... it's like it's rendering what WAS there before the POST ... the only way to get it to display what the latest data consists of is to hard refresh the page. It's really odd.
EDITED
You need to make the login process one of the first things your script does. I once had similar problems and then found out that I was making the login process too late in my script. I will put a practical pseudo-example that will NOT work as intended:
<?php
if (in_array("Maths",$Subjects) $MainSubject="Maths";
if ($_POST['name'] == "Admin" && $_POST['password'] == "MyCoolPassword!")
{
$Lang=en;
$Subjects = array ("Maths","Physics","English");
}
echo $MainSubject;
?>
This is a too simple code (and will throw some errors), so the mistake is easy to spot. But what if you are working with several includes, calling functions here and there and doing many things like this? Then the same mistake could occur at a large scale. Just one thought, but without more code from the OP we cannot really answer, just give some 'maybe it's this'.
Other thing that could go wrong is that cookies are set AFTER finishing parsing the php code, not at the instant that setcookie() is called in the code. A more throughout answer can be found here: php set cookie issue
what's odd is that my variables are updating after the submission. I guess you mean your variables are NOT updating right after the submission from the rest of the question, it's pretty unclear. Please post more code so we can help you better.

How to pass variables received in GET string through a php header redirect?

I'm receiving values in a GET string from Aweber upon user's submission of a form. I take the variables they send and submit them to a SMS gateway to notify a 3rd party of the submission by text message.
Here's my problem. I need to redirect the page that performs the outgoing SMS commands in a php header to another page that finally displays the GET variables sent from Aweber.
I can retrieve the variables and their values in the first page. How do I pass them to the second page?
Here is the code I'm using on the first page (sms.php) to collect the variables sent by Aweber:
$fname = $_GET['name'];
$femail = $_GET['email'];
$fphone = $_GET['telephone'];
....etc
header('Location: confirmed.php');
exit;
First convert the $_GET HTTP variable into a query string using
$query = http_build_query($_GET);
Then append the query string variable to your redirect header
header('location: domain.com'."?".$query);
Done.
session_start();
$_SESSION['fname'] = $_GET['name'];
$_SESSION['femail'] = $_GET['email'];
$_SESSION['fphone'] = $_GET['telephone'];
....etc
header('Location: confirmed.php');
and get it on the next page like:
session_start();
$fname = $_SESSION['fname'];
$femail = $_SESSION['femail'];
$fphone = $_SESSION['fphone'];
....etc
You don't need to store them in a session, you can easily pass them with your location header:
$fname = $_GET['name'];
$femail = $_GET['email'];
$fphone = $_GET['telephone'];
//now a header with these var's:
header("Location: confirmed.php?name=".$fname."&email=".$femail."&telephone=".$fphone);
In confirmed.php you can get these variables with $_GET method.
Please for anyone reading this in future, use sessions for this kind of variable value transfer because if you rely mostly on adding variable to header then if the user in still on that form and carries out an action that changes the value of the header then your own variable value changes since it depends on the header......simply put, USE SESSIONS.
Store them in the session:
$_SESSION['fname'] = $_GET['name'];
Use session_start at the beginning of each file.
Try this. It worked perfectly for me.
if ($_GET)
{
$query = str_replace("%3D", "=", str_replace("%26", "&", strval(urlencode(http_build_query($_GET)))));
header('location: https://www.example.com'.'?'.$query);
}
else
{
header('location: https://www.example.com');
};
The best you can do is put all your POST variables to a session like this:
On page1.php put:
//Start the session
session_start();
//Dump your POST variables
$_SESSION['post-data'] = $_POST;
And on page2.php put: (If on page1.php we use a normal POST form submit with form action="page2.php")
//Start the session
session_start();
//Access your POST variables
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
//Unset the useless session variable
unset($_SESSION['post-data']);
Or on page2.php put: (If on page1.php we use a self submit with form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?> and then use a header("Location: page2.php"); to move to the page2.php and pass our POST variables via a session)
//Start the session
session_start();
//Access your POST variables
$_POST = $_SESSION['post-data'];
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
unset($_SESSION['post-data']);
I literally spent hours figuring that out because all the forums put it wrong or incomplete.
Now it's as easy as just calling the variables you passed from the page1.php like this for example: <b>Points: </b><?php echo $points; ?> and that's it!!
When situating the header('Location: page2.php'); in a if condition, etc. make sure that it will be in the first PHP script of the page and above any HTML output.
This works use this sentex
header('location:member_dashboard.php?id='.$id);

Post method prevents the page to load

I have created a page called profile.php that gets a value from mainpage.php, by using "get" method. But, If the value that was sent from mainpage.php is empty or wrong, the page redirects to the mainpage.php. However, I used "post" method in profile.php that allows users to post something in profile.php. So that If the user submits something, profile.php reloads and reloading profile.php makes the variable, that i get from mainpage, empty and directs the page to mainpage.php unwillingly.How can i fix it? Codes;
$another_user = $_GET['username'];//gets a value from mainpage.php
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."'");
$sent = mysql_fetch_array($check);
if(!$sent)
{
header('Location: mainpage.php');
exit();
}
//some codes around here
<form action="profile.php" method="post">
Commet: <input type="text" name="comment" placeholder = "comments?"/>
<input type="submit"/>
</form>
<?php
if(isset($_POST['comment'])&&!($_POST['comment']=""))
{
$writing = $_POST['comment'];
echo $writing;
}
Thanks
To start with you have a syntax error in your second line, as the colors show you already. So change it into:
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."')";
There are many solutions to your problem. One of them could be to verify which page the user is coming from. If this is mainpage.php you can verify the username and if this is profile.php you should check the comment variable.
You can make use of the $_SERVER['HTTP_REFERER'] variable to check which is the referer. So something like:
if ($_SERVER['HTTP_REFERER'] == "http://www.domain.com/mainpage.php") {
//do your username check
}
else if ($_SERVER['HTTP_REFERER'] == "http://www.domain.com/profile.php") {
//do your comment check
}
Another and maybe easier way would be to make sure that your $_POST['comment'] has not been set when dealing with the username.. Like this:
if (!isset($_POST['comment'])) {
$another_user = $_GET['username'];//gets a value from mainpage.php
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."'");
$sent = mysql_fetch_array($check);
if(!$sent) {
header('Location: mainpage.php');
exit();
}
}
else {
//...
}

Categories