さくらレンタルサーバーライトでもLaravel。

2023.05.03

Logging

おはようございます。さくらレンタルサーバーライトで初期のドメインでもLaravelは導入可能。ただし、Laravelの構築はローカル側でDockerなりなんなりを使用して構築しないと限りなく面倒なので、おすすめしません。

Laravelのローカル導入は割愛して、さくらレンタルサーバーライトの初期ドメインで構築するには、どのようにすれば良いかを記載します。まず、ローカル側でLaravelを構築し、そのファイルをサーバー側のwww配下にアップロードします。その後、wwwに.htaccessファイルを新規作成し下記のような記述を書いてください。こうすることで、さくらレンタルサーバーライトでもLaravelを使用できます。尚、Mysqlはさくらレンタルサーバーライトでは使用できないので、sqliteを使用する事になります。

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/reborn9-app/public/
RewriteRule ^(.*) /reborn9-app/public/$1

軽量のWebサービスならさくらレンタルサーバーのライトでも十分動作します。是非、トライしてみてください。

追伸:ライトなのでcronは使用できません。格安サーバーでcronまで使用したいというのならばロリポップが良いかと思います。5分間ですがcronも使用できます、ロリポップ最強かも🤔。

タグ

$1, cron, docker, htaccessファイル, Laravel, MYSQL, public, reborn9-app, REQUEST_URI, RewriteEngine On RewriteCond %, RewriteRule, Sqlite, www配下, さくらレンタルサーバー, さくらレンタルサーバーライト, ロリポップ, ロリポップ最強, 記述, 軽量, 追伸,

数珠繋ぎのツイートシステムに予約機能を付けました😂 #php #code

2022.10.07

Logging

おはようございます、偏頭痛持ちは雨が降るが一番大変です☔。

先日、数珠繋ぎのツイートシステムを作ったのですが、そのシステムに予約機能を付けました。尚、TwitterAPIのバージョン2でスケジュールのパラメーターが今のところ無いですね。これから先、機能が付くかも知れないですが今のところ無いようです。因みにソースコードは近日中にQiitaGithubにUPします。此処ではソースコードの一部を掲載します(※記事を更新しました下へスクロール🫠)。

Twitter API v2 ツイート数珠繋ぎ

尚、crontabでPHPファイルを叩くようにしています、あと注意事項ですが予約を一度した投稿については変更等は出来ません、編集機能等の機能追加の予定はないです。また、予約管理はsqlite3を使用して管理しています。

<?php
date_default_timezone_set('Asia/Tokyo');
ini_set("display_errors",0);
require_once "./data/tw-config-v2.php";
require_once "../vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class tw
{
    var $connection = null;
    var $pdo = null;
    function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
    }
    function db_connection()
    {
        try {
            //code...
            $res = $this->pdo = new PDO("sqlite:./data/tw-tweets-db.sqlite3");
        } catch (\Throwable $th) {
            //throw $th;
            //print $th->getMessage();
            $res = false;
        }
        return $res;
    }

    function timecheck($timeonoff, $times)
    {
        if (!$timeonoff) return true;
        $n = new DateTime();
        $t = new DateTime($times);
        return $t <= $n ? true : false;
    }

    function pickup_tweets(mixed $tw_text = null, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        if (!$times) return false;
        $obj = (object)[];
        $times = preg_replace("/\-/", "/", $times);
        $times = preg_replace("/T/", " ", $times);

        if ($this->timecheck($timeonoff, $times)) {
            if (isset($tw_text) && is_array($tw_text)) {
                foreach ($tw_text as $key => $value) {
                    if (preg_replace("/[ | ]/", "", $value)) {
                        $obj = !$key ? ($this->connection->post("tweets", ["text" => $value], true)
                        ) : ($this->connection->post("tweets", ["reply" => ["in_reply_to_tweet_id" => $obj->data->id], "text" => $value], true)
                        );
                    }
                }
                return true;
            }
        } else {
            return $timeonoff ? $this->save_sqlite($tw_text, $timeonoff, $times, $id): true;
        }
    }

    function save_sqlite($tw_text = null, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        if ($this->db_connection()) {
            try {
                //code...
                if (isset($tw_text) && is_array($tw_text)) {
                    foreach ($tw_text as $key => &$value) {
                        if (preg_replace("/[ | ]/", "", $value)) {
                            $stmt = $this->pdo->prepare("insert into tweets (tw_id,user,times,tw_text)values(:tw_id,:user,:times,:tw_text)");
                            $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                            $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                            $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                            $stmt->bindValue(":tw_text", $value, PDO::PARAM_STR);
                            $stmt->execute();
                        }
                    }
                }
                $this->pdo = null;
                return true;
            } catch (\Throwable $th) {
                //throw $th;
                return false;
            }
        }
    }
    function tweets_load(string $id = "")
    {
        if (!$id) return false;
        try {
            //code...
            $value = null;
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("select * from tweets where user = :user order by times,tw_id asc;");
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $res = $stmt->execute();
                $value = $res ? $stmt->fetchAll() : false;
                $this->pdo = null;
            }
            return $value;            
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
    }
    function tweets_update(int $key = 0, int $timeonoff = 0, mixed $times = null, string $id = "",mixed $tw_text="")
    {
        try {
            //code...
            if(!preg_replace("/[ | ]{0,}/","",$tw_text))return false;
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("update tweets set tw_text = :tw_text where tw_id = :tw_id and user = :user and times = :times");
                $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                $stmt->bindValue(":tw_text", $tw_text, PDO::PARAM_STR);
                $stmt->execute();
                $this->pdo = null;
            }
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
        return true;

    }

    function tweets_delete(int $key = 0, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        try {
            //code...
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("delete from tweets where tw_id = :tw_id and user = :user and times = :times");
                $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                $stmt->execute();
                $this->pdo = null;
            }
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
        return true;
    }

    function bat_tweets(mixed $value = null)
    {
        if (!$value) return false;
        $obj = (object)[];
        $t = "";
        foreach ($value as $key => $val) {
            if ($this->timecheck(1, $val["times"])) {
                $obj = ($val["times"]<>$t)? ($this->connection->post("tweets", ["text" => $val["tw_text"]], true)
                ) : ($this->connection->post("tweets", ["reply" => ["in_reply_to_tweet_id" => $obj->data->id], "text" => $val["tw_text"]], true)
                );
                $this->tweets_delete($val["tw_id"], 1, $val["times"], $val["user"]);
                $t = $val["times"];
            } else {
              //  var_dump($val);
              //  break;
            }
        }
    }
}

if ($argv[0]) {
    $tw = new tw();
    $value = $tw->tweets_load(xss_d($argv[1]));
    $tw->bat_tweets($value);
}
function xss_d($val = false)
{
    if (is_array($val)) {
        foreach ($val as $key => $value) {
            $val[$key]  = strip_tags($value);
            $val[$key]  = htmlspecialchars($val[$key]);
        }
    } else {
        $val  = strip_tags($val);
        $val  = htmlspecialchars($val);
    }
    return $val;
}

追記:予約編集機能なども付けました🙄。

GithubとQittaのリンクはこちらです。
Github:https://github.com/taoka-toshiaki/tweets-system-box1
Qitta:https://qiita.com/taoka-toshiaki/items/5ef12b60b267742bf584

タグ

2, , 39, Asia, Code, crontab, date, default, github, ini, lt, php, qiita, Se, set, Sqlite, timezone, Tokyo, TwitterAPI, UP, コード, これ, システム, スクロール, スケジュール, ソース, ツイート, ところ, バージョン, パラメーター, ファイル, 一部, , 予定, 予約, 事項, , 使用, 偏頭痛, , 先日, 変更等, 大変, 投稿, 掲載, 数珠繋ぎ, 更新, 機能, 機能等, 此処, 注意, 管理, 編集, 記事, 近日, 追加, ,

Sqliteで作った簡易掲示板のコードを配布致します。#php #code

2022.09.20

Logging

おはようございます。台風は過ぎ去りましたがせっかくの三連休が残念です💦。

今日は先日、Sqliteを使用して簡易掲示板を作ってみましたのでコードを配布致します、尚、PHP8の環境下で動作させています(PHP7系でも動作すると思います)。

Sqliteってnow()関数がなかったりだとか、Deleteする時に、noカラムを昇順しlimitを使用して削除出来ないだとか、いろいろとMysqlとは違う所があり、面倒だなと思いながらコードを書きました、尚、SqliteはWebサーバーの階層に置かないように、置いても良いですが・・・。そのままの状態だと誰でもダウンロードが可能になってしまいますのでご注意ください。自分は地下に眠らしています😅。

一応、二重投稿防止の為に20秒経過しないと再投稿出来ないようにしています😌。トライしていない事は禁止ワード等がありません🤔。つけようと思ったのですがまぁ良いかなと、、、。

動作している環境のリンクはこちら。

https://reborn9.sakura.ne.jp/

軸となるPHPのソースコードを2つ貼っときますね。

<?php
session_start();
$toke_byte = openssl_random_pseudo_bytes(16);
$csrf_token = bin2hex($toke_byte);
$_SESSION['csrf_token'] = $csrf_token;
?>
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="Description" content="Enter your description here" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="assets/css/style.css?<?= time() ?>">
    <title>掲示板</title>
</head>

<body class="p-3 text-white">
    <div class="p-4 shadow rounded" style="background-color:#d6dbdf;">
        <div class="container mt-5">
            <div class="row">
            <div class="col-12 text-center">
                <h1 class="shadow" style="color:#195a57;">掲示板::version 2.5</h1>
            </div>
                <div class="col-12">
                    <div class="input-group shadow rounded">
                        <div class="input-group-append">
                            <span class="input-group-text bg-dark text-white" id="my-addon">ニックネーム</span>
                        </div>
                        <input class="form-control" type="text" name="name" placeholder="ニックネームを入力" aria-describedby="my-addon">
                    </div>
                    <div class="form-group shadow rounded">
                        <label for="my-textarea">コメント</label>
                        <textarea id="my-textarea" class="form-control" name="comment" rows="7"></textarea>
                    </div>
                    <button id="btn" class="mt-2 btn btn-info text-white shadow rounded" type="button">投稿する</button>
                </div>
            </div>
        </div>
        <div class="container mt-5">
            <div class="row">
                <div id="view" class="col-12"></div>
            </div>
        </div>
    </div>
    <footer>
        <a href="/">TOP</a> :: © Reborn9.sakura.ne.jp <?=date("Y")?>
    </footer>
    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.0/js/bootstrap.min.js"></script>
    <script src="assets/js/main.js?<?= time() ?>"></script>
</body>

</html>
<?php
class db
{
    var $pdo = null;
    function __construct()
    {
        try {
            $this->pdo = new PDO("sqlite:../../bbs.sqlite3");
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);        //code...
        } catch (\Throwable $th) {
            //throw $th;
            print $th->getMessage();
        }
    }
    function select_limit()
    {
        if($this->pdo){
            $stmt = $this->pdo->prepare('select * from bbs order by no desc limit 0,5');
            $stmt->execute();
            $result = $stmt->fetchAll();
            $stmt = null;
            $this->pdo = null;
            return new view($result);
        }
    }
    function insert($name,$comment,$sns_cnt=0)
    {

        try {
            $stmt = $this->pdo->prepare('INSERT INTO bbs (`time`,`name`,`comment`,sns_cnt)values(strftime(\'%Y年%m月%d日 %H時%M分%S秒\',CURRENT_TIMESTAMP, \'localtime\'),:name,:comment,:sns_cnt)');
            $stmt->bindParam(':name', $name, PDO::PARAM_STR);
            $stmt->bindParam(':comment', $comment, PDO::PARAM_STR);
            $stmt->bindParam(':sns_cnt', $sns_cnt, PDO::PARAM_INT);
            $stmt->execute();
            $stmt = $this->pdo->prepare('DELETE FROM bbs WHERE bbs.no = (SELECT no from bbs ORDER BY no ASC LIMIT 1);');
            $stmt->execute();
            $stmt = null;
            $this->pdo = null;
            return true;
        } catch (\Throwable $th) {
            print $th->getMessage();
            return false;
        }
    }
}

class view{
    var $item = null;
    function __construct($item)
    {
        $this->item = $item;        
    }
    function view_item($item="")
    {
        try {
            $item = $item?$item:$this->item;
            ob_start();
            ?>
            
            <?php
            foreach($item as $key=>$value){
                ?>
                <div class="mt-2 row txtbox shadow rounded">
                <div class="col-3 name_<?=$value["no"]?> rounded-start fs-6">
                    ニックネーム::<?=$value["name"]?>さん
                </div>
                <div class="col-9 time_<?=$value["no"]?> fs-6">
                    投稿日時::<?=$value["time"]?>
                </div>
                <div class="col-12 comment_<?=$value["no"]?>">
                    <?= nl2br($value["comment"])?>
                </div>
                <div class="col-12 sns_cnt_<?=$value["no"]?>">
                    <!-- <?=$value["sns_cnt"]?> -->
                </div>
                </div>
                <?php
            }        
            ?>
                
            <?php
            $ret["view"]= ob_get_clean();
            $ret["msg"]= "done";
    
        } catch (\Throwable $th) {
            //throw $th;
            $ret["msg"] = "error";
        }
        return $ret;
    }
}

session_start();
$ret = null;
$mode =  xss_defence($_POST["mode"]);
// $time =  ;
$name =  xss_defence($_POST["name"]);
$comment =  xss_defence($_POST["comment"]);
$sns_cnt =  (int)xss_defence($_POST["sns_cnt"]);
if (isset($_POST["csrf_token"]) 
 && $_POST["csrf_token"] === $_SESSION['csrf_token'] && (function($t){
    return time() - $t > 20?true:false;
 })($_SESSION["save"])) {
    if($mode==="save"){
        $name = !preg_replace("/[ | ]/","",$name)?"匿名":$name;
        $comment = !preg_replace("/[ | ]/","",$comment)?"":$comment;
        if($comment){
            $db = new db();
            $db->insert($name,$comment);
            $_SESSION["save"] = time();
        }
    }
    $db = null;
    $db = new db();
    $ret = $db->select_limit()->view_item();
    print  json_encode($ret);
}
function xss_defence($value){
    if(is_array($value)){
        foreach($value as $key=>$val){
            $value["$key"] = strip_tags($val);
            $value["$key"] = htmlspecialchars($value["$key"],ENT_QUOTES);
        }

    }else{
        $value = strip_tags($value);
        $value = htmlspecialchars($value);
    }
    return $value;
}

配布コードはこちらです。

タグ

20, 7, 8, Code, Delete, LIMIT, MYSQL, no, Now, php, Sqlite, web, いろいろ, カラム, コード, ご注意, サーバー, せっかく, そのまま, ダウンロード, トライ, ワード, 三連, , , 今日, , 使用, 先日, 削除, 動作, 可能, 台風, 地下, , 投稿, 掲示, 昇順, , 残念, , 状態, 環境, 禁止, 簡易, 経過, 自分, , , 配布, 関数, 防止, 階層, 面倒,