ユーザー認証

<?php
    $admin_password = "m9k7PZRgG8SAySmG";
    $dataFile = dirname(__FILE__).'/data/userauth.data';
    $iv_a = &#91;177,108,37,2,26,148,178,3,72,100,27,156,62,231,205,83&#93;;
    $enc_iv = implode('', array_map('chr', $iv_a));

    $info = "";
    $m = empty($_POST&#91;'m'&#93;) ? '' : $_POST&#91;'m'&#93;;
    if($m == 'add') $info = m_add();
    if($m == 'get') $info = m_get();

    function m_add() {
        $userId = empty($_POST&#91;'userId'&#93;) ? '' $_POST&#91;'userId'&#93;;
        $password = empty($_POST&#91;'password'&#93;) ? '' : $_POST&#91;'password'&#93;;
        $secret = empty($_POST&#91;'secret'&#93;) ? '' : $_POST&#91;'secret'&#93;;
        if ($userId == "" || $password == "" || $secret == ""){
            return "ユーザー情報を正しく入力してください";
        }
        putUserData(&#91;
        'userId'=>$userId, 'password'=>$password,
                    'secret'=>$secret]);
        return "保存しました";
    }

   //ユーザーデータを追加 ---(*3)
    function putUserData($user){
        global $dataFile, $enc_iv, $admin_password;
        
        $salt = base64_encode(openssl_random_pseudo_bytes(16));
        $password = $user['password'];
        $user['password'] = hash('sha256', $password.$salt);
        $user['salt'] = $salt;
        $secret = openssl_encrypt(
        $user['secret'], 'aes-256-cbc',
                                  $password.$salt, 0, $enc_iv);
        $user['secret']= $secret;
        $data = getUserData();
        $data[$user['userId']] = $user;
        $json = json_encode($data);
        print_r($data, $json);
        $enc = openssl_encrypt($json, 'aes-256-cbc', $admin_password, 0, $enc_iv);
        file_put_contents($dataFile, $enc);
    }

// user transaction
    function m_get(){
        global $enc_iv;
        $userId = empty($_POST['userId']) ? '' : $_POST['userId'];
        $password = empty($_POST['password']) ? '' : $_POST['password'];
        if ($userId == "")return "input is empty";
        $data = getUserData();
        if (!isset($data[$userId])) return "情報に誤りがあります";
        $u = $data[$userId];
        $salt = $u['salt'];
        $pw_hash = hash('sha256', $password.$salt);
        if ($u['password'] != $pw_hash) return "情報にあやまりがあります";
        $secret_raw = $u['secret'];
        $secret = openssl_decrypt($secret_raw, "aes-256-cbc",
                                  $password.$salt, 0, $enc_iv);
        $secret_ = htmlentities($secret);
        return "<div class='read'><h3>ユーザー認証成功</h3>".
        "<ul><li>userId: $userId</li>".
        "<li>secret: $secret_</li></ul></div>";
    }

// get user data
    function getUserData(){
        global $dataFile, $enc_iv, $admin_password;
        $data = [];
        if (file_exists($dataFile)){
            $raw = file_get_contents($dataFile);
            $json = openssl_decrypt($raw, "aes-256-cbc",
                                    $admin_password, 0, $enc_iv);
            $data = json_decode($json, true);
        }
        return $data;
    }
?>
<html><meta charset="utf-8">
<body><style>
.read { background-color: #e0e0fc; padding: 10px; }
    form { margin-left: 10px; }
</style>
    <?php echo $info; ?>
    <h2>ユーザーの参照</h2>
    <form method="post">
    <input type="hidden" name="m" value="get">
    userId:<br><input name="userId"><br>
    password:<br><input type="password" name="password"><br>
    <input type="submit" value="参照">
</form>

<hr><h2>ユーザーの追加</h2>
<form method="post">
    <input type="hidden" name="m" value="add">
    userId:<br><input name="userId"><br>
    password:<br><input type="password" name="password"><br>
    secret(秘密のメモ):<br><input name="secret"><br>
    <input type="submit" value="add">
    </form>
</body></html>

シーザー暗号

<meta charset="UTF-8">
<?php
// get parameter
    $str = isset($_GET&#91;"str"&#93;) : "";
    $shift = isset($_GET&#91;"shift"&#93;) ? intval($_GET&#91;"shift"&#93;) : 3;
    if ($str != "")convert($str, $shift);
    $str_ = htmlentities($str, ENT_QUOTES);
// display form
echo <<< EOS
<form>
    character line: <input name="str" value="$str_"><br>
    shift: <input name="shift" value="$shift"><br>
    <input type=="submit" value="change">
</form>
    EOS;
    function makeTable($shift){
    $ch1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $shift = $shift % strlen($ch1);
        $ch2 = substr($ch1, $shift).substr($ch1, 0, $shift);
        $table = [];
        for ($i = 0; $i < strlen($ch1); $i++){
            $c1 = substr($ch1, $i, 1);
            $c2 = substr($ch2, $i, 1);
            $table&#91;$c2&#93; = $c1;
        }
        return $table;
    }
    function convert($str, $shift){
        if (empty($_GET&#91;"str"&#93;)) return;
        $table = makeTable($shift);
        $res = "";
        for ($i = 0; $i < strlen($str); $i++){
            $c = substr($str, $i, 1);
            $res .= isset($table&#91;$c&#93;) ? $table&#91;$c&#93; : $c;
        }
        $str = htmlentities($str, ENT_QUOTES);
        $res = htmlentities($res, ENT_QUOTES);
        echo "<div>before transfer: $str</div>";
        echo "<div>after transfer: $res</div><hr>";
    }

迷路の自動生成

0,";
$pat[1] = "1,";
$html = "";
for ($y = 0; $y < count($maze); $y++){ for ($x = 0; $x < count($maze); $x++){ $html .= $pat[$maze[$y][$x]]; } $html .= "\n"; } return $html; }[/php]

YAML

<?php
// read YAML library
    require 'vendor/autoload.php';
    use Symfony\Component\Yaml;

// declare data
$data = &#91;
    'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
    'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
    'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
    'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
    ];
    $file = "serialize-test.yaml";

    $dumper = new Yalm\Dumper();
    $yaml = $dumper->dump($data);
    file_put_contents($file, $yaml);

    $yaml2 = file_get_contents($file);
    $yaml_p = new Yaml\Parser();
    $data2 = $yaml_p->parse($yam12);
    foreach ($data2 as $name => $v) {
        $age = $v["age"];
        $hobby = $v["hobby"][0];
        if (isset($v["hobby"][1])){
            $hobby .= " ".$v["hobby"][1];
        }
        echo "[$name] $age $hobby\n";
    }

simpleXMLElement

<?php
// declare data
$data = &#91;
    'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
    'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
    'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
    'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
    ];
    // saving file pass
    $file = "serialize-test.xml";

    // transfer function from php array to XML
    function array2xml($arr, $xml_obj = NULL) {
        if ($xml_obj == NULL){
            $def = '<?xml version="1.0"?><root></root>';
        $xml_obj = new SimpleXMLElement($def);
        }
        foreach($arr as $key => $value){
        if (is_numeric($key)) $key = "item";
            if (is_array($value)){
                $subnode = $xml_obj->addChile($key);
                array2xml($value, $subnode);
            } else {
                $v = htmlentities($value);
                $xml_obj->addChild($key, $v);
            }
        }
    return $xml_obj;
    }

// transfer array to object
$xml_obj = array2xml($data);
$str = $xml_obj->asXML();
// save to file
file_put_contents($file, $str);

// read from file
$xml2 = simplexml_load_file($file);
foreach ($xml2->children() as $it){
    $name = $it->getName();
    $age = $it->age;
    echo "$name:$age:";
    $hobby = $it->hobby;
    foreach ($hobby->children() as $h){
        echo "($h)";
    }
    echo "\n";
}

json_encode()

jsonを使って書き直し

<?php
//declare data
$data = &#91;
    'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
    'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
    'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
    'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
    ];

// file pass to preserve
    $file = "serialize-test.json";

//serialize
    $str = json_encode($data, JSON_PRENTY_PRINT);

//preserve
    file_put_contents($file, $str);

//recover data from a file
    $str2 = file_get_contents($file);
    $data2 = json_decode($str2, true);
// display Arisa hobby
    print_r($data2['Arisa']['hobby']);

serialize()

phpの配列はメモリ上に配置されており、これをストレージに保存したり、ブラウザなどクライアント先に一定の書式で出力するためには、何らかのシリアライズ(serialize)という処理をする必要が有ります。

<?php
// declare data
$data = &#91;
    'Taro'=>['age'=>30, 'hobby'=>['Guitar','Piano']],
    'Takeshi'=>['age'=>18, 'hobby'=>['Reading']],
    'Arisa'=>['age'=>16, 'hobby'=>['Walking','Tea']],
    'Sara'=>['age'=>22, 'hobby'=>['Sleeping']]
    ];

    $file = "serialize-test.txt";

      $str = serialize($data);
    file_put_contents($file, $str);

    $str = serialize($data);
    file_put_contents($file, $str);

    $str2 = file_get_contents($file);
    $data2 = unserialize($str2);
// display Arisa hobby
    print_r($data2['Arisa']['hobby']);

ビンゴマシン

<html><body><?php
// bingo machine
    session_start();

// get from turn
    $turn = empty($_GET&#91;"turn"&#93;) ? 0 : interval($_GET&#91;"turn"&#93;);

    if($turn == 0|| empty($_SESSION&#91;"numbers"&#93;)){
        $numbers = array();
        for ($i = 1; $i <= 75; $i++){
            $numbers&#91;$i&#93; = $i;
        }
        shuffle($numbers);
        // save session
        $_SESSION&#91;"numbers"&#93; = $numbers;
    }

    $numbers = $_SESSION&#91;"numbers"&#93;;
    $num = $numbers&#91;$turn&#93;;
    $now_turn = $turn + 1;
    $next = ($turn + 1) % 75;

    echo "<p>{$now_turn}ターン目</p>";
    echo"<h1>$num</h1>";
    echo "<p><a href='bingo.php?turn=$next'>next number</a></p>";
?></body></html>