I am looking for email in my view page. there are two ways email can get there. Either by POST or by SESSION.
if it is a $_POST then I want to use the $_POST email other wise I want to use the email saved in session.
Currently the code I have is below
$email = (isset($_POST['email']) ? $_POST['email'] : '');
whats the BEST way to do it in least lines of code
I'm guessing you're just looking for this (assuming the email address is stored in the $_SESSION array under the key email):
$email = (isset($_POST['email']) ? $_POST['email'] : $_SESSION['email']);
Or am I misunderstanding your question?
Try this:
$email = (isset($_POST['email']) ? $_POST['email'] : (isset($_SESSION['email'])) ? $_SESSION['email'] : '');
Which is the same of:
if(isset($_POST['email'])) {
$email = $_POST['email'];
} else {
if(isset($_SESSION['email'])) {
$email = $_SESSION['email'];
} else {
$email = '';
}
}
A funny alternative to the correct answer of #Gabriel Santos
$input = function($param, $default = '') {
static $input;
if (null === $input) {
$input = array_merge($_SESSION, $_POST);
}
return isset($input[$param]) ? $input[$param] : $default;
};
// get input
$email = $input('asd');
Related
I made a registration form that takes email, username, firstname, etc...Only Password will not store in the database upon submission.
The field is declared correctly in the HTML file, password is set to varchar, all the other variables post but I can't pinpoint why not this password field.
Please find below my set up:(php 5.6.39)
So i corrected the "." after Username on line 25, but now it's weird.
it still doesn't post to the then actually outputs my error message "First Name and Last Name is a required field and cannot be blank."
$required = array('Email','FirstName','LastName', 'Username', 'Password');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field){
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "First Name and Last Name is a required field and
cannot be blank.";
} else {
echo " Awesome, you filled it all in! ";
}
even when all fields are submitted
Hey you put full stop instead of comma after UserName :
'Username','Password'
Try This,
$uname = (!empty($_POST['UserName'])) ? $_POST['UserName'] : $uname;
$pword = (!empty($_POST['Password'])) ? $_POST['Password'] : $pword;
Warning for Sql Injection
Don't use direct $_POST try to sanitize it first,
$uname = (isset($_SESSION['Username']) ? $_SESSION['Username'] : NULL);
$pword = (isset($_SESSION['Password']) ? $_SESSION['Password'] : NULL);
$uname = (isset($_POST['Username']) ? $_POST['Username'] : $uname);
$pword = (isset($_POST['Password']) ? $_POST['Password'] : $pword);
There is a PHP update form where a user can update his records. The below-mentioned code looks redundant to me. How can I optimize this PHP code? Also, I have the admins username and email in a different table and the admin detail columns (such as first name, last name, gender, dob) in a different table. What will be the best way to check if username and email both have been updated or if any one of them and update it in the database accordingly.
Below is my source code:
if(isset($_POST['btnClick']) {
$f_name = NULL;
$l_name = NULL;
$username = NULL;
$email = NULL;
$gender = NULL;
$dob = NULL;
$f_name = filter_input(INPUT_POST, "f_name", FILTER_SANITIZE_STRING);
$l_name = filter_input(INPUT_POST, "l_name", FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_VALIDATE_STRING);
$dob = filter_input(INPUT_POST, "dob", FILTER_VALIDATE_STRING);
try {
if(isset($username) && $username != $_SESSION['username']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "Username changed value inputted";
}
else if(isset($email) && $email != $_SESSION['email']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "email change value inputted";
}
else if(isset($username) && isset($email)) {
/*Update both records */
}
You can do something like this:
<?php
try {
if (isset($username) && $username != $_SESSION['username']) {
$fieldsToUpdate[] = 'username=:username';
$updatedFields[] = 'Username';
}
if (isset($email) && $email != $_SESSION['email']) {
$fieldsToUpdate[] = 'email=:email';
$updatedFields[] = 'Email';
}
if (isset($fieldsToUpdate) && count($fieldsToUpdate) > 0) {
$sqlUpdate = "UPDATE admins SET " . implode($fieldsToUpdate, ', ') . " WHERE admin_id=:admin_id";
/*Update code here...*/
$finalMessage = 'Fields: ' . implode($updatedFields, ', ') . ' have been updated.';
}
}
PS: This is an example code that how can you optimize your code with PHP arrays and implode() function to run single query to update single or multiple fields.
I'm confused how to use isset and empty, I'm trying to write a simple api, there should be error saying which param is missing and return error too if the param is null.
What's wrong my statement below?
$email= isset($_POST['email']) ? mysqli_real_escape_string($mysqli, $_POST['email']) : '';
if(empty($email)) {
echo 'email cannot be empty!'
}
You don't actually need to use both isset and empty, because empty already does it.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
More details are here:
http://php.net/manual/en/function.empty.php
So your code could look this way, for example:
if (empty(trim($_POST['email']))) {
echo "Email cannot be empty!\n";
// you should add return or raise exception here
// or even exit
exit;
}
$email = trim($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Your email {$email} is invalid\n";
// you should add return or raise exception here
// or even exit
exit;
}
$email = mysqli_real_escape_string($email);
Change $email to :
$email= isset($_POST['email']) && !empty($_POST['email']) ? mysqli_real_escape_string($mysqli, $_POST['email']) : '';
So the $_POST['email'] is not containing empty value.
Try to use next code snippet
if( false === input_filter(INPUT_POST, FILTER_VALIDATE_EMAIL) ) {
echo "error message";
}
$email = input_filter(INPUT_POST, FILTER_SANITIZE_EMAIL );
// to do somethink with email...
I think you are trying to check $email value which is null. You should check $fname in if statement instead.
try this to check for all missing fields:
$required_fields = array('email', 'name', 'password');
$err_msgs=array();
foreach($required_fields as $field) {
if(empty( $_POST[$field]) ){
err_msgs[]= $field . ' cannot be empty!';
}
}
if (!empty($err_msgs)) {
echo json_decode($err_msgs);
}
Edit: removed isset() after reading Axalix's answer.
I need to change the value of the variable $destination to help validate a form. If none of the fields within the form, the page refreshes with the error message displayed, which works. If the fields are all filled in, the the $destination value should change and the message 'it works!' is printed. However, if all fields are filled in and the user submits the form, the message 'it works!' is printed, but the $destination's value is still set to 'this-page'. What am I missing here?
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!$fname OR !$lname OR !$email OR !$phone) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Hope this is academic. There are better ways to approach this. But here:
$destination = '';
$fname = isset($_POST['fname']) ? $_POST['fname'] : null ;
$lname = isset($_POST['lname']) ? $_POST['lname'] : null ;
$phone = isset($_POST['phone']) ? $_POST['phone'] : null ;
$email = isset($_POST['email']) ? $_POST['email'] : null ;
if (empty($fname) || empty($lname) || empty($phone) || empty($email)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
} else {
print 'It works!';
$destination = 'results-page';
}
Someday take a look at some PHP frameworks and how they handle form validation. for example: http://framework.zend.com/manual/1.12/en/zend.form.elements.html Might give you some insight.
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!empty($fname) || !empty($lname) || !empty($email) OR !empty($phone)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Seems like the problems isn't related to the validation part here. You are getting both the print from the else statement and the $destination variable from the if statement? That should be logically impossible. Are you sure you don't have any syntax errors etc. in your code? Is that the exact code you have in your program?
I trying to create a simple user registration, that saves data into a database.
But I have an error I cant defeat.
Its says
Notice: Undefined index: pass_conf in C:\wamp\www\book\reg.php on
line 27
But my pass_config seems to be right.
Any ideas whats the problem ? this is the php code
/// Updating my code, this one works
<?php
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "pagination";
$connection = mysql_connect($host,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$connection);
/*
$name = $_POST["username"];
$pass = $_POST["password"];
$pass_conf = $_POST["pass_conf"];
$email = $_POST["email"];
$ip = $_POST["ip"]; */
$name = isset($_POST['username']) ? $_POST['username'] : 0;
$pass = isset($_POST['password']) ? $_POST['password'] : 0;
$pass_conf = isset($_POST["pass_conf"]) ? $_POST["pass_conf"] : 0; // 0 equals your default off value.
$email = isset($_POST['email']) ? $_POST['email'] : 0;
$ip = isset($_POST['ip']) ? $_POST['ip'] : 0;
if($name == false || $pass == false || $pass_conf == false || $email == false){
echo "Please fill in all the required fields.";
};
if($pass != $pass_conf){
echo "Passwords do not match.";
}else {
$connection = mysql_connect($host,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$connection);
$sql = "INSERT INTO user (username,password,email,ip) VALUES ($name, $pass, $email, $ip)";
$result = mysql_query($sql);
echo "Thank you for your registration to Our Site";
};
?>
I Will add my form.php also since I got a request for it.
<?php
$IP = $_SERVER['REMOTE_ADDR'];
?>
<form name=reg action=reg.php method=post>
Username : <input type=text name=username><br>
Password : <input type=password name=password><br>
Confirm :<input type=password name=pass_conf><br>
Email : <input type=text name=email><br>
<input type=hidden name=ip value='<?php echo $IP ?>'>
<input type=submit value='Register'>
</form>
Thanks
instead of $x = $_POST['x'] use $x = isset($_POST['x']) ? $_POST['x'], null.
Or use:
function post($key, $default = null) {
return isset($_POST[$key]) ? $_POST[$key] : $default;
}
First off, good job on using E_ALL while creating your app! Your "pass_conf" value is probably a checkbox that isn't selected when submitting your form and so no value is ever sent. A simple:
$pass_conf = isset($_POST["pass_conf"]) ? $_POST["pass_conf"] : 0; // 0 equals your default off value.
That message means that the value you are trying to get is not present in the array. So either the value is not filled in or is not passed thru correctly (check the fields name, it has to be exactly the same).
Have you tried:
if (array_key_exists("pass_conf", $_POST))
$pass_conf = mysql_real_escape_string($_POST["pass_conf"]);
else
$pass_conf = null;
$sql =
"INSERT INTO events (username, password, email, ip) " .
"VALUES ('{$name}','{$pass}','{$email}','{$ip}')";
See this question that I asked for my full example and scroll down to how it was answered by user dldnh; it's similar to yours, so maybe it will help you: [link] Undefined index notice