Skip to content

Instantly share code, notes, and snippets.

@papettoTV
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save papettoTV/9659681 to your computer and use it in GitHub Desktop.
Save papettoTV/9659681 to your computer and use it in GitHub Desktop.
Set Basic Auth makeing .htaccess and .htpasswd
<?php
/*
* ベーシック認証設置ツール
* 1)ベーシック認証掛けたいフォルダにこのファイルを設置してアクセス!
* 2)ユーザ・パスワードを設定後、認証確認出来たら完了です。
*
* バリデーション、ファイルパーミションなど、対応甘いので、改善したい!
*/
?>
<?php
$dir = dirname(__FILE__);
$filename= basename(__FILE__);
if(count($_POST)>0){
$user = $_POST["user"];
$passwd = $_POST["passwd"];
$s = crypt($passwd);
$fp = fopen($dir.'/.htaccess','w');
$basics = array();
$basics[] = '<Files ~ "^\.(htaccess|htpasswd)$">';
$basics[] = 'deny from all';
$basics[] = '</Files>';
$basics[] = 'AuthUserFile '.$dir.'/.htpasswd';
$basics[] = 'AuthGroupFile /dev/null';
$basics[] = 'AuthName "Please enter your ID and password"';
$basics[] = 'AuthType Basic';
$basics[] = 'require valid-user';
$basics[] = 'order deny,allow';
$v=implode("\n",$basics);
fwrite($fp,$v);
fclose($fp);
$fp=fopen($dir.'/.htpasswd','w');
$p=$user.':'.$s;
fwrite($fp,$p);
fclose($fp);
header("Location: ./".$filename);
}
if(file_exists($dir."/.htpasswd")){
$isMaked=true;
}else{
$isMaked=false;
}
?>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ベーシック認証</title>
<body>
<?php
if($isMaked){
?>
<h1>ベーシック認証設置&認証できました。</h1>
<p>お疲れさまです。これで完了です。</p>
<p>もしこのツールを気に入ったり、改善したいと思ったら、<a href="https://gist.github.com/papettoTV/9659681" target="_blank">ここ</a>を見てみてください。</p>
<p>それと、このファイル(<?php echo $filename; ?>)は不要なので、消しておきましょう。</p>
<?php
}else{
?>
<h1>ベーシック認証設置</h1>
<p>設定したいユーザ名とパスワードを入力してください。</p>
<form action="./<?php echo $filename; ?>" method="post">
ユーザ名:<input type="input" name="user" /><br />
パスワード:<input type="input" name="passwd" /><br />
<input type="submit" value="作成して認証する" />
</form>
<?php
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment