Can anyone see a bug in my code here?
Two files, one variable is set on the first page using JS and I want to pass it to the next page.
username variable is set here, first in variable then in session
username = wordOne + wordTwo + wordThree;
<?php $_SESSION['username'] = $username; ?>
then I submit the form which takes user to register-form.php
<form method="POST" action="register-form.php">
<button>I like it! Make it my username.</button>
</form>
when that page loads, username is grabbed and output into the input as a value
<body onload="inputUsername()">
function inputUsername(){
var username = "<?php echo isset($_POST[username])?$_POST[username]:''; ?>";
console.log("I'm running " + username);
document.getElementById('inputUsername').value = username;
}
But this doesn't work as the variable username is not persisting across the pages.
What I see is that you are asking for $_POST[username] but from the form you're not passing it.I mean something like this:
<form method="POST" action="register-form.php">
<input type="hidden" name="username" value="<?php echo $_SESSION['username']; ?>">
<button>I like it! Make it my username.</button>
In your current code, You are accessing _POST variable, however you are setting _SESSION variable in your code. Therefore, the possible fix is :
1. check for _SESSION variable in inputUsername() function OR
2. Set username in your form, so that when you submit it, it post to new page.
Related
Good morning, afternoon or night :D
I want to pass my $_GET['area'] variable to a method, but after submitting the form, it only let me pass such variable to the header() method:
Note: This is the variable from the URL I want to pass: /index.php?area=work
I have a index.view.php with a button:
<a href="crearArt.php?area=<?php echo $_GET['area'] ?>" >Add new article</a>
From the URL, the button receives the $_GET['area'] and when I click the button it takes me to the area where I can create new articles, here is the code of crearArt.view.php file:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST">
//... Bunch of inputs
<button type="submit" name="crearArticle">Create New Content</button>
</form>
When I click on "Create New Content" (submitting the form), the crearArt.php file should get the $_GET['area'] variable and pass it to the $addDataToDB() method but that doesn't happens, if I put a print_r() inside the if condition to check if the variable it doesn't show the variable.
Furthermore, if I pass the variable to the header() method it does work, meaning that (I think) the variable still there.
Here the crearArt.php file
<?php
$inputNames = [];
$inputValues = [];
if(isset($_POST['crearArticle'])){
// Get all inputs from the form
foreach($_POST as $key => $value){
if($key !== 'crearArticle'){
// This will NOT add the button' name property when the form gets submitted
array_push($inputNames, $key);
array_push($inputValues, $value);
};
};
// Add values to WorkDB || CodeDB
$addDataToDB($inputNames, $inputValues, $_GET['area']);
// Return to index.php?area=??
header('Location: index.php?area='.$_GET['area']);
} // END MAIN IF
?>
Sumerizing, when I press on "Create New Content" it should pass the variable to $addDataToDB() but it doesn't do it, even though the URL has the $_GET['area'] var with it: /crearArt.php?area=work
Question:
Is there a way to get this variable without creating hidden inputs in the crearArt.view.php?
Thanks in advance
PS: I'm new into PHP.
In addition
I tried creating a var outside the if conditional and then passing it to the method but that doesn't work either.
By using that variable I'm gonna let the function "know" from which area I come from so the function "know" to which database it has to refer to.
If I use variable as a string ('work'), it does work.
Each HTTP request you make has its own URL.
The request you make to crearArt.php?area=<?php echo $_GET['area'] ?> and the request you make to <?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?> are different requests with different query strings and will have different values in $_GET.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>"
According to the manual, PHP_SELF is:
The filename of the currently executing script, relative to the document root.
You haven't put a query string in your URL.
When you submit the form $_GET['area'] won't exist.
I have a question about how I can access the value from a variable from one page on another one.
I have a registration script and the registration form is on my homepage. I want to dynamically create a random name for every input field (change the value of the name attribute). The current name attribute for the input is just firstName, but I want it to be like firstName_345635. The 345635 is a randomly generated number and will change everytime the page refreshes.
Here is my random number variable:
$firstNameInputName = 'firstName_' . rand(10000, 50000);
The output becomes: firstName_[randomNumer].
The problem is, the register.php has all the post variables to get the form data. What I have now is this:
$firstName = $_POST["firstName"]);
I need to get the value from the random number variables from the homepage and instead of giving the $firstname variable the name firstName, it should get the name that the random number generating variable has produced on the homepage.
How can I achieve this?
You should use a session (or cookies) var to save this dynamic name.
Approach 1. Session (or cookies)
page1.php
<?php
session_start();
$customCode = rand(5, 15);
$_SESSION['customCode'] = $customCode; ?>
<form action="page2.php" method="post">
<input type="text" name="firstName_<?php echo $customCode; ?>" />
</form>
page2.php
<?php
session_start();
$customCode = $_SESSION['customCode']; ?>
$firstName = $_POST['firstName_'.$customCode];
Approach 2. You can put a input hidden field in your form like:
<input type="hidden" name="customCode" value="345635" />
And get it in second page like:
$firstName = $_POST['firstName_'.$_POST['customCode']];
Approach 3. You can iterate over your $_POST array to get firstName like:
foreach($_POST in $key => $value) {
if(strpos($key, "firstName")) {
$firstName = $value;
}
}
The solution is sessions, session variables are superglobal variables which means you can use them in different files as long as its the same session, to use them you need to start the session at every page you'll use them in, also, starting the session has to be done before any output is shown.
Ex (registeration page):
<?php
session_start();
/**
** HTML AND FORM HERE WHATEVER ELSE YOU NEED TO DISPLAY
**/
$_SESSION['FirstName'] = $firstNameInputName;
?>
Ex (processing page):
<?php
session_start();
echo $_POST[$_SESSION['FirstName']]; // Output: Whatever was entered inside the field
?>
I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();
How do I maintain the $post value when a page is refreshed; In other words how do I refresh the page without losing the Post value
This in not possible without a page submit in the first place! Unless you somehow submitted the form fields back to the server i.e. Without Page Refresh using jQuery etc. Somesort of Auto Save Form script.
If this is for validation checks no need for sessions as suggested.
User fills in the form and submits back to self
Sever side validation fails
$_GET
<input type="hidden" name="first"
value="<?php echo htmlspecialchars($first, ENT_QUOTES); ?>" />
validation message, end.
alternatively as suggested save the whole post in a session, something like this, but again has to be first submitted to work....
$_POST
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }
You can't do this. POST variables may not be re-sent, if they are, the browser usually does this when the user refreshes the page.
The POST variable will never be re-set if the user clicks a link to another page instead of refreshing.
If $post is a normal variable, then it will never be saved.
If you need to save something, you need to use cookies. $_SESSION is an implementation of cookies. Cookies are data that is stored on the user's browser, and are re-sent with every request.
Reference: http://php.net/manual/en/reserved.variables.session.php
The $_SESSION variable is just an associative array, so to use it, simply do something like:
$_SESSION['foo'] = $bar
You could save your $_POST values inside of $_SESSION's
Save your all $_POST's like this:
<?php
session_start();
$_SESSION['value1'] = $_POST['value1'];
$_SESSION['value2'] = $_POST['value2'];
// ETC...
echo "<input type='text' name='value1' value='".$_SESSION['value1']."' />";
echo "<input type='text' name='value2' value='".$_SESSION['value2']."' />";
?>
Actually in html forms it keeps post data.
this is valuble when you need to keep inserted data in the textboxes.
<form>
<input type="text" name="student_name" value="<?php echo
isset($_POST['student_name']) ? $_POST['student_name']:'';
?>">
</form>
put post values to session
session_start();
$_SESSION["POST_VARS"]=$_POST;
and you can fetch this value in another page like
session_start();
$_SESSION["POST_VARS"]["name"];
$_SESSION["POST_VARS"]["address"];
You can use the same value that you got in the POST inside the form, this way, when you submit it - it'll stay there.
An little example:
<?php
$var = mysql_real_escape_string($_POST['var']);
?>
<form id="1" name="1" action="/" method="post">
<input type="text" value="<?php print $var;?>"/>
<input type="submit" value="Submit" />
</form>
You can use file to save post data so the data will not will not be removed until someone remove the file and of-course you can modify the file easily
if($_POST['name'])
{
$file = fopen('poststored.txt','wb');
fwrite($file,''.$_POST['value'].'');
fclose($file);
}
if (file_exists('poststored.txt')) {
$file = fopen('ipSelected.txt', 'r');
$value = fgets($file);
fclose($file);
}
so your post value stored in $value.
When a user links to link it redirects to edit.php - here's an example: www.cars.com/edit.php?id=23
In edit.php, I use _GET to store the value in a session. The value is stored in $_session['user'] but when the form on the same page is submitted echo $_session['user'] displays nothing - how can I make it display the value?.
<?php
session_start();
$_session['user']=$_GET['id']; // I use _GET to store the value in session
if( isset($_POST['submit'])) {
echo $_session['user'];
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="formI2D" enctype="multipart/form-data" id="formI2D" />
It's because you're redeclaring your $_SESSION['user'] even when it's a POST (I think).
You can fix this by adding ?id=$_GET['id'] in you form's action, or by wrapping your $_SESSION initialisation like that:
if (isset($_GET['id'])) {
$_SESSION['user']=$_GET['id'];
}
Also, you should use uppercase for php global arrays ($_POST, $_COOKIE, $_SESSION etc)