Sicurezza nella registrazione

leon-kennedy

Utente Attivo
19 Mag 2010
147
0
0
Ciao a tutti!Vorrei rendere più sicura la registrazione al mio sito CRIPTANDO le password degli iscritti con MD5 e inserendo un modulo CAPTCHA.
A inoltre vorrei anche poter inserire la data di registrazione.

Ecco il codice che ho scritto finora:

PHP:
<?php

include('connect.php');

function filtro_db($stringa) 
{ 
    $stringa = trim ($stringa); 
    if(empty($stringa)) 
    { 
        return FALSE; 
    } 
    else if(get_magic_quotes_gpc()) 
    { 
        stripslashes($stringa); 
    } 
    return mysql_real_escape_string($stringa); 
} 

$user = filtro_db($_POST['user']); 
$pass = filtro_db($_POST['pass']);   
$mail = filtro_db($_POST['mail']);   
$manager = filtro_db($_POST['manager']);   
$team = filtro_db($_POST['team']);   

//controllo se i campi sono vuoti 

if(!$user || !$pass || !$mail || !$manager || !$team)   
    { 
        header("location:error1.php"); 
        exit; 
    } 

//controllo che la mail sia scritta in modo corretto 
if (!ereg("^[a-z0-9][_.a-z0-9-]+@([a-z0-9][0-9a-z-]+.)+([a-z]{2,4})",$mail)) 
    { 
        header("location:error3.php"); 
        exit; 
    }
if(!preg_match('/^[A-Za-z0-9]{6,25}$/',$user))
if(!preg_match('/^[A-Za-z0-9]{6,25}$/',$pass))
if(!preg_match('/^[A-Za-z0-9]{6,25}$/',$manager))
if(!preg_match('/^[A-Za-z0-9]{6,25}$/',$team))
{
header("location:error4.php");
exit;
}
//verifico se ci sono utenti con lo stesso user o email 
$query_1=mysql_query("SELECT * FROM iscritti WHERE email='".$mail."' or nickname='".$user."'") 
or die("errore nella query;".mysql_error()); 
$num=mysql_num_rows($query_1); 
//se ci sono campi gia occupati 
if($num > 0) 
{ 
header("location:error2.php"); 
exit; 
} 

//altrimenti procedo con l'inserimento 

else 
{ 
$query_insert=mysql_query("INSERT INTO iscritti 
(nickname, password, email, manager, team) 
VALUES 
('$user', '$pass', '$mail', '$manager', 
'$team')")or die("errore nella query;".mysql_error()); 

$query_insert=mysql_query("INSERT INTO squadra_dati 
(manager, team, punti, livello, cash, vittorie, pareggi, sconfitte) 
VALUES 
('$manager', '$team', '0', 'Amateur League', '10000000 Coins' '0' '0' '0')")or die("errore nella query;".mysql_error()); 

header("location:reg_success.php"); 

function mostra_form() 
{ 
if(isset($_GET['msg'])) 
echo '<b>'.htmlentities($_GET['msg']).'</b><br /><br />'; 
}
}
?>

Grazie e buona giornata!
 

alessandro1997

Utente Attivo
6 Ott 2009
5.302
1
0
26
Roma
alessandro1997.netsons.org
Purtroppo non ho molto tempo, quindi ti posso dare solamente qualche consiglio teorico.
  1. È meglio criptare le password in SHA1, invece che in MD5.
  2. È meglio usare PDO (PHP Data Object) ed imparare ad utilizzare le prepared statements.
  3. È meglio usare il salt delle password.
La prossima volta cercherò anche di scrivere un po' di codice ;)
 

leon-kennedy

Utente Attivo
19 Mag 2010
147
0
0
Se quando hai un pò di tempo puoi farmi un esempio te ne sarei grato! ;)

Invece per la data della registrazione come posso fare!
Nella tabella "iscritti" ho creato il campo

"data_reg" datetime
 

leon-kennedy

Utente Attivo
19 Mag 2010
147
0
0
Grazie a entrambi,ho creato una pagina a parte chiamata "controllo.php" e ho fatto questo:

PHP:
<?
//facciamo partire la sessione
session_start();

//creaiamo la stringa random e criptiamola
$crypt = sha1(microtime() * mktime());

//preleviamo una porzione della stringa
$str = substr($crypt,0,4);

//indichiamo il percorso all'immagine
$img = imagecreatefrompng("./img.png");

//inseriamo degli elementi grafici all'interno del file
$color = imagecolorallocate($img, 0, 0, 0);
$linea = imagecolorallocate($img,239,239,239);
imageline($img,0,0,49,39,$linea);
imageline($img,40,0,64,29,$linea);

//scriviamo la stringa nell'immagine
imagestring($img, 5, 20, 10, $str, $color);

//salviamo la stringa in sessione
$_SESSION['control'] = sha1($str);

//mostriamo a video l'immagine
header("Content-type: image/png");
imagepng($img);

if(sha1($_POST['stringa']) != $_SESSION['control'])
{
  die("Sei forse uno spam robot?");
}else{
  echo 'Ciao Essere Umano!';
}

?>
Non mi è però ancora ben chiaro il fatto delle immagini del CAPTCHA qualcuno può spiegarmi meglio con qualche esempio?0:)
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Ciao ragazzi, io mi collego alla discussione perchè proprio in questi giorni sto avendo un problema ad inserire un CAPTCHA e vedo che nella discussione ci sono Eliox ed Ale che mi hanno già aiutato altre volte.

Allora....io ho questo CAPTCHA e mi pare funzioni
PHP:
<?php
session_start();
    define("WIDTH", 200);
    define("HEIGHT", 70);

	define("F_SIZE", 20);
    define("F_ANGLE", 0);
$rnd = rand(1,4);
switch ($rnd) 
{
	case 1:
		define("F_FONT", "myfont.ttf");
		break;
	case 2:
		define("F_FONT", "myfont2.ttf");
		break;
	case 3:
		define("F_FONT", "myfont3.ttf");
		break;
	case 4:
		define("F_FONT", "myfont4.ttf");
		break;
}

	$img = imagecreate(WIDTH, HEIGHT);

    $white = imagecolorallocate($img, 255,255,255);
    $brdr = imagecolorallocate($img, 0,0,0);
	$black = imagecolorallocate($img, rand(0,150),rand(0,150),rand(0,150));

    $start_x = rand(10,15);
    $start_y = (int)HEIGHT/2;

    imagerectangle($img, 0,0,WIDTH-1,HEIGHT-1, $brdr);

	$text = chr(rand(65,90));
	$key = $text;
    imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+30, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+60, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+90, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+120, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+150, $start_y + (rand(-5,5)), $black, F_FONT, $text);

$_SESSION["hash"]=$key;

$rnd = rand(1,9);
switch ($rnd) 
{
	case 1:
		$img_copy = imagecreatefrompng("captcha.png");
		break;
	case 2:
		$img_copy = imagecreatefrompng("captcha2.png");
		break;
	case 3:
		$img_copy = imagecreatefrompng("captcha3.png");
		break;
	case 4:
		$img_copy = imagecreatefrompng("captcha4.png");
		break;
	case 5:
		$img_copy = imagecreatefrompng("captcha5.png");
		break;
	case 6:
		$img_copy = imagecreatefrompng("captcha6.png");
		break;
	case 7:
		$img_copy = imagecreatefrompng("captcha7.png");
		break;
	case 8:
		$img_copy = imagecreatefrompng("captcha8.png");
		break;
	case 9:
		$img_copy = imagecreatefrompng("captcha9.png");
		break;
}
imagecopymerge($img, $img_copy, 0, 0, 0, 0, imagesx($img), imagesy($img), rand(10,30));
header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>

E vorrei inserirlo in questo form di registrazione che però controlla i campi con javascript:

PHP:
<?php
session_start();	// Maintain session state
header("Cache-control: private");	// Fixes IE6's back button problem.

// Dont allow members to go to add user page
if(@$_SESSION['user']) header("location: login.php");
elseif(@$_POST['user']){
	// Get and set vars (without html characters)
	$user = htmlspecialchars(strtolower($_POST["user"]));
	$pass = htmlspecialchars($_POST["pass"]);
	$permission = 0;		// Default: user, until admin changes
	$email = htmlspecialchars($_POST["email"]);
	$url = htmlspecialchars($_POST["url"]);

	// Add dots to date
	if($_POST["day"]) $dob = $_POST["day"]. ".". $_POST["month"]. ".". $_POST["year"];
	else $dob = false;

	$location = htmlspecialchars($_POST["location"]);
	$joined = $_POST["joined"];

	// Create the string to append
	$string = "\r\n". $user. "<del>". md5($pass). "<del>". $permission. "<del>". $email. "<del>". $url. "<del>". $dob. "<del>". $location. "<del>". $joined;

	// Make sure username doesn't already exist
	//-----------------------------------------
	// Include the flat-file
	$file = file("users.php") or die("Problem getting the user details flat-file [users.php]");

	// Get the size of file
	$totalLines = sizeof($file);

	// Get the users details line by line
	$line = 0;
	$match = 0;
	do{
		// Check the line isn't a comment
		if("//" != substr($file[$line], 0, 2)){
			// Break our records up
			@list($username, $password, $permission, $email, $url, $dob, $location, $joined) = explode("<del>", $file[$line]);

			// Check the username and passwords match
			if((strtolower($user) == strtolower($username))) $match = 1;
			else $match = 0;
		}

		// Exit loop if match found
		if($match) break;
			
		// Increment line count
		$line++;
	} while($line < $totalLines);

	// Only add new user if a match is not found
	if($match){
	?>
		<script language = "javascript" type = "text/javascript">
		<!-- // Go back
			alert("Username already taken, taking you back to choose another");
			history.go(-1);
		-->
		</script>
	<?php
	}
	else{
		// Open the users file
		$fp = fopen("users.php", "a+");

		// Append the new user to end of users file
		fwrite($fp, $string);

		// Close the file
		fclose($fp);

		// Redirect to index
		header("location: index.php?new=1");
	}
}
else{
?>
<html>
<head>

<link rel = "stylesheet" type = "text/css" href = "style.css">
<title>members area: mike holloway</title>
</head>
<body onload = "document.getElementById('user').focus();">
<form method = "post" action = "<?php print($_SERVER['PHP_SELF']); ?>">
<table border = "0" cellspacing = "0" cellpadding = "10" width = "50%" align = "center" style = "height: 100%;">
	<tr>
		<td colspan = "3" valign = "bottom">
			<span class = "bold">join our member list!</span>	<br>
			<span class = "hilight">hilighted text are required fields</span>
		</td>
	</tr>
	<tr>
		<td colspan = "3" height = "5%">
			<a href = "index.php">back</a>
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			<span class = "hilight">username:</span>
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "user" name = "user" style = "width: 80%" class = "text" tabindex = "1">
		</td>
		<td rowspan = "7" width = "16" height = "16" align = "right" valign = "bottom">
			<input type = "hidden" name = "joined" value = "<?php print(date("d.m.Y H:i:s", mktime())); ?>">
			<input type = "Image" src = "next.gif" width  = "16" height = "16" name = "submit" alt = "arrow pointing right: next" border = "0" align = "top" onfocus = "return checkFields();" tabindex = "10"></a>
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			<span class = "hilight">password:</span>
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "password" id = "pass" name = "pass" style = "width: 80%" class = "text" tabindex = "2">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			<span class = "hilight"> confirm password:</span>
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "password" id = "pass2" name = "pass2" style = "width: 80%" class = "text" tabindex = "3">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			email:
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "email" name = "email" style = "width: 80%" class = "text" tabindex = "4">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			http://
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "url" name = "url" style = "width: 80%" class = "text" tabindex = "5">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			date of birth:
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<span class = "bold">d: </span><input type = "text" id = "day" name = "day" size = "2" class = "text"  maxlength = "2" tabindex = "6"> <span class = "bold">m: </span><input type = "text" id = "month" name = "month" size = "2" class = "text"  maxlength = "2" tabindex = "7"> <span class = "bold">y: </span><input type = "text" id = "year" name = "year" size = "4" class = "text"  maxlength = "4" tabindex = "8">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			location:
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "location" name = "location" style = "width: 80%" class = "text" tabindex = "9">
		</td>
	</tr>
	<tr>
		<td colspan = "3" valign = "top">
			&nbsp;
		</td>
	</tr>
</table>
</form>

<script language = "javascript" type = "text/javascript">
<!--// Check field values are correct before submitting
	function checkFields(){
		var flag = 1;	// Return flag

		// Check for empty values in important fields first
		if(!document.getElementById("user").value || !document.getElementById("pass").value || !document.getElementById("pass2").value){
			alert("Please enter values in the following:\n\nUSERNAME\nPASSWORD\nCONFIRM PASSWORD");
			document.getElementById("user").focus();
			return true;
		}
		// Check that passwords are the same
		else if(document.getElementById("pass").value != document.getElementById("pass2").value){
			alert("Please enter two matching passwords");
			document.getElementById("pass").value = '';
			document.getElementById("pass2").value = '';
			document.getElementById("pass").focus();
			return true;
		}
		// Check the day / month / year fields if there's a value in one of them
		else if(document.getElementById("day").value || document.getElementById("month").value || document.getElementById("year").value){

			// Check day first
			if((isNaN(document.getElementById("day").value)) || (document.getElementById("day").value > 31) || (document.getElementById("day").value < 1)){
			alert("Please enter a valid day in the DOB field");
			document.getElementById("day").value = '';
			document.getElementById("day").focus();
			return true;
			}
			// Check month next
			else if((isNaN(document.getElementById("month").value)) || (document.getElementById("month").value > 12) || (document.getElementById("month").value < 1)){
				alert("Please enter a valid month in the DOB field");
				document.getElementById("month").value = '';
				document.getElementById("month").focus();
				return true;
			}
			// Finally the year
			else if((isNaN(document.getElementById("year").value)) || (document.getElementById("year").value >= <?php print date("Y", mktime()); ?>) || (document.getElementById("year").value < 1)){
				alert("Please enter a valid year in the DOB field");
				document.getElementById("year").value = '';
				document.getElementById("year").focus();
				return true;
			}
			else flag = 0;
		}
		else flag = 0;

		// One final check if the others went through fine
		if(!flag){
			if(document.getElementById("email").value){
				// Finally, check the email
				if(document.getElementById("email").value.indexOf("@") == -1 || document.getElementById("email").value.indexOf(".") == -1){
					alert("If entering an email addy, please make sure it is valid");
					document.getElementById("email").focus();
					return true;
				}
				else return false;
			}
			else return false;
		}
	}
-->
</script>
</body>
</html>
<?php
}
?>

E questo due cose funzionano perchè le ho comunque prese da materiale disponibile tra gli script del sito....
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Ora, per mettere il CAPTCHA nel form mi basta fare:

PHP:
<html>
<head>

<link rel = "stylesheet" type = "text/css" href = "style.css">
<title>members area: mike holloway</title>
</head>
<body onload = "document.getElementById('user').focus();">
<form method = "post" action = "<?php print($_SERVER['PHP_SELF']); ?>">
<table border = "0" cellspacing = "0" cellpadding = "10" width = "50%" align = "center" style = "height: 100%;">
	<tr>
		<td colspan = "3" valign = "bottom">
			<span class = "bold">join our member list!</span>	<br>
			<span class = "hilight">hilighted text are required fields</span>
		</td>
	</tr>
	<tr>
		<td colspan = "3" height = "5%">
			<a href = "index.php">back</a>
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			<span class = "hilight">username:</span>
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "user" name = "user" style = "width: 80%" class = "text" tabindex = "1">
		</td>
		<td rowspan = "7" width = "16" height = "16" align = "right" valign = "bottom">
			<input type = "hidden" name = "joined" value = "<?php print(date("d.m.Y H:i:s", mktime())); ?>">
			<input type = "Image" src = "next.gif" width  = "16" height = "16" name = "submit" alt = "arrow pointing right: next" border = "0" align = "top" onfocus = "return checkFields();" tabindex = "10"></a>
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			<span class = "hilight">password:</span>
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "password" id = "pass" name = "pass" style = "width: 80%" class = "text" tabindex = "2">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			<span class = "hilight"> confirm password:</span>
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "password" id = "pass2" name = "pass2" style = "width: 80%" class = "text" tabindex = "3">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			email:
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "email" name = "email" style = "width: 80%" class = "text" tabindex = "4">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			http://
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "url" name = "url" style = "width: 80%" class = "text" tabindex = "5">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			date of birth:
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<span class = "bold">d: </span><input type = "text" id = "day" name = "day" size = "2" class = "text"  maxlength = "2" tabindex = "6"> <span class = "bold">m: </span><input type = "text" id = "month" name = "month" size = "2" class = "text"  maxlength = "2" tabindex = "7"> <span class = "bold">y: </span><input type = "text" id = "year" name = "year" size = "4" class = "text"  maxlength = "4" tabindex = "8">
		</td>
	</tr>
	<tr>
		<td width = "30%" height = "10" valign = "bottom">
			location:
		</td>
		<td width = "70%" height = "10" valign = "bottom">
			<input type = "text" id = "location" name = "location" style = "width: 80%" class = "text" tabindex = "9">
		</td>
	</tr>
	<tr>
		<td colspan = "3" valign = "top">
			&nbsp;
		</td>
	</tr>
      <tr>
        <th width="199" scope="row">Enter letters from image </th>
        <td width="181"><label>          
          <center>
            <img src="captcha.php" alt="Security Image" width="200" height="70" border="1">
            <input name="key" type="text" id="key" size="6" maxlength="6">
          </center>
        </label>        
</td>
</tr>
</table>
</form>

<script language = "javascript" type = "text/javascript">
<!--// Check field values are correct before submitting
	function checkFields(){
		var flag = 1;	// Return flag

		// Check for empty values in important fields first
		if(!document.getElementById("user").value || !document.getElementById("pass").value || !document.getElementById("pass2").value){
			alert("Please enter values in the following:\n\nUSERNAME\nPASSWORD\nCONFIRM PASSWORD");
			document.getElementById("user").focus();
			return true;
		}
		// Check that passwords are the same
		else if(document.getElementById("pass").value != document.getElementById("pass2").value){
			alert("Please enter two matching passwords");
			document.getElementById("pass").value = '';
			document.getElementById("pass2").value = '';
			document.getElementById("pass").focus();
			return true;
		}
		// Check the day / month / year fields if there's a value in one of them
		else if(document.getElementById("day").value || document.getElementById("month").value || document.getElementById("year").value){

			// Check day first
			if((isNaN(document.getElementById("day").value)) || (document.getElementById("day").value > 31) || (document.getElementById("day").value < 1)){
			alert("Please enter a valid day in the DOB field");
			document.getElementById("day").value = '';
			document.getElementById("day").focus();
			return true;
			}
			// Check month next
			else if((isNaN(document.getElementById("month").value)) || (document.getElementById("month").value > 12) || (document.getElementById("month").value < 1)){
				alert("Please enter a valid month in the DOB field");
				document.getElementById("month").value = '';
				document.getElementById("month").focus();
				return true;
			}
			// Finally the year
			else if((isNaN(document.getElementById("year").value)) || (document.getElementById("year").value >= <?php print date("Y", mktime()); ?>) || (document.getElementById("year").value < 1)){
				alert("Please enter a valid year in the DOB field");
				document.getElementById("year").value = '';
				document.getElementById("year").focus();
				return true;
			}
			else flag = 0;
		}
		else flag = 0;

		// One final check if the others went through fine
		if(!flag){
			if(document.getElementById("email").value){
				// Finally, check the email
				if(document.getElementById("email").value.indexOf("@") == -1 || document.getElementById("email").value.indexOf(".") == -1){
					alert("If entering an email addy, please make sure it is valid");
					document.getElementById("email").focus();
					return true;
				}
				else return false;
			}
			else return false;
		}
	}
-->
</script>
</body>
</html>
<?php
}
?>

Ok....Ora lasciamo perdere il risultato grafico che non so quale sia....visto che ho il sito su un altro pc e questo codice l'ho buttato giù alla veloce per postarvelo...Cmq...Ho inserito nel form il campo che mi serviva e l'immagine dal CAPTCHA.
Devo metter a posto i javascript per rilevare che è compilata anche l'id="key", ma poi non so come fare a dirgli che le due cose devono esser uguali....Io mi aspettavo una cosa tipo:

PHP:
	// Check that passwords are the same
		else if(document.getElementById("pass").value != document.$_SESSION["hash"].value){
			alert("Please enter two matching passwords");
			document.getElementById("key").value = '';
			document.$_SESSION["hash"].value = '';
			document.getElementById("key").focus();
			return true;
		}

Ma sfortunatamente il java non lo mastico e ieri ho provato 2000 combinazioni e non sono mi riuscito a venirne ad una....Mi date una mano?
In pratica tutte le prove che ho fatto, il codice se ne fregava di cosa mettevo nel CAPTCHA e la registrazione utente continuava.....
Forse devo definire le variabili e dirgli in php che l'img CAPTCHA corrisponde ad un id e poi confrontarlo con key....ma non so come si fa....
 

alessandro1997

Utente Attivo
6 Ott 2009
5.302
1
0
26
Roma
alessandro1997.netsons.org
C'è un piccolo problema: in Javascript non puoi leggere le sessioni memorizzate per l'utente, perché è un linguaggio lato client, mentre i file di sessione vengono memorizzati sul server dove risiede lo script PHP.
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Quindi non si può e bon fare come provavo io?
Devo allora inserire uno script php tipo quello che veniva usato nell'esempio di prima?

Ho visto altri codici che sull'input richiamavano un javscript "on click" .... Non si riesce neppure in quel modo?
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Ma devo mettere anche il php del CAPTCHA sulla stessa pagina o quello può anche stare su un'altro file?
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Scusatemi, ma io son sempre qua che picchio la testa su sta cosa.... Ma se io faccio:

$key2=$_SESSION["hash"];
$key=trim($_POST['key”];

Una volta che ho attribuito un id alla sessione, a quel punto non riesco a far funzionare il javascript usando il comando "getElementById" come per tutti gli altri campi?

Se no, usando php dovrei fare qualcosa tipo:

PHP:
<?php
session_start();

//Definisco la variabile
$captcha=$_POST['key'];

//Confronto i due testi
if (strcmp($captcha, $_SESSION['hash']) != 0) {
$_SESSION['errore']['key']=true;
$presenza_errori=true;
}
else {
$_SESSION['errore']['key']=false;
}

// visualizzo il messaggio di errore
if ($_SESSION['errore']['key']==true) {
echo ‘<li>Il TESTO inserito non è corretto.</li>’;
}

Mi rendo conto che probabilmente scrivo delle putt..... Però mi sembra che me ne manca solo qualche pezzettino qua e là.... Ma è sicuro sicuro che con javascript non si fa????

Più che altro per mantenere la stessa filosofia io vorrei visulaizzare quel messaggio il testo inserito non è corretto allo stesso modo di come visualizzo gli altri, ovvero con il pop-up che mi dice non hai completato tutti i campi, la mail è sbagliata ecc....
 

alessandro1997

Utente Attivo
6 Ott 2009
5.302
1
0
26
Roma
alessandro1997.netsons.org
Sinceramente ho qualche difficoltà a seguirti. Un sistema CAPTCHA funziona quasi sempre così: il software genera un codice casuale che poi viene scritto su un'immagine e memorizzato in una sessione. L'utente deve riprodurre il codice in un campo del form. Se il codice inserito coincide con quello presente nella sessione allora il codice è corretto. Essendo le sessioni memorizzate sul server non c'è modo di accedervi tramite Javascript, che viene eseguito dal client.

Però ora che ci penso potresti ovviare creando uno script PHP che controlla se il codice inserito corrisponde alla sessione e in quel caso visualizza 1, altrimenti 0. Poi lo richiami con AJAX passando come unico parametro il codice inserito dall'utente, e così puoi controllare se corrisponde, perché è PHP a leggere la sessione e non Javascript. Se decidi di adottare questo metodo di consiglio di usare jQuery, che rende il lavoro con richieste AJAX una stupidaggine.
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Dai un'occhiata a questo:

HTML:
<html>
<head>
<title>Ultra Light CAPTCHA</title>
<script language="javascript">
function fun()
{
vcod = document.f1.key.value;
erlog="";

if (vcod.length!=6)
	erlog=erlog + "<tr><td><span class='style2'>• Security Text Length must be 4.</span></td></tr>";

if (erlog == "")
	{
	 document.f1.action="http://localhost/captcha/check.php";
	 document.f1.method="post";
	 document.f1.submit();
	}
else
	document.getElementById("error").innerHTML = '<p align="center"><table width="514" bordercolor="#FF00CC">' + erlog + "</p></table>";
}
</script>
</head>

<style type="text/css">
<!--
body {
	background-color: #91D2FF;
}
.style1 {color: #333333}
-->
</style>

<body>
<h1 align="center">Anti-Spam Testing Form</h1>
<form name="f1">
  <div align="center">
    <table width="514" border="1" align="center" bordercolor="#00CCFF">
      <tr>
        <th width="199" scope="row">Enter letters from image </th>
        <td width="181"><label>          
          <center>
            <img src="captcha.php" alt="Security Image" width="200" height="70" border="1">
            <input name="key" type="text" id="key" size="6" maxlength="6" title="Are you a HUMAN ?">
          </center>
        </label>        </td>
        <td width="112" bordercolor="#91D2FF"><div align="center" class="style1">
            <center>
              Length 6 
            </center>
        </div></td>
      </tr>
      <tr>
        <th colspan="3" scope="row">
          <label>
          
          <input type="button" name="sub" value="Submit" onClick="fun()" title="Signup"/>
          </label>          <label>
          
          <input type="reset" name="Submit2" value="Reset" title="Clear"/>
          </label>        </th>
      </tr>
    </table> 
  </div>  
  <div align="center"></div>
</form>
<div id="error" align="justify"></div>
<h5 align="right" class="style1">Powered By Sourav Ghosh </h5>
</body>
</html>
Che si appoggia su questo:

PHP:
<?php
session_start();
    define("WIDTH", 200);
    define("HEIGHT", 70);

	define("F_SIZE", 20);
    define("F_ANGLE", 0);
$rnd = rand(1,4);
switch ($rnd) 
{
	case 1:
		define("F_FONT", "myfont.ttf");
		break;
	case 2:
		define("F_FONT", "myfont2.ttf");
		break;
	case 3:
		define("F_FONT", "myfont3.ttf");
		break;
	case 4:
		define("F_FONT", "myfont4.ttf");
		break;
}

	$img = imagecreate(WIDTH, HEIGHT);

    $white = imagecolorallocate($img, 255,255,255);
    $brdr = imagecolorallocate($img, 0,0,0);
	$black = imagecolorallocate($img, rand(0,150),rand(0,150),rand(0,150));

    $start_x = rand(10,15);
    $start_y = (int)HEIGHT/2;

    imagerectangle($img, 0,0,WIDTH-1,HEIGHT-1, $brdr);

	$text = chr(rand(65,90));
	$key = $text;
    imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+30, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+60, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+90, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+120, $start_y + (rand(-5,5)), $black, F_FONT, $text);
	$text = chr(rand(65,90));
	$key = $key.$text;
	imageTTFtext($img, F_SIZE, F_ANGLE + rand(-45,45), $start_x+150, $start_y + (rand(-5,5)), $black, F_FONT, $text);

$_SESSION["hash"]=$key;

$rnd = rand(1,9);
switch ($rnd) 
{
	case 1:
		$img_copy = imagecreatefrompng("captcha.png");
		break;
	case 2:
		$img_copy = imagecreatefrompng("captcha2.png");
		break;
	case 3:
		$img_copy = imagecreatefrompng("captcha3.png");
		break;
	case 4:
		$img_copy = imagecreatefrompng("captcha4.png");
		break;
	case 5:
		$img_copy = imagecreatefrompng("captcha5.png");
		break;
	case 6:
		$img_copy = imagecreatefrompng("captcha6.png");
		break;
	case 7:
		$img_copy = imagecreatefrompng("captcha7.png");
		break;
	case 8:
		$img_copy = imagecreatefrompng("captcha8.png");
		break;
	case 9:
		$img_copy = imagecreatefrompng("captcha9.png");
		break;
}
imagecopymerge($img, $img_copy, 0, 0, 0, 0, imagesx($img), imagesy($img), rand(10,30));
header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>

E quest'altro:
PHP:
<?php
session_start();
error_reporting (0);
$key2=$_SESSION["hash"];
$key=trim($_POST['key']);

if($pass2 == "")
	$err = $err + "Please insert a valid security code.<br>";

if (strcasecmp ($key,$key2) != 0)
	$err = $err + "Failed to pass CAPTCHA TEST.<br>Are you a machine ?";
else
	print "Cool, you are a smart human !";

if ($err != "")
{
	print "<font color='red'><b>Errors</b><br>";
	print $err;
}
?>
<style type="text/css">
<!--
body {
	background-color: #66CCFF;
}
-->
</style>
Il primo file contiene il form e lavora con un javascript...poi si appoggia al secondo che genera il captcha e sul terzo che fa il check....
Ha degli errori, perchè va bene se metti il codice giusto, ma si pianta se fai degli errori e non ti da la possibilità di tornare indietro...Però su ha un javascript e la funzione viene attivata con il comando on click =
Io vorrei fare una cosa così più o meno, ma invece di andare sulla pagina di check con landing page vorrei proseguire l'action del mio form originale dopo aver controllato il codice....
 

Tommy1981

Utente Attivo
1 Mag 2010
84
0
0
Ho risolto seguendo questa traccia....
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

<script>
function CAPTCHA()
{
var car, min, max, dif, lun, inc;
car  = "abcdefghijklmnopqrstuvwxyz";
car += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
car += "1234567890";
min  = 5;
max  = 5;
dif  = max - min;
lun  = Math.round((Math.random() * dif) + min);
inc  = 0;
cod  = "";
while (inc < lun)
{
  cod += car.charAt(Math.round(Math.random() * car.length));
  inc++;
}
return cod;
}


function Prova(){
document.getElementById("captcha").innerHTML = CAPTCHA();
}

function Invia()
{
var testo = document.modulo.testo.value;
var codice = document.modulo.codice.value;
if (testo == "")
{
  alert("Inserisci del testo nell'apposita casella!");
  document.modulo.testo.value = "";
  document.modulo.testo.focus();
}
else if (codice != document.getElementById("captcha").innerHTML)
{
  alert("Il codice di sicurezza è errato!");
  document.modulo.codice.value = "";
  document.modulo.codice.focus();
}
else
{
  document.modulo.method = "post";
  document.modulo.action = "script.asp";
  document.modulo.submit();
}
}
</script>

</head>



<body onLoad="Prova()">


<form name="modulo">
Copia il codice di sicurezza:
<span id="captcha"></span><br><br>
<input type="text" name="codice" size="50"><br><br>
<input type="button" value="Invia i dati" onclick="Invia()">
</form>

</body>
</html>

Per come serviva a me sono contento, sono riuscito a buttare tutto dentro nella pagina dove c'è il form di registrazione.
 
Discussioni simili
Autore Titolo Forum Risposte Data
E [RISOLTO]Sicurezza attacchi con $_session: come viene gestita nella trasmissione server client ? PHP 5
Leoluca SICUREZZA, GRUPPO DI LAVORO E PROFILI MS Access 2
R Mettere in sicurezza una comunicazione .NET Framework 0
NioMio Aruba Sicurezza certificati e ranking di sicurezza 2019/2020 Hosting 1
E [CERCO] Pubblicità per Ebook tema Sicurezza Informatica Vendere e Acquistare pubblicita' online 1
F [php] sicurezza password form login PHP 2
G [PHP] Quali sono tutte le misure di sicurezza che un sito deve avere? PHP 1
W [PHP] Un dettaglio di logica e approccio sulla sicurezza di un progetto. PHP 9
K xamp impostazioni di sicurezza Web Server 5
W [C#] Sicurezza Client/Server - SOAP o RESTFull API .NET Framework 0
W Windows vs Linux per la sicurezza su ATM Windows e Software 0
A Retribuito: Sviluppatore Asp classico esperto in sicurezza webserver IIS e SQL Offerte e Richieste di Lavoro e/o Collaborazione 0
matteoraggi Sicurezza di un server apache con uso limitato Apache 0
K [php] due domande sulla sicurezza PHP 1
S [PHP] $_SESSION e sicurezza... PHP 2
giorgiolovecchio [WordPress] Risorsa http invalida sicurezza sito WordPress 2
KILLERIX Sicurezza dei database nei siti web Database 2
V [PHP] upload di file in cartella e sua sicurezza PHP 137
romeocharly nuove norme di sicurezza paypal Guadagnare col Sito 3
M Formazione per diventare uno specialista di Sicurezza Informatica Sicurezza e Virus 3
A Sicurezza sito PHP 0
P Errore Codice Sicurezza Guestbook Supporto Mr.Webmaster 0
L Paypal - aggiornamenti alla sicurezza PHP 5
L Sicurezza login e limitazione accessi PHP 3
A Non riesco più a visualizzare il codice sicurezza nel forum Supporto Mr.Webmaster 3
A sicurezza wp login failed WordPress 5
R Security Ninja Core Scanner Plugin Sicurezza WordPress 5
I Problemi di sicurezza php PHP 1
voldemort Sicurezza login $_SESSION attacchi XSS CSRF PHP 0
C Sicurezza Textarea PHP 1
F sicurezza script login PHP 3
Akuma consiglio sicurezza per soluzione problema apici PHP 0
filippino phpBB: spam nonostante captcha e domanda di sicurezza phpBB 0
A consiglio sulla sicurezza PHP 5
A ricavare il path alle cartelle e sicurezza PHP 5
M Codice di sicurezza su modulo Classic ASP 25
G MyBB: Sicurezza della pagina e del suo contenuto CMS (Content Management System) 2
L problema gestione utenti e sicurezza persone PHP 3
M creare da soli in sicurezza un sito Offerte e Richieste di Lavoro e/o Collaborazione 4
asevenx problema con codice di sicurezza captcha PHP 2
M Sicurezza dati form per insert e select in database PHP 11
M Sicurezza delle sessioni PHP 25
F Richiesta pillola su sicurezza jQuery 5
B Sicurezza php/mysql form PHP 2
L Database esterno e sicurezza Database 2
J Come usare certificato SSL per la sicurezza PHP 2
G Vendere e comprare in sicurezza in internet Presenta il tuo Sito 0
T Sicurezza sito Web PHP 11
B Aumentare livello di sicurezza accesso client area riservata Classic ASP 5
I [CERCO] Articolista per browser game o sicurezza informatica Offerte e Richieste di Lavoro e/o Collaborazione 1

Discussioni simili