isset() not working properly on form - php

I have a registration form that user submits, data is sent using isset($_POST) to see if there is anything that was put into form input boxes. If not it is sent to an else which then sends it to a function that returns the user back to registration form to complete some missing forms. For some reason it is not working properly.
Here is my checking code -------
function returnBack(){
header("Location:register.php");
exit;
}
if(isset($_POST['myusername']))
{
$myusername = $_POST['myusername'];
}
else
{
returnBack();
}
if(isset($_POST['mypassword'])) {
$mypassword=$_POST['mypassword'];
}
else{
returnBack();
}
if(isset($_POST['myemail'])) {
$myemail=$_POST['myemail'];
}
else{
returnBack();
}
if(isset($_POST['myname'])) {
$myname=$_POST['myname'];
}
else{
returnBack();
}
if(isset($_POST['mylastname'])){
$mylastname=$_POST['mylastname'];
}
else{
returnBack();
}
/////////////////////////////////////////////////////////////*******CONNECT TO SERVER ******************************************************************/
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
////////////////////////////////////////////////////////////***********INSERT REGISTER DATA INTO DB ***************************************************************/
//$encrypt_password = md5($mypassword);
$insertdata = $DBH->prepare("INSERT INTO members (username, password, email, firstname, lastname ) VALUES ('$myusername','$mypassword','$myemail','$myname','$mylastname')");
$insertdata->execute();
echo "success";
$DBH = null;
Here is the form section ------------------------------
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="register" method="post" action="insertnewmem.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Registration Form </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername" ></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="myemail" type="text" id="myemail"></td>
</tr>
<tr>
<td>First Name</td>
<td>:</td>
<td><input name="myname" type="text" id="myname"></td>
</tr>
<tr>
<td>Last Name</td>
<td>:</td>
<td><input name="mylastname" type="text" id="mylastname"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Register"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
UPDATED ----------------------------------------------
Sorry it skips the function returnBack() and just inserts it into db even if form not properly filled.

Try !empty() instead of isset(). This will evaluate to true only if there is something other than null, false, 0, or empty string ''. You probably have empty strings being submitted.

Others have posted answer, but let me explain why.
isset() checks to see if the value was set, not what the value is, but simply if it has a value. When you submit your form, you are passing an empty string as the value for each of the inputs.
Normally I check this using:
if(isset($_POST['variable']) && $_POST['variable'] !== "")
The first part makes sure the variable exists ( so that the second condition will not throw an error ) and the second condition makes sure that the string is not empty.

Related

CodeIgniter: changing password in controller

I'm trying to allow users to change their passwords in my site.
I'm getting stuck in the controller. My doubt is whether $sql = $this->db->select("*")->from("logins_table")->where('lt_username',$this->session->userdata('email'))->get(); is working or not.
My controller:
<?php
class Changepw extends MY_Controller {
public function Changepwd(){
}
public function reset() // we will load models here to check with database
{
$sql = $this->db->select("*")->from("logins_table")->where('lt_username',$this->session->userdata('email'))->get();
foreach ($sql->result() as $my_info) {
$db_password = $my_info->lt_password;
$db_id = $my_info->lt_id;
}
if($this->input->post('opassword') == $db_password && ($this->input->post('npassword') != '') && ($this->input->post('cpassword')!='')) {
$fixed_pw = mysql_real_escape_string(md5($this->input->post('npassword')));
$update = $this->db->query("Update 'logins_table' SET 'lt_password'= '$fixed_pw' WHERE 'id'= '$db_id'")or die(mysql_error());
//$this->form_validation->set_message('change',"sucess");
echo json_encode(array("success"=>true));
}else {
//$this->form_validation->set_message('change', "err");
echo json_encode(array("success"=>false));
}
exit;
}
}
and my view page is:
<table width="95%" border="0" cellspacing="5" cellpadding="5">
</tbody>
<tr>
<td width="35%" class="heading">Email</td>
<td><input type="text" name="email" ></td>
<tr>
<td class="heading">Existing Password</td>
<td><input type="password" name="opassword" ></td>
</tr>
<tr title="Ignore new password if you dont want to change password">
<td class="heading">New Password</td>
<td><input type="password" name="npassword"></td>
</tr>
<tr>
<td class="heading">Confirm Password</td>
<td><input type="password" name="cpassword"></td>
</tr>
<tr>
<td> </td>
<td><button name="Submit" id="forgotBtn" class="customBtn" value="Submit">Save changes</button>
</td>
<tr>
<td> </td>
<td ><div class="errorMsg" id="errMsg" style="display:none"> Error in updating </div></td>
</tr>
</tr>
</tbody>
</table>
</form>
$("#forgotBtn").on('click', function()
{
$.post( "/changepw/reset", $("#forgotForm").serialize(), // serializes the form's elements.
function(data) {
data = jQuery.parseJSON(data);
if(data.error == false) {
$("#successMsg").hide();
}else{
$("#errMsg").show();
}
} );
return false;
});
Thanks.
I think according to the code, your error is here.
$this->input->post('opassword') == $db_password// this line
While storing password in database you have used md5(), but here you are just checking for the plain text which is wrong
md5($this->input->post('opassword')) == $db_password
This should help you.

increment variable on submit to update mysql query

I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>

Php login form problems

I am having problems with this, when i login with valid data, the page just refreshes (i am assuming that the if statement in protectedstuff.php failed). When i used the deprecated method to register the session and check if it exists, it worked if(!session_is_registered(myusername)).
Oh and also I am able to see a cookie was created "PHPSESSID".
what am I doing wrong?
login.php ->
<?php
if($_POST){
$errorLogin="Wrong Username or Password";
$link = mysqli_connect('localhost', 'root', '', 'mydb')
or die('Could not connect: ' . mysqli_error($link));
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql_query="SELECT * FROM users WHERE username='$myusername' and password='$mypassword';";
$result = mysqli_query($link, $sql_query) or die('query failed'. mysqli_error($link));
$row = mysqli_fetch_assoc($result);
$dbUserName= $row['username'];
$dbPassword= $row['password'];
// Mysql_num_row is counting table row
// If result matched $myusername and $mypassword,
if($myusername==$dbUserName && $mypassword==$dbPassword){
// Register $myusername, and redirect to file "login_success.php"
//session_register("myusername"); <- deprecated
$_SESSION['myusername']=$myusername;
header("location:protectedstuff.php");
}else {
echo $errorLogin;
}
}
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
the usernames and passwords are already in the database.
This is my protectedstuff.php
<?php
session_start();
if(!isset($_SESSION['myusername']))
{
header("location:login.php");
}
else{
?>
<html>
<body>
Login Successful
</body>
</html>
<?php
}
?>
Thank you!
I don't see a session_start() above your $_POST block. You must call that on every page BEFORE any output is sent

php mysql and form error

i have a form error when i put password and click submit button query executed but on database password row empty :(
please help me to sort out this problem i tried but didn't solve. php contain html via double quotes
thanks
<?php echo errormessage();
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']) AND isset($_REQUEST['token']) && !empty($_REQUEST['token'])){
// Verify data
$email = mysql_prep($_REQUEST['email']); // Set email variable
$token = mysql_prep($_REQUEST['token']); // Set hash variable
$result = mysqli_query($connection,"SELECT email, hash FROM job_seeker WHERE email='".$email."' AND hash='".$token."'");
$num_rows = mysqli_num_rows($result);
if($num_rows > 0){
echo '<form method="post" action=""><table class="table table-bordered" width="100%" >
<tr>
<td width="40%">New Password :</td>
<td width="60%"><input type="password" required="" value="" name="pass"></td>
</tr>
<tr>
<td>Confirm New Password : </td>
<td><input type="password" required="" value="" name="cpass"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Update"></td>
</tr>
</table></form>';
//<?php //var_dump($_POST);
#$pass = mysql_prep($_POST['pass']);
#$cpass = mysql_prep($_POST['cpass']);
if(isset($_POST)){
if($pass == $cpass)
{
//echo $hashed_password = password_encrypt($pass);
$hashed_password = $pass;
$result = mysqli_query($connection,"UPDATE job_seeker SET hashed_password='$hashed_password', hash='' WHERE email='".$email."' AND hash='".$token."'");
if ($result) {
// Success
$_SESSION["message"] = "Password Successfully Changed.";
} else {
// Failure
$_SESSION["message"] = "Oops... Something went wrong.";
}
}
}
}else{
$_SESSION["message"] = "OOPS: Link Expired. Please check your inbox.";
}
}else{
//var_dump($_REQUEST);
redirect_to('index.php');
}
?>
The code line:
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']) AND isset($_REQUEST['token']) && !empty($_REQUEST['token'])){
checks for the password and executes query only if the password (token) is posted.
Please update it to:
if(isset($_REQUEST['email']) && !empty($_REQUEST['email'])){
And you code will work.
Problem solved if(isset($_POST)){ lol every one gave new instruction except to change the code if(isset($_POST))
There are errors in the "password change" portion of your code.
$result = mysqli_query($connection,"UPDATE job_seeker SET hashed_password='$hashed_password', hash='' WHERE email='".$email."' AND hash='".$token."'");
depending on your php configuration, it might set the password column to
"$hashed_password"
or to whatever was in the variable $hashed_password
You probably meant to do this :
$result = mysqli_query($connection,"UPDATE job_seeker SET hashed_password='".$hashed_password."', hash='' WHERE email='".$email."' AND hash='".$token."'");
But that is still a terrible idea, because this is vulnerable to sql injection.
Also, make sure you have your column names right, down to the letter. ( i can't check that for you )
I could be because you have predefined Value in form.
Try to change this:
echo '<form method="post" action=""><table class="table table-bordered" width="100%" >
<tr>
<td width="40%">New Password :</td>
<td width="60%"><input type="password" required="" value="" name="pass"></td>
</tr>
<tr>
<td>Confirm New Password : </td>
<td><input type="password" required="" value="" name="cpass"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Update"></td>
</tr>
</table></form>';
For this:
echo '<form method="post" action=""><table class="table table-bordered" width="100%" >
<tr>
<td width="40%">New Password :</td>
<td width="60%"><input type="password" required="" name="pass"></td>
</tr>
<tr>
<td>Confirm New Password : </td>
<td><input type="password" required="" name="cpass"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Update"></td>
</tr>
</table></form>';
Without value attribute

Unable to submit CSV file to uploader

I've made a CSV uploaded where the user must tell the program the exact name of certain columns in the CSV file so it can access and grab data to store in database. I have some error messages where whenever they don't fill something out that is necessary it will take them back to form to fix what ever mistakes they made. The issue is it always takes me back and I don't really know why.
Code for Uploader ---------------------------------------------------------------------
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
function returnBack(){
header("Location:csvuploader/csvuploaderform.php?seterror=1");
exit;
}
if (isset($_POST['submit'])){
/*******************************GET NAME OF COLUMNS IN CSV FILE *********************************************************/
if (empty($_POST['files'])){
returnBack();
}
if (empty($_POST['firstname'])){
returnBack();
}
if (empty($_POST['lastname'])){
returnBack();
}if (empty($_POST['email'])){
returnBack();
}
if (empty($_POST['phone'])){
returnBack();
}
$file = $_FILES['files']['tmp_name'];
$handle = fopen($file , "r");
$fileop = fgetcsv($handle,1000,",");
$firstname_index = array_search($_POST['firstname'],$fileop);
if (empty($firstname_index)){
returnBack();
}
$lastname_index = array_search($_POST['lastname'],$fileop);
if (empty($lastname_index)){
returnBack();
}
$email_index = array_search($_POST['email'],$fileop);
if (empty($email_index)){
returnBack();
}
$phone_index = array_search($_POST['phone'],$fileop);
if (empty($phone_index)){
returnBack();
}
/***********************ASSIGN COLUMN VALUES TO ACCORDING VARIABLES AND INSERT THEN INTO CSV TABLE IN DB *************************************/
while (($fileop = fgetcsv($handle,1000,",")) !== false)
{
$firstname = $fileop[$firstname_index];
$lastname = $fileop[$lastname_index];
$email = $fileop[$email_index];
$phone = $fileop[$phone_index];
$insertdata = $DBH->prepare("INSERT INTO csv (firtname, lastname, email, phone) VALUES ('$firstname','$lastname','$email','$phone')");
$insertdata->execute();
}
if ($insetdata){
echo "Successfully Uploaded. Thank you.";
}
}
Thank you for your time!
UPDATED ---------------------------
form code
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form method="post" action="csvuploader.php" enctype="multipart/form-data">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>CSV Uploader </strong></td>
</tr>
<tr>
<td>Enter Name of First Name Column </td>
<td>:</td>
<td><input name="fisrtname" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?> </td>
</tr>
<tr>
<td>Enter Name of Last Name Column </td>
<td>:</td>
<td><input name="lastname" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?></td>
</tr>
<tr>
<td>Enter Name of Email Column </td>
<td>:</td>
<td><input name="email" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?></td>
</tr>
<tr>
<td>Enter Name of Phone Number Column </td>
<td>:</td>
<td><input name="phone" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?></td>
</tr>
<tr>
<td width="294"><input type="file" name="files" /><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Select a File</span>";
}
?></td>
</tr>
<br />
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
I'm not sure how your data file look, but you might want to use trim on fgetcsved array values, because the last values are very likely to include a line-end:
$fileop=fgetcsv($handle);
$fileop=array_map("trim",$fileop);
/*recognize index*/
while (($fileop=fgetcsv($handle))!==false)
{
$fileop=array_map("trim",$fileop);
$firstname=$fileop[$firstname_index];
/*insert into DB*/
}
Edit:
Oops, seems I missed something...you're using
if(empty($firstname_index))
in your code, but if, for instance, array_search($_POST["firstname"],$fileop) returns 0 (which is the first index in an array), your empty($firstname_index) will be TRUE, and you will be kicked back.
You should use
if($firstname_index===false)
instead (in all four indexes). PHP Document.
Edit #2:
Also, it's better to make you title-matching case-insensitive:
$fileop=fgetcsv($handle);
$fileop=array_map("strtoupper",array_map("trim",$fileop));
$firstname_index=array_search(strtoupper($_POST["firstname"]),$fileop);
if($firstname_index===false) returnBack();
/*and all four indexes*/

Categories