Results for securite : 18

6 - astuce sécurité PHP - Le Hollandais Volant
# en début de script
if (basename($_SERVER['SCRIPT_NAME']) === 'index.php' and strpos(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 'index.php') === FALSE ) {
	$var_request_URI = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH).'index.php';
} else {
	$var_request_URI = $_SERVER['REQUEST_URI'];
}
if (parse_url($var_request_URI, PHP_URL_PATH) !== $_SERVER['SCRIPT_NAME']) {
	header('Location: '.$_SERVER['SCRIPT_NAME']);
}


			
7 - ssave-sload: secured data saving
# Secured save/load variable data (inspired by Oros)
function ssave($file=null,$content=''){
	if (!$file){return false;}
	file_put_contents($file.'.php', '<?php /* '.base64_encode(gzdeflate(serialize($content))).' */ ?>');
}
function sload($file=null){
	if (!$file || !is_file($file)){return false;}
	return unserialize(gzinflate(base64_decode(substr(file_get_contents($file),9,-strlen(6)))));
}
			
8 - FORMULAIRE DE MODIFICATION DES DROITS CHMOD DES FICHIERS ET DOSSIERS
<?php
/*
FORMULAIRE DE MODIFICATION DES DROITS CHMOD DES FICHIERS ET DOSSIERS
Enregistrez ce fichier dans votre répertoire hébergement web, ouvrez-le 
avec votre navigateur et suivez les instructions.
Un rapport d'erreur est fourni.
*/

// initialisation des variables
$dosPerm = "0";
$ficPerm = "0";
$retval = "0"; // nombre d'erreurs CHMOD

 // Chemin du dossier a traiter
    $chem = preg_replace("/[^_A-Za-z0-9-\.%\/]/i",'', $_POST["chemin"]);    // chemin de fichier absolu (avec nettoyage contre piratage)
    $chem = preg_replace("/\.\.\//",'', $chem);    // on interdit la commande ../
    define('ABSPATH', dirname(__FILE__));
    $chem = ABSPATH.$chem;    // chemin de fichier absolu de votre compte du genre /home/loginftp/www/ ou /home/loginftp/public_html/ etc.

//Droits des dossiers
    $d1 = preg_replace("/[^057]/",'', $_POST["dir1"]);
    $d2 = preg_replace("/[^057]/",'', $_POST["dir2"]);
    $d3 = preg_replace("/[^057]/",'', $_POST["dir3"]);
    $dosPerm = "0".$d1.$d2.$d3;
    $dosPerm = octdec($dosPerm);
//droits des fichiers
    $f1 = preg_replace("/[^046]/i",'', $_POST["fic1"]);
    $f2 = preg_replace("/[^046]/i",'', $_POST["fic2"]);
    $f3 = preg_replace("/[^046]/i",'', $_POST["fic3"]);
    $ficPerm = "0".$f1.$f2.$f3;
    $ficPerm = octdec($ficPerm);

// Formulaire html pour changer les droits
    print "<html><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />";
    print "<body><h3>Changer les droits d'acc&egrave;s CHMOD aux dossiers et fichiers <br />dans votre h&eacute;bergement.</h3>";
    print "<table><tr><td>";
    print "<form method=\"post\">";
    print "<tr><td>Droits des dossiers: </td>";
    print "<td><select name=\"dir1\"><option value=\"0\">0</option><option value=\"5\">5</option><option value=\"7\" selected>7</option></select><select name=\"dir2\"><option value=\"0\">0</option><option value=\"5\" selected>5</option><option value=\"7\">7</option></select><select name=\"dir3\"><option value=\"0\">0</option><option value=\"5\" selected>5</option><option value=\"7\">7</option></select></td></tr>";
    print "<tr><td>Droits des fichiers: </td>";
    print "<td><select name=\"fic1\"><option value=\"0\">0</option><option value=\"4\">4</option><option value=\"6\" selected>6</option></select><select name=\"fic2\"><option value=\"0\">0</option><option value=\"4\" selected>4</option><option value=\"6\">6</option></select><select name=\"fic3\"><option value=\"0\">0</option><option value=\"4\" selected>4</option><option value=\"6\">6</option></select></td></tr>";
    print "<tr><td>R&eacute;pertoire &agrave; contr&ocirc;ler: </td>";
    print "<td>".ABSPATH." <input type=\"text\" name=\"chemin\" maxlength=\"80\" size=\"30\" value=\"/\" ></td></tr>";
    print "<tr><td> </td><td><input type=\"submit\" value=\" Changer les CHMOD des Dossiers et Fichiers \">";
    print "</form>";
    print "</td></tr></table>";

if ( ($dosPerm||$ficPerm) > 0 ){

    function rChmod($chem,$dosPerm,$ficPerm) {
        echo "<p><b>Journal:</b></p>\r\n";

        $d = new RecursiveDirectoryIterator($chem); 
        $d ->setFlags(RecursiveDirectoryIterator::SKIP_DOTS); 
        foreach (new RecursiveIteratorIterator($d, 1) as $path) {
            $chmodret = false;
            $chmodresultat = "";
            if ( $path->isDir() ) {
            $chmodret = chmod( $path, $dosPerm ); }
            else {
            if ( is_file( $path )  ) {
            $chmodret = chmod( $path, $ficPerm ); }
            }
            if ($chmodret) {$chmodresultat = "OK"; }
            else {
                $chmodresultat = "ERREUR";
                ++$retval;
                }
            echo $chmodresultat . " " . $path . "<br />\r\n";
        }
    return $retval;
}
    $nbfailed = rChmod($chem,$dosPerm,$ficPerm);
    echo "<p><b>";
    if ($nbfailed > 0) {
        echo $nbfailed . " erreur(s) CHMOD. Voyez le journal ci-dessus.";
        }
    else echo "Pas d'erreur apparente. Vérifiez par vous-même.</b></p>\r\n";
}
?>
			
10 - strip_almost_all_tags
function strip_almost_all_tags($chaine){
	// ajouter le strip attributes
	// à la barbare
	$secure='#on(click|dblclick|blur|change|dragdrop|focus|keydown|keyup|keypress|mouseover|mouseout|load|unload|keydown)=#i';
	$keep=array('<img ','<a ', '<em', '<br>','<br/>','</a', '</em', '<br />','<p ', '</p','<div ', '</div','<span ', '</span', '<li', '</li', '<ul', '</ul');
	$temp_repl=array('[img ','[a ','[em','[br]','[br/]','[/a','[/em','[br /]','[p ','[/p','[div ','[/div','[span ','[/span','[li','[/li','[ul','[/ul');
	$chaine=str_ireplace($keep,$temp_repl,$chaine);
	$chaine=strip_tags($chaine);
	$chaine=preg_replace($secure, 'on$1&#61;', $chaine);
	return str_ireplace($temp_repl,$keep,$chaine);
}
			
11 - Strip_cars
function strip_tags(input, allowed) {
				//http://phpjs.org/functions/strip_tags/
				allowed = (((allowed || '') + '')
				.toLowerCase()
				.match(/<[a-z][a-z0-9]*>/g) || [])
				.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
				var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
				commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
				return input.replace(commentsAndPhpTags, '')
				.replace(tags, function($0, $1) {
				  return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
				});
			}
			
12 - clean - nettoyer une variable
function clean($value) {

       // If magic quotes not turned on add slashes.
       if(!get_magic_quotes_gpc())

       // Adds the slashes.
       { $value = addslashes($value); }

       // Strip any tags from the value.
       $value = strip_tags($value);

       // Return the value out of the function.
       return $value;

}
			
13 - secure - sécuriser une chaine ou un tableau contre le XSS
function secure($var,$level=0){
    // $level=0 > returns text only (no html or script), 1 > text + html (no script), 2 > all content secured with entities
    if (is_array($var)){foreach ($var as $index=>$v){$var[$index]=secure($v,$level);}}
    else if (is_string($var)){
        if ($level==0){$var=strip_tags($var);}
        else if ($level==1){$var=preg_replace('#on[a-z]+ ?= ?["\'].*?["\'](?=[ />])|</?script>|javascript:#i','',$var);}
        else {$var=htmlspecialchars($var);}
    }
    return $var;
}
			
15 - auto_error_handler
<?php
# Error handler by bronco@warriordudimanche.net #################
function showline($line,$file){
	$f=file($file);$r='';
	for ($l=$line-2;$l<$line+2;$l++){
		if (isset($f[$l])){
			if ($l==$line-1){
				$r.='<em style="color:white;text-shadow:0 0 2px black"><strong>'.$l.' >> </strong> '.$f[$l].'</em>';
			}else{
				$r.='<strong>'.$l.' >> </strong> '.$f[$l];
			}
		}
	}
	return $r;
}
function error_handler($number, $message, $file, $line, $vars){
	echo "
		<div style='word-wrap: break-word;Box-sizing: Border-box ;border-radius:5px;padding:15px;margin-bottom:20px;box-shadow:0 2px 1px maroon;font-family:courier;position:absolute;top:0;left:0;background-color:rgba(255,100,100,0.2);width:100%;height:auto;position:relative;min-width:320px;'>
			<h1 style='color:red;border-radius:5px;background-color:pink;padding:5px;box-shadow:0 2px 1px maroon'>Erreur $number</h1>
			<p style=''> <em>$message </em> a la ligne <strong style='font-size:24px'>$line</strong> dans le fichier <strong style='font-size:24px'>file: $file.</strong></p>
			
			<pre style='font-weight:bold;padding:20px;margin-left:10px;color:orange;text-shadow:0 1px 1px maroon;box-shadow:inset 0 2px 1px maroon;border-radius:5px;background-color:red;'><code>".showline($line,$file)."</pre></code>
			<h1 style='color:red;border-radius:5px;background-color:pink;padding:5px;box-shadow:0 2px 1px maroon'>Variables</h1>
			<pre style='overflow:scroll;height:200px;'>";
			var_dump($vars) ;
			echo "</pre>
			<a style='display:block;text-align:right;font-size:14px;color:maroon;text-decoration:none;font-weight:bold;font-styl:italic;' href='http://warriordudimanche.net/'>Error handler par warriordudimanche.net</a>
		</div>";

	if ( ($number !== E_NOTICE) && ($number < 2048) ) {die("Erreur fatale.");}
}

set_error_handler('error_handler');
#################################################################
?>
			
17 - Sécuriser des chaines
function cleanInput($input) {
 
 $search = array(
  '@<script[^>]*?>.*?</script>@si',  // Strip out javascript
  '@<[/!]*?[^<>]*?>@si',      // Strip out HTML tags
  '@<style[^>]*?>.*?</style>@siU',  // Strip style tags properly
  '@<![sS]*?--[ tnr]*>@'     // Strip multi-line comments
 );
 
  $output = preg_replace($search, '', $input);
  return $output;
 }

function sanitize($input) {
  if (is_array($input)) {
    foreach($input as $var=>$val) {
      $output[$var] = sanitize($val);
    }
  }
  else {
    if (get_magic_quotes_gpc()) {
      $input = stripslashes($input);
    }
    $input = cleanInput($input);
    $output = mysql_real_escape_string($input);
  }
  return $output;
}

// Usage:
$bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
 $good_string = sanitize($bad_string);
 // $good_string returns "Hi! It's a good day!"

 // Also use for getting POST/GET variables
 $_POST = sanitize($_POST);
 $_GET = sanitize($_GET);
			
18 - Sécuriser GET et POST
$_ = array();
foreach($_POST as $key=>$val){
$_[$key]=mysql_escape_string(htmlentities($val));
}
foreach($_GET as $key=>$val){
$_[$key]=mysql_escape_string(htmlentities($val));
}

utilisation:
echo $_['MaVariablePostOuGet'];