Page 2 of 3

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:12 pm
by Celauran
... and it turns out that both strtotime and DateTime understand dd-mm-yyyy and mm/dd/yyyy, but not mm-dd-yyyy. The problem here, is that strtotime() will parse it incorrectly rather than returning false. DateTime::__construct() throws an exception, though.

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:15 pm
by jaad
That's awesome I love the bit of theory you gave me with the substituted script. I will read on that.

But unfortunately it doesn't work.... when I enter let's say 01-01-2000 in the date field I get no error message. my script tells me "your change have been updated and when I look a the field in the table it wrote it as 0000-00-00 :o(

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:18 pm
by Celauran
Without seeing what's being passed to your DB query, I can't really comment.

Code: Select all

php > $date = date('Y-m-d', strtotime('01-01-2000'));
php > echo $date . "\n";
2000-01-01
php > 
Works fine.

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:29 pm
by Celauran
It's not pretty, but something like this could allow for dd-mm-yyyy:

Code: Select all

function parseDate($date) {
	try {
		$dt = new DateTime($date);
		return $dt;
	} catch (Exception $e) {
		try {
			$date = str_replace('-', '/', $date);
			$dt = new DateTime($date);
			return $dt;
		} catch (Exception $e) {
			return false;
		}
	}
}
Note that this will return a DateTime object. You'll need to format it before inserting it into the DB.

Code: Select all

$date = parseDate($_POST['dob']);
if ($date) {
    $dob = $date->format('Y-m-d');
}

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:31 pm
by jaad
if the date is entered in the field as yyyy-mm-dd there is no problem it goes into the table as it is type. works fine. but if someone writes it in a different format then I get 0000-00-00 every single time

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:34 pm
by Celauran
I'm inclined to think that at least part of the problem is in the query string itself, then.

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:40 pm
by jaad
here is the update function

Code: Select all

<?php 
class Users{
 	
	private $db;

	public function __construct($database) {
	    $this->db = $database;
	}	
	
	public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $id){

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`bio`			= ?,
								`image_location`= ?
								
								WHERE `id` 		= ? 
								");

		$query->bindValue(1, $first_name);
		$query->bindValue(2, $middle_name);
		$query->bindValue(3, $last_name);
		$query->bindValue(4, $gender);
		$query->bindValue(5, $dob);
		$query->bindValue(6, $sin);
		$query->bindValue(7, $bio);
		$query->bindValue(8, $image_location);
		$query->bindValue(9, $id);
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}	
	}

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:44 pm
by Celauran
What's calling this? Have you checked the value of $dob inside the method itself?

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:47 pm
by jaad

Code: Select all

$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $user_id);
       header('Location: settings.php?success');
exit();
would that be it?

bare in mind I am a newbie at this...

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:48 pm
by Celauran
Also, and slightly off topic, PDO allows for named placeholders, which I find far easier to read/follow than question marks. Consider

Code: Select all

$query = "UPDATE `users` SET `first_name` = :first, `last_name` = :last";
$stmt = $db->prepare($query);
$stmt->execute(array(':first' => $first_name, ':last' => $last_name));

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:49 pm
by Celauran
jaad wrote:

Code: Select all

$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $user_id);
       header('Location: settings.php?success');
exit();
would that be it?

bare in mind I am a newbie at this...
That's definitely the code that's calling it. What does $dob contain? Try echoing it before the update call (or inside it) to see if that may be the culprit here.

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 9:56 pm
by jaad
I'm not sure if I did that correctly but here is what I got

Code: Select all

1234-12-12

Not a valid date.
I used the print function below it in the validation code:

Code: Select all


if (isset($_POST['dob']) && !empty($_POST['dob'])) {
        $dob_timestamp = strtotime($_POST['dob']);
		print ($_POST['dob']);------------------------------------------<<<<<<<<<<<<<<<
        if ($dob_timestamp === false) {
                $errors[] = "Not a valid date.";
        } else {
                $dob = date('Y-m-d', $dob_timestamp);
        }
}

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 10:03 pm
by Celauran
Hang on, why are you printing $_POST['dob']? Also, 1234-12-12 is a perfectly valid date. Can you post all of the code in question?

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 10:13 pm
by jaad
because you asked me to
Try echoing it before the update call (or inside it) to see if that may be the culprit here.


it's before the calling function I figured that is what you were asking me to do?????

Code: Select all


<?php 
include_once 'core/init.php';
$general->logged_out_protect();
?>
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" type="text/css" href="css/style.css" >
	<title>Settings</title> 
    
 
<script>

function disableEnterKey(e){
	var key; 
	if(window.event)
	key = window.event.keyCode;     //IE
	else
	key = e.which;     				//firefox
    if(key == 13)
        return false;
	     else
         return true;
}
	</script>
</head>
<body>
	<div id="container">
		<?php include 'includes/menu.php'; ?>
		<?php
	    if (isset($_GET['success']) && empty($_GET['success'])) {
	        echo '<h3>Your details have been updated!</h3>';	        
	    } else{

            if(empty($_POST) === false) {		
			
				if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
					if (ctype_alpha($_POST['first_name']) === false) {
					$errors[] = 'Please enter your First Name with only letters!';
					}	
				}
				if (isset($_POST['middle_name']) && !empty ($_POST['middle_name'])){
					if (ctype_alpha($_POST['middle_name']) === false) {
					$errors[] = 'Please enter your Middle Name with only letters!';
					}	
				}
				if (isset($_POST['last_name']) && !empty ($_POST['last_name'])){
					if (ctype_alpha($_POST['last_name']) === false) {
					$errors[] = 'Please enter your Last Name with only letters!';
					}	
				}
				if (isset($_POST['sin']) && !empty ($_POST['sin'])){
					if (trim(ctype_digit($_POST['sin'])) === false) {
					$errors[] = 'Letters are not allowed in this field!';
					}	
				}
					
				if (isset($_POST['dob']) && !empty($_POST['dob'])) {
        $dob_timestamp = strtotime($_POST['dob']);
		print ($_POST['dob']);
        if ($dob_timestamp === false) {
                $errors[] = "Not a valid date.";
        } else {
                $dob = date('Y-m-d', $dob_timestamp);
        }
}
				if (isset($_POST['gender']) && !empty($_POST['gender'])) {
					
					$allowed_gender = array('undisclosed', 'Male', 'Female');

					if (in_array($_POST['gender'], $allowed_gender) === false) {
						$errors[] = 'Please choose a Gender from the list';	
					}

				} 
				

				if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
					
					$name 			= $_FILES['myfile']['name'];
					$tmp_name 		= $_FILES['myfile']['tmp_name'];
					$allowed_ext 	= array('jpg', 'jpeg', 'png', 'gif' );
					$a 				= explode('.', $name);
					$file_ext 		= strtolower(end($a)); unset($a);
					$file_size 		= $_FILES['myfile']['size'];		
					$path 			= "avatars";
					
					if (in_array($file_ext, $allowed_ext) === false) {
						$errors[] = 'Image file type not allowed';	
					}
					
					if ($file_size > 2097152) {
						$errors[] = 'File size must be under 2mb';
					}
					
				} else {
					$newpath = $user['image_location'];
				}

				if(empty($errors) === true) {
					
					if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']) && $_POST['use_default'] != 'on') {
				
						$newpath = $general->file_newpath($path, $name);

						move_uploaded_file($tmp_name, $newpath);

					}else if(isset($_POST['use_default']) && $_POST['use_default'] === 'on'){
                        $newpath = 'avatars/default_avatar.png';
                    }
							
					$first_name 	= htmlentities(trim($_POST['first_name']));
					$last_name 		= htmlentities(trim($_POST['last_name']));
					$middle_name	= htmlentities(trim($_POST['middle_name']));	
					$gender 		= htmlentities(trim($_POST['gender']));
					$dob	 		= htmlentities(trim($_POST['dob']));
					$sin			= htmlentities(trim($_POST['sin']));
					$bio 			= htmlentities(trim($_POST['bio']));
					$image_location	= htmlentities(trim($newpath));
					
					$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $user_id);
					header('Location: settings.php?success');
					exit();
				
				} else if (empty($errors) === false) {
					echo '<p>' . implode('</p><p>', $errors) . '</p>';	
				}	
            }
    		?>
         
    		<h2>Settings.</h2> <p><b>Note: Information you post here is made viewable to others.</b></p>
            <hr />

            <form action="" method="post" enctype="multipart/form-data">
                <div id="profile_picture">
                 
               		<h3>Change Profile Picture</h3>
                    <ul>
                        
        				<?php
                        if(!empty ($user['image_location'])) {
                            $image = $user['image_location'];
                            echo "<img src='$image'>";
                        }
                        ?>
                        
                        <li>
                        <input type="file" name="myfile" />
                        </li>
                        <?php if($image != 'avatars/default_avatar.png'){ ?>
	                        <li>
	                            <input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
	                        </li>
	                        <?php 
                        }
                        ?>
                    </ul>
                </div>
            
            	<div id="personal_info">
	            	<h3 >Change Profile Information </h3>
	                <ul>
	                    <li>
	                        <h4>First name:</h4>
	                        <input type="text" name="first_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
	                    </li> 
                         <li>
	                        <h4>Middle name:</h4>
	                        <input type="text" name="middle_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['middle_name']) ){echo htmlentities(strip_tags($_POST['middle_name']));} else { echo $user['middle_name']; }?>">
	                    </li>  
	                    <li>
	                        <h4>Last name: </h4>
	                        <input type="text" name="last_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
	                    </li>
	                    <li>
	                        <h4>Gender:</h4>
	                        <?php
	                       	 	$gender 	= $user['gender'];
	                        	$options 	= array("undisclosed", "Male", "Female");
	                            echo '<select name="gender">';
	                            foreach($options as $option){
	                               	if($gender == $option){
	                               		$sel = 'selected="selected"';
	                               	}else{
	                               		$sel='';
	                               	}
	                                echo '<option '. $sel .'>' . $option . '</option>';
	                            }
	                        ?>
	                        </select>
	                    </li>
                         <li>
	                        <h4>D.O.B (YYYY-MM-DD #:</h4>
	                        <input type="date ('yyyy-mm-dd')" name="dob" id="datepicker" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['dob']) ){echo htmlentities(strip_tags($_POST['dob']));} else { echo $user['dob']; }?>">
	                    </li>
                        <li>
	                        <h4>Social Insurance #:</h4>
	                        <input type="text" name="sin" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['sin']) ){echo htmlentities(strip_tags($_POST['sin']));} else { echo $user['sin']; }?>">
	                    </li>
	                    <li>
	                        <h4>Bio:</h4>
	                        <textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
	                    </li>
	            	</ul>    
            	</div>
            	<div class="clear"></div>
            	<hr />
            		<span>Update Changes:</span>
                    <input type="submit" value="Update">
               
            </form>
    </div>

</body>
</html>
<?php
}
and here is the user class

Code: Select all


<?php 
class Users{
 	
	private $db;

	public function __construct($database) {
	    $this->db = $database;
	}	
	
	public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $id){

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`bio`			= ?,
								`image_location`= ?
								
								WHERE `id` 		= ? 
								");

		$query->bindValue(1, $first_name);
		$query->bindValue(2, $middle_name);
		$query->bindValue(3, $last_name);
		$query->bindValue(4, $gender);
		$query->bindValue(5, $dob);
		$query->bindValue(6, $sin);
		$query->bindValue(7, $bio);
		$query->bindValue(8, $image_location);
		$query->bindValue(9, $id);
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}	
	}

	public function change_password($user_id, $password) {

		global $bcrypt;

		/* Two create a Hash you do */
		$password_hash = $bcrypt->genHash($password);

		$query = $this->db->prepare("UPDATE `users` SET `password` = ? WHERE `id` = ?");

		$query->bindValue(1, $password_hash);
		$query->bindValue(2, $user_id);				

		try{
			$query->execute();
			return true;
		} catch(PDOException $e){
			die($e->getMessage());
		}

	}

	public function recover($email, $generated_string) {

		if($generated_string == 0){
			return false;
		}else{
	
			$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `generated_string` = ?");

			$query->bindValue(1, $email);
			$query->bindValue(2, $generated_string);

			try{

				$query->execute();
				$rows = $query->fetchColumn();

				if($rows == 1){
					
					global $bcrypt;

					$username = $this->fetch_info('username', 'email', $email); // getting username for the use in the email.
					$user_id  = $this->fetch_info('id', 'email', $email);// We want to keep things standard and use the user's id for most of the operations. Therefore, we use id instead of email.
			
					$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
					$generated_password = substr(str_shuffle($charset),0, 10);

					$this->change_password($user_id, $generated_password);

					$query = $this->db->prepare("UPDATE `users` SET `generated_string` = 0 WHERE `id` = ?");

					$query->bindValue(1, $user_id);
	
					$query->execute();

					mail($email, 'Your password', "Hello " . $username . ",\n\nYour your new password is: " . $generated_password . "\n\nPlease change your password once you have logged in using this password.\n\n-Example team");

				}else{
					return false;
				}

			} catch(PDOException $e){
				die($e->getMessage());
			}
		}
	}

    public function fetch_info($what, $field, $value){

		$allowed = array('id', 'username', 'first_name', 'middle_name','last_name', 'gender', 'dob', 'sin', 'bio', 'email'); // I have only added few, but you can add more. However do not add 'password' eventhough the parameters will only be given by you and not the user, in our system.
		if (!in_array($what, $allowed, true) || !in_array($field, $allowed, true)) {
		    throw new InvalidArgumentException;
		}else{
		
			$query = $this->db->prepare("SELECT $what FROM `users` WHERE $field = ?");

			$query->bindValue(1, $value);

			try{

				$query->execute();
				
			} catch(PDOException $e){

				die($e->getMessage());
			}

			return $query->fetchColumn();
		}
	}

	public function confirm_recover($email){

		$username = $this->fetch_info('username', 'email', $email);// We want the 'id' WHERE 'email' = user's email ($email)

		$unique = uniqid('',true);
		$random = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),0, 10);
		
		$generated_string = $unique . $random; // a random and unique string

		$query = $this->db->prepare("UPDATE `users` SET `generated_string` = ? WHERE `email` = ?");

		$query->bindValue(1, $generated_string);
		$query->bindValue(2, $email);

		try{
			
			$query->execute();

			mail($email, 'Recover Password', "Hello " . $username. ",\r\nPlease click the link below:\r\n\r\nhttp://www.example.com/recover.php?email=" . $email . "&generated_string=" . $generated_string . "\r\n\r\n We will generate a new password for you and send it back to your email.\r\n\r\n-- Example team");			
			
		} catch(PDOException $e){
			die($e->getMessage());
		}
	}

	public function user_exists($username) {
	
		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
		$query->bindValue(1, $username);
	
		try{

			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				return true;
			}else{
				return false;
			}

		} catch (PDOException $e){
			die($e->getMessage());
		}

	}
	 
	public function email_exists($email) {

		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ?");
		$query->bindValue(1, $email);
	
		try{

			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				return true;
			}else{
				return false;
			}

		} catch (PDOException $e){
			die($e->getMessage());
		}

	}

	public function register($username, $password, $email){

		global $bcrypt; // making the $bcrypt variable global so we can use here

		$time 		= time();
		$ip 		= $_SERVER['REMOTE_ADDR']; // getting the users IP address
		$email_code = $email_code = uniqid('code_',true); // Creating a unique string.
		
		$password   = $bcrypt->genHash($password);

		$query 	= $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `ip`, `time`, `email_code`) VALUES (?, ?, ?, ?, ?, ?) ");

		$query->bindValue(1, $username);
		$query->bindValue(2, $password);
		$query->bindValue(3, $email);
		$query->bindValue(4, $ip);
		$query->bindValue(5, $time);
		$query->bindValue(6, $email_code);

		try{
			$query->execute();

			mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
		}catch(PDOException $e){
			die($e->getMessage());
		}	
	}

	public function activate($email, $email_code) {
		
		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `email_code` = ? AND `confirmed` = ?");

		$query->bindValue(1, $email);
		$query->bindValue(2, $email_code);
		$query->bindValue(3, 0);

		try{

			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				
				$query_2 = $this->db->prepare("UPDATE `users` SET `confirmed` = ? WHERE `email` = ?");

				$query_2->bindValue(1, 1);
				$query_2->bindValue(2, $email);				

				$query_2->execute();
				return true;

			}else{
				return false;
			}

		} catch(PDOException $e){
			die($e->getMessage());
		}

	}


	public function email_confirmed($username) {

		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ? AND `confirmed` = ?");
		$query->bindValue(1, $username);
		$query->bindValue(2, 1);
		
		try{
			
			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				return true;
			}else{
				return false;
			}

		} catch(PDOException $e){
			die($e->getMessage());
		}

	}

	public function login($username, $password) {

		global $bcrypt;  // Again make get the bcrypt variable, which is defined in init.php, which is included in login.php where this function is called

		$query = $this->db->prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
		$query->bindValue(1, $username);

		try{
			
			$query->execute();
			$data 				= $query->fetch();
			$stored_password 	= $data['password']; // stored hashed password
			$id   				= $data['id']; // id of the user to be returned if the password is verified, below.
			
			if($bcrypt->verify($password, $stored_password) === true){ // using the verify method to compare the password with the stored hashed password.
				return $id;	// returning the user's id.
			}else{
				return false;	
			}

		}catch(PDOException $e){
			die($e->getMessage());
		}
	
	}

	public function userdata($id) {

		$query = $this->db->prepare("SELECT * FROM `users` WHERE `id`= ?");
		$query->bindValue(1, $id);

		try{

			$query->execute();

			return $query->fetch();

		} catch(PDOException $e){

			die($e->getMessage());
		}

	}
	  	  	 
	public function get_users() {

		$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `time` DESC");
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}

		return $query->fetchAll();

	}	
}

Re: different date format in different browsers

Posted: Fri Jan 10, 2014 10:17 pm
by Celauran
There's the problem. The $dob we had defined earlier using strtotime() and date() is being overwritten by what's in the $_POST array.

Code: Select all

$dob	 = htmlentities(trim($_POST['dob']));