Jump to content

anybody did user registration/login ?


qwertyeee
 Share

Recommended Posts

The new user system will provide better support for developing your own user registration functions. But it's probably still a month or so before I'll have that ready. In the new user system, users are actually pages, so you can interact with them, add fields to them, and so on, in the same way.

  • Like 3
Link to comment
Share on other sites

  • 7 months later...

That's my code. I always use jquery for instant registration without refreshing page, so my code is composed of 3 parts.

The html form, the javascript that performs the validation (also check if username and email are already used) and the php that performs registration process. After registration user will redirect to profile page with welcome message.

There are some code lines you probably don't need but you can easily clean...simple php.

Note: because of jquery you cannot have the php code inside PW folders so i have an external folder called "process" with all my php files called by jquery at the same level of "site" folder, in this case "/process/register.php".

P.S.: i'm using jquery validate plugin for validation.

FORM

<script type="text/javascript" src="/site/templates/scripts/register.js"></script>
<div class="row">
		<div class="span16">
			<fieldset>
			<legend></legend>
			<form action='/iscrizione/' method='post' id="registerform">
				<div class="clearfix"><label for="login_name">Username</label><div class="input"><input type="text" id="login_name" name="login_name" value="" maxlength="50" /></div></div>
				<div class="clearfix"><label for="login_pass">Password</label><div class="input"><input type="password" id="login_pass" name="login_pass" value="" /></div></div>
				<div class="clearfix"><label for="confirm_pass">Ripeti password</label><div class="input"><input type="password" name="confirm_pass" value="" /></div></div>
				<div class="clearfix"><label for="email">Email</label><div class="input"><input type="text" name="email" id="email" value="" maxlength="40" /></div></div>
				<div class="actions">
					<input type="submit" value="Iscriviti" class="btn primary" name="register_submit" id="register_submit" />
				</div>

			</form>
			</fieldset>
		</div>
	</div>

JS

$(document).ready(function(){

$("#registerform").validate({
	debug: false,
	rules: {
		login_name: {
			required: true,
			minlength: 6,
			remote: "/process/username.php"
		},
		login_pass: {
			required: true,
			minlength: 6
		},
		confirm_pass: {
			required: true,
			minlength: 6,
			equalTo: "#login_pass"
		},
		email: {
			required: true,
			email: true,
			remote: "/process/emails.php"
		}
	},
	messages: {
		login_name: {
			required: "Inserisci il tuo username",
			minlength: jQuery.format("Inserisci almeno {0} caratteri"),
			remote: jQuery.validator.format("Lo username {0} non è disponibile.")
		},
		login_pass: {
			required: "Inserisci la password",
			minlength: jQuery.format("Inserisci almeno {0} caratteri")
		},
		confirm_pass: {
			required: "Ripeti la password",
			minlength: jQuery.format("Inserisci almeno {0} caratteri"),
			equalTo: "Le password non sono uguali"
		},
		email: {
			required: true,
			email: "Inserisci una email valida",
			remote: jQuery.validator.format("Questa email è già presente nel nostro database.")	
		},
	},
	submitHandler: function(form) {
		$("#register_submit").attr('value','Attendi...');
		$("#register_submit").attr('disabled', 'disabled');
		$.post('/process/register.php', $("#registerform").serialize(), function(data) {
			if (data=='success'){
				var url = "/mioprofilo/";    
				$(location).attr('href',url);
			}else{
				$(".span16").prepend(
			    	$(data).hide().fadeIn('slow')
			    );  
			    $(".error").fadeOut(5000);  
				$("#register_submit").attr('value','Iscriviti');    
				$("#register_submit").removeAttr('disabled');
			}
		});
	}
});

});

PHP

<?php
require_once('../index.php');
require_once('class.tempmail.php');
$input = wire('input');
$sanitizer = wire('sanitizer');
$roles = wire('roles');
if($input->post->register_submit) {
$username   		= $sanitizer->username($input->post->login_name);
$pass    	 		= $input->post->login_pass;
$email   	 		= $sanitizer->email($input->post->email);
$u 		 	 		= new User();
$u->name 	 		= $username; 
$u->pass 	 		= $pass;
$u->email 	 		= $email;
$u->roles->add($roles->get("guest"));
$u->roles->add($roles->get("utente-basic")); // my custom role
$u->save();
       // i add profile picture to every user after registration using 5 different random avatar images.
$pnum = rand(0,5);
$profilephoto = wire('config')->paths->root."site/templates/styles/images/noprofile".$pnum.".jpg";
$u->profilephoto->add($profilephoto);
$u->profilethumb->add($profilephoto);
$u->save();

if (wire('session')->login($username, $pass)){

	$array_content[]=array("username", $username);  
	$array_content[]=array("login", $username);  
	$array_content[]=array("password", $pass);

	$admin_id	 =  "noreply@domain.com";
	$user_email  =  $email;

	sendingemail_phpmailer($array_content, "register.html","class.phpmailer.php","Sitename",$admin_id,$user_email,"Welcome to website");

	print "success";
}else{
	print '<div class="alert-message error">
       <p>Errore durante la registrazione. Riprova.</p>
     </div>';
}
}
?>

Code for checking the existing email (or username, same code, just change variable)

<?php
require_once('../index.php');
$email = trim(strtolower($_REQUEST['email']));	
$sql_check=wire('users')->find("email=$email");	
if($sql_check<>""){
echo 'false';
}else{
echo 'true';
}
?>

And that's the login

HTML FORM

<?php if ($session->get("_user_id")){
$session->redirect('/');
} ?>
<? include('./head.inc'); ?>
<div class="topbar">
 <div class="fill">
   <div class="container">
     <h3><a href="/">Sitename</a></h3>
     <ul class="nav">
       <li class="active"><a href="/">Login</a></li>
     </ul>
   </div>
 </div>
</div>
<br><br><br>
<script type="text/javascript" src="/site/templates/scripts/login.js"></script>
<div class="container">
<div class="content">
	<div class="page-header">
		<h1><?php echo $page->title; ?><small> effettua l'accesso</small></h1>
	</div>
	<div class="row">
		<div class="span16">
			<fieldset id="formlogin">
			<legend>Login</legend>
			<form action='/login/' method='post' id="loginform">
				<div class="clearfix"><label for="login_name">Username</label><div class="input"><input type="text" name="login_name" value="" class="required" /></div></div>
				<div class="clearfix"><label for="login_pass">Password</label><div class="input"><input type="password" name="login_pass" value="" class="required" /></div></div>				
				<div class="actions">
					<input type="submit" value="Accedi" class="btn primary" name="login_submit" id="login_submit" />
				</div>
			</form>
			</fieldset>
		</div>
	</div>
</div>
<? include('./foot.inc'); ?>
</div> <!-- /container -->
</body>
</html>

JS

$(document).ready(function(){

$("#loginform").validate({
	debug: false,
	rules: {
		login_name: {
			required: true
		},
		login_pass: {
			required: true
		}
	},
	messages: {
		login_name: "Inserisci il tuo username",
		login_pass: "Inserisci la password",
	},
	submitHandler: function(form) {
		$("#login_submit").attr('value','Sto accedendo...');
		$("#login_submit").attr('disabled', 'disabled');
		$.post('/process/login.php', $("#loginform").serialize(), function(data) {
			if (data=='success'){
				var url = "/";    
				$(location).attr('href',url);
			}else{
				$(".span16").prepend(
			    	$(data).hide().fadeIn('slow')
			    );  
			    $(".error").fadeOut(5000);  
				$("#login_submit").attr('value','Accedi');    
				$("#login_submit").removeAttr('disabled');
			}
		});
	}
});

});

PHP

<?php
require_once('../index.php');
$input = wire('input');
if($input->post->login_submit) {
$name = wire('sanitizer')->username($input->post->login_name);
$pass = $input->post->login_pass;
if(wire('session')->login($name, $pass)){
	print 'success';
}else{
	print '<div class="alert-message error">
       <p>Dati non validi. Riprova</p>
     </div>';
}
}
?>

After registration i send a welcome email.

That's the tempmail php that use the well known phpmailer class for sending emails adding templating functionality. You need to download the class.phpmailer.php from the web.

<?
function sendingemail_phpmailer ($var_array,$template,$phpmailer,$FromName,$From,$to,$Subject,$videolist){
	if (!is_array($var_array)){
		echo "first variable should be an array. ITS NOT !";
		exit;
	}
	require_once($phpmailer);

	$mail = new PHPMailer();
	$mail->IsSendmail(); // telling the class to use SMTP
	$mail->Host = ""; // SMTP server
	$mail->FromName = $FromName;
	$mail->Sender = $FromName;
	$mail->From = $From;
	$mail->AddAddress($to);
	$mail->Subject = $Subject;
	$mail->IsHTML(true); 

	$filename = $template;
	$fd = fopen ($filename, "r");
	$mailcontent = fread ($fd, filesize ($filename));

	foreach ($var_array as $key=>$value){
		$mailcontent = str_replace("%%$value[0]%%", $value[1],$mailcontent );
	}

	$mailcontent = stripslashes($mailcontent);

	fclose ($fd);
	$mail->Body=$mailcontent;
	if(!$mail->Send()){
	   echo "Errore durante l'invio del messaggio";
	   exit;
	}
}
?>
  • Like 3
Link to comment
Share on other sites

Thanks for posting this Sevarf2, it's good and interesting to see one approach to this.

One thing I wanted to mention in your code for checking existing email, it's preferable to sanitize the value before including it in a selector. Less important, but it's also preferable to get it from wire('input') rather than from something like $_GET, $_POST or $_REQUEST since it will account for annoying server-side settings like magic_quotes. So here would be an update to that script:

<?php
require_once('../index.php');
$email = wire('sanitizer')->email(wire('input')->post->email));	
$sql_check = wire('users')->find("email=$email");	
if(count($sql_check)) {
echo 'false';
} else {
echo 'true';
}

Also I recommend leaving the closing PHP tag "?>" out if it's the end of the file. The reason is that it's unnecessary, and causes problems if any whitespace happens to end up after it. Of course the whitespace is invisible, so it leads to difficult to find bugs. :) Best just to skip the ?> at the end of the file.

Link to comment
Share on other sites

There's actually nothing wrong with using the PHP vars like $_GET and $_POST (or $_REQUEST if necessary). But ProcessWire saves you the step of having to check for magic quotes, so it's usually easier to use the ones that PW supplies. But if you are checking for non-string type stuff (that would never have quotes) then it doesn't matter much what you use.

Link to comment
Share on other sites

  • 1 year later...
Note: because of jquery you cannot have the php code inside PW folders so i have an external folder called "process" with all my php files called by jquery at the same level of "site" folder, in this case "/process/register.php".

Why it's not possibile to have php code inside PW folders using jquery? Can anyone explain this to me ? :)

Link to comment
Share on other sites

@3fingers: The default .htaccess in PW blocks access to PHP files in certain locations:

  # Block access to any PHP-based files in /templates-admin/
  RewriteCond %{REQUEST_URI} (^|/)(wire|site|site-[^/]+)/templates-admin($|/|/.*\.(php|html?|tpl|inc))$ [OR]
  # Block access to any PHP or markup files in /site/templates/
  RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/templates($|/|/.*\.(php|html?|tpl|inc))$ [OR]
  # Block access to any PHP files in /site/assets/
  RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/assets($|/|/.*\.php)$ [OR]
  # Block access to any PHP files in core or core module directories
  RewriteCond %{REQUEST_URI} (^|/)wire/(core|modules)/.*\.(php|inc|tpl|module)$ [OR]
  # Block access to any PHP files in /site/modules/
  RewriteCond %{REQUEST_URI} (^|/)(site|site-[^/]+)/modules/.*\.(php|inc|tpl|module)$ [OR]
I'm not sure what the situation was back in 2011, but at least currently you can access php files directly under site/ or in any custom directory (like site/process/). The rules in .htaccess are just to block direct access to files that are supposed to be run/accessed via PW. So if you want to put some standalone code (or a script bootstrapping PW of course) in site/ directory you can, as long as it's not inside directories used internally by PW itself.
  • Like 2
Link to comment
Share on other sites

That totally makes sense to me.

Infact i misread Sevarf2's post where he wrote:

... all my php files called by jquery at the same level of "site" folder ....

 "Same level" != "chidren of" :)

Thanks for your explanation @nik, helpful anyway.

Link to comment
Share on other sites

HI @Sevarf2,

I'm trying to integrate your code (thanks :)) but I cannot find my way out of this since I'd like to know the folder structure of those files and their respective names, just to save me some time to undestrand which files go where.

Could you please provide me this infos?

Really appreciated.

P.s (Parli italiano?).

Thanks!

Link to comment
Share on other sites

  • 1 month later...

@Sevarf2, I am also trying to integrate your code and having some difficulties to setup file and folder structures.

I have following folder setup:

site

templates

signup.php  --> what would be form action page [<form action='/iscrizione/' method='post' id="registerform">]

login.php

scripts

register.js    --> what would be value, is it page  [$("#register_submit").attr('value','Iscriviti'); ]

login.js         

wire

process --> new folder as per your setup

emails.php

login.php

register.php

username.php

Do I have to add as template into PW and setup as page from that template. if yes then please describe.

Your help is much appreciated. Thank you!

Link to comment
Share on other sites

  • 4 weeks later...

No I haven't but I went with different approach. I kept the new folder "Process" and developed stand-alone web application using Flourish UnFramework with MVC. I used separate database for the web application which is based on RDBMS concept. I tried my best to use with PW to develop membership portal but I hit the wall so many time so I used my OO experinece to develop web application using MVC style. I know quite a bit of you guys have done it but I had not enough time to experiment anything at that time. 

Link to comment
Share on other sites

  • 10 months later...

That's my code. I always use jquery for instant registration without refreshing page, so my code is composed of 3 parts.

The html form, the javascript that performs the validation (also check if username and email are already used) and the php that performs registration process. After registration user will redirect to profile page with welcome message.

There are some code lines you probably don't need but you can easily clean...simple php.

Note: because of jquery you cannot have the php code inside PW folders so i have an external folder called "process" with all my php files called by jquery at the same level of "site" folder, in this case "/process/register.php".

P.S.: i'm using jquery validate plugin for validation.

FORM

<script type="text/javascript" src="/site/templates/scripts/register.js"></script>
<div class="row">
			<div class="span16">
				<fieldset>
				<legend></legend>
				<form action='/iscrizione/' method='post' id="registerform">
					<div class="clearfix"><label for="login_name">Username</label><div class="input"><input type="text" id="login_name" name="login_name" value="" maxlength="50" /></div></div>
					<div class="clearfix"><label for="login_pass">Password</label><div class="input"><input type="password" id="login_pass" name="login_pass" value="" /></div></div>
					<div class="clearfix"><label for="confirm_pass">Ripeti password</label><div class="input"><input type="password" name="confirm_pass" value="" /></div></div>
					<div class="clearfix"><label for="email">Email</label><div class="input"><input type="text" name="email" id="email" value="" maxlength="40" /></div></div>
					<div class="actions">
						<input type="submit" value="Iscriviti" class="btn primary" name="register_submit" id="register_submit" />
					</div>
					
				</form>
				</fieldset>
			</div>
		</div>
JS
$(document).ready(function(){
	
	$("#registerform").validate({
		debug: false,
		rules: {
			login_name: {
				required: true,
				minlength: 6,
				remote: "/process/username.php"
			},
			login_pass: {
				required: true,
				minlength: 6
			},
			confirm_pass: {
				required: true,
				minlength: 6,
				equalTo: "#login_pass"
			},
			email: {
				required: true,
				email: true,
				remote: "/process/emails.php"
			}
		},
		messages: {
			login_name: {
				required: "Inserisci il tuo username",
				minlength: jQuery.format("Inserisci almeno {0} caratteri"),
				remote: jQuery.validator.format("Lo username {0} non è disponibile.")
			},
			login_pass: {
				required: "Inserisci la password",
				minlength: jQuery.format("Inserisci almeno {0} caratteri")
			},
			confirm_pass: {
				required: "Ripeti la password",
				minlength: jQuery.format("Inserisci almeno {0} caratteri"),
				equalTo: "Le password non sono uguali"
			},
			email: {
				required: true,
				email: "Inserisci una email valida",
				remote: jQuery.validator.format("Questa email è già presente nel nostro database.")	
			},
		},
		submitHandler: function(form) {
			$("#register_submit").attr('value','Attendi...');
			$("#register_submit").attr('disabled', 'disabled');
			$.post('/process/register.php', $("#registerform").serialize(), function(data) {
				if (data=='success'){
					var url = "/mioprofilo/";    
					$(location).attr('href',url);
				}else{
					$(".span16").prepend(
				    	$(data).hide().fadeIn('slow')
				    );  
				    $(".error").fadeOut(5000);  
					$("#register_submit").attr('value','Iscriviti');    
					$("#register_submit").removeAttr('disabled');
				}
			});
		}
	});
	

});
PHP
<?php
require_once('../index.php');
require_once('class.tempmail.php');
$input = wire('input');
$sanitizer = wire('sanitizer');
$roles = wire('roles');
if($input->post->register_submit) {
	$username   		= $sanitizer->username($input->post->login_name);
	$pass    	 		= $input->post->login_pass;
	$email   	 		= $sanitizer->email($input->post->email);
	$u 		 	 		= new User();
	$u->name 	 		= $username; 
	$u->pass 	 		= $pass;
	$u->email 	 		= $email;
	$u->roles->add($roles->get("guest"));
	$u->roles->add($roles->get("utente-basic")); // my custom role
	$u->save();
        // i add profile picture to every user after registration using 5 different random avatar images.
	$pnum = rand(0,5);
	$profilephoto = wire('config')->paths->root."site/templates/styles/images/noprofile".$pnum.".jpg";
	$u->profilephoto->add($profilephoto);
	$u->profilethumb->add($profilephoto);
	$u->save();
	
	if (wire('session')->login($username, $pass)){
		
		$array_content[]=array("username", $username);  
		$array_content[]=array("login", $username);  
		$array_content[]=array("password", $pass);
		
		$admin_id	 =  "noreply@domain.com";
		$user_email  =  $email;
	 
		sendingemail_phpmailer($array_content, "register.html","class.phpmailer.php","Sitename",$admin_id,$user_email,"Welcome to website");
		
		print "success";
	}else{
		print '<div class="alert-message error">
        <p>Errore durante la registrazione. Riprova.</p>
      </div>';
	}
}
?>
Code for checking the existing email (or username, same code, just change variable)
<?php
require_once('../index.php');
$email = trim(strtolower($_REQUEST['email']));	
$sql_check=wire('users')->find("email=$email");	
if($sql_check<>""){
	echo 'false';
}else{
	echo 'true';
}
?>
And that's the login

HTML FORM

<?php if ($session->get("_user_id")){
	$session->redirect('/');
} ?>
<? include('./head.inc'); ?>
<div class="topbar">
  <div class="fill">
    <div class="container">
      <h3><a href="/">Sitename</a></h3>
      <ul class="nav">
        <li class="active"><a href="/">Login</a></li>
      </ul>
    </div>
  </div>
</div>
<br><br><br>
<script type="text/javascript" src="/site/templates/scripts/login.js"></script>
<div class="container">
	<div class="content">
		<div class="page-header">
			<h1><?php echo $page->title; ?><small> effettua l'accesso</small></h1>
		</div>
		<div class="row">
			<div class="span16">
				<fieldset id="formlogin">
				<legend>Login</legend>
				<form action='/login/' method='post' id="loginform">
					<div class="clearfix"><label for="login_name">Username</label><div class="input"><input type="text" name="login_name" value="" class="required" /></div></div>
					<div class="clearfix"><label for="login_pass">Password</label><div class="input"><input type="password" name="login_pass" value="" class="required" /></div></div>				
					<div class="actions">
						<input type="submit" value="Accedi" class="btn primary" name="login_submit" id="login_submit" />
					</div>
				</form>
				</fieldset>
			</div>
		</div>
	</div>
	<? include('./foot.inc'); ?>
</div> <!-- /container -->
</body>
</html>
JS
$(document).ready(function(){

	$("#loginform").validate({
		debug: false,
		rules: {
			login_name: {
				required: true
			},
			login_pass: {
				required: true
			}
		},
		messages: {
			login_name: "Inserisci il tuo username",
			login_pass: "Inserisci la password",
		},
		submitHandler: function(form) {
			$("#login_submit").attr('value','Sto accedendo...');
			$("#login_submit").attr('disabled', 'disabled');
			$.post('/process/login.php', $("#loginform").serialize(), function(data) {
				if (data=='success'){
					var url = "/";    
					$(location).attr('href',url);
				}else{
					$(".span16").prepend(
				    	$(data).hide().fadeIn('slow')
				    );  
				    $(".error").fadeOut(5000);  
					$("#login_submit").attr('value','Accedi');    
					$("#login_submit").removeAttr('disabled');
				}
			});
		}
	});

});
PHP
<?php
require_once('../index.php');
$input = wire('input');
if($input->post->login_submit) {
	$name = wire('sanitizer')->username($input->post->login_name);
	$pass = $input->post->login_pass;
	if(wire('session')->login($name, $pass)){
		print 'success';
	}else{
		print '<div class="alert-message error">
        <p>Dati non validi. Riprova</p>
      </div>';
	}
}
?>
After registration i send a welcome email.

That's the tempmail php that use the well known phpmailer class for sending emails adding templating functionality. You need to download the class.phpmailer.php from the web.

<?
	function sendingemail_phpmailer ($var_array,$template,$phpmailer,$FromName,$From,$to,$Subject,$videolist){
		if (!is_array($var_array)){
			echo "first variable should be an array. ITS NOT !";
			exit;
		}
		require_once($phpmailer);
		
		$mail = new PHPMailer();
		$mail->IsSendmail(); // telling the class to use SMTP
		$mail->Host = ""; // SMTP server
		$mail->FromName = $FromName;
		$mail->Sender = $FromName;
		$mail->From = $From;
		$mail->AddAddress($to);
		$mail->Subject = $Subject;
		$mail->IsHTML(true); 
		
		$filename = $template;
		$fd = fopen ($filename, "r");
		$mailcontent = fread ($fd, filesize ($filename));
								
		foreach ($var_array as $key=>$value){
			$mailcontent = str_replace("%%$value[0]%%", $value[1],$mailcontent );
		}
								
		$mailcontent = stripslashes($mailcontent);
								
		fclose ($fd);
		$mail->Body=$mailcontent;
		if(!$mail->Send()){
		   echo "Errore durante l'invio del messaggio";
		   exit;
		}
	}
?>

isn't the user login page and registration page are ordinary plain html instead of PW pages with assoicated template file (user login template file and registration template file ) ?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...