制限付きのクロンを無限寿限無にする方法。 #php #無限 #cron

2022.10.12

Logging

おはようございます🦏。昔の文章を読んでくれて今の記事を読まないユーザーさんがいます、凹む😖。

さて、今日はさくらレンタルサーバーでcronを制限以上に使う方法を数年前に書いた記事が未だに読まれたりするのでプログラムコードを直してタイトルも直してQiitaGithubにUPしました。

そのUPした記事があまりアクセスが跳ねなくて少しがっくりしたのがスポーツの日の朝の事です。Qiitaは何だか触りの記事かとても専門性の高い記事が人気を集めるだなって事を、この頃理解したのですが、自分は何方にも寄っていない記事なので跳ねないのかも知れません。

ソースコード貼り付けて置きます。尚、使い方などはQiitaGithubを参照してください。

<?php
date_default_timezone_set('Asia/Tokyo');
class cron
{
    public function __construct(mixed $filepath = "")
    {
        $val = @file_get_contents($this->pval($filepath));
        $obj_ = @json_decode($this->pval($val));
        $obj = (object)[];
        foreach ($obj_ as $key => $value) {
            $obj->name = "month";
            $obj->val = $value->m;
            if ($flg = $this->trigger_check($obj,"m",1,12)) {
                $obj->name = "day";
                $obj->val = $value->d;
                if ($flg = $this->trigger_check($obj,"d",1,31)) {
                    $obj->name = "hour";
                    $obj->val = $value->H;
                    if ($flg = $this->trigger_check($obj,"H",0,23)) {
                        $obj->name = "minutes";
                        $obj->val = $value->i;
                        if ($flg = $this->trigger_check($obj,"i",0,59)) {
                            $obj->name = "week";
                            $obj->val = implode(",", $value->w);
                            if ($flg = $this->trigger_check($obj,"w",0,0)) {
                                $this->command($value->command);
                            }
                        }
                    }
                }
            }
        }
    }
    public function command(mixed $command_val = "")
    {
        $command_val = $this->pval($command_val);
        exec($command_val . " > /dev/null &");
        // print "よろしくお願いします~~~!!".PHP_EOL;
        return true;
    }

    public function pval(mixed $val = "")
    {
        if (is_array($val)) {
            foreach ($val as $key => $value) {
                $val[$key] = strip_tags($value);
            }
        } else {
            $val = strip_tags($val);
        }
        return $val;
    }

    public function trigger_check(mixed $variable = "",mixed $d="",int $min=0 ,int $max=0)
    {
        if (!$variable) return false;
        if ($variable->val === "*") return true;
        switch ($variable->name) {
            case 'week':
                $value = @explode(",", $variable->val);
                return (int)$value[(int)date($d)] === 1 ? true : false;
                break;
            default:
                if (preg_match("/^(\*\/[0-9]{1,})$/", $variable->val)) {
                    $value = @explode("*/", $variable->val)[1];
                    if (is_numeric($value) && $value >= $min && $value <= $max) {
                        return (int)date($d) % $value === 0 ? true : false;
                    }
                }
                if (preg_match("/^([0-9]{1,}\,{1,})/", $variable->val)) {
                    $value = @explode(",", $variable->val);
                    $value = array_map('intval', $value);
                    return in_array((int)date($d), $value, true) === true ? true : false;
                }

                $value = (int)$variable->val;
                if (is_numeric($value) && $value >= $min && $value <= $max) {
                    return $value === (int)date($d) ? true : false;
                }
                return false;
                break;
        }
        return false;
    }
}

if($argv[1]){
    //argv
    new cron($argv[1]);
}


タグ

39, Asia, class, cron, date, default, github, lt, php, public, qiita, set, timezone, Tokyo, UP, アクセス, クロン, コード, サーバー, さくら, スポーツ, ソース, タイトル, プログラム, ユーザー, レンタル, , 人気, , 今日, 何方, 使い方, 制限, 参照, 寿限無, 専門性, 少し, , 文章, 方法, , , , 未だ, 無限, 理解, 自分, 記事, ,

数珠繋ぎのツイートシステムに予約機能を付けました😂 #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, コード, これ, システム, スクロール, スケジュール, ソース, ツイート, ところ, バージョン, パラメーター, ファイル, 一部, , 予定, 予約, 事項, , 使用, 偏頭痛, , 先日, 変更等, 大変, 投稿, 掲載, 数珠繋ぎ, 更新, 機能, 機能等, 此処, 注意, 管理, 編集, 記事, 近日, 追加, ,

WPのカレンダーや予約投稿の日付がズレてしまう件:WP5.3以降:?

2020.11.15

Logging

WPのカレンダーや予約投稿の日付がズレてしまう件:WP5.3以降に起きるらしい。ワードプレスが大幅なアップグレードしたことが影響しているみたいです。この原因を突き止めるのに結構時間がかかりました。頭の良い人はすごいなと関心、、、。原因ですが簡単に言うとテンプレートやプラグインに下記の関数を使用していたら何やら、日付がズレてしまうというなんとも言えない事象が起きる可能性があります。例えば、テンプレートのFunctions.phpの中にそういう記述があると表示される時にカレンダーがズレてしまうとかそういう現象が発生します。

date_default_timezone_set("Asia/Tokyo");

因みに自分はこの原因を突き止めるのに結構時間を割きました、共通してくれると有り難いです。参考にしたサイトを貼っときます。
https://blog.medical-design.co.jp/archives/2569

元リンクは下記のツイッターのリンクを参照ください。

https://twitter.com/zip358com/status/1327770010404601857

タグ

5.3, Asia, blog, co, date, default, functions, https, jp, medical-design, php, quot, set, timezone, Tokyo, wp, アップ, カレンダー, グレード, こと, サイト, ズレ, テンプレート, なん, プラグイン, プレス, ワード, 下記, , 予約, 事象, , , 使用, 共通, 原因, 参考, 可能性, 大幅, 影響, 投稿, 日付, , 時間, 現象, 発生, 簡単, 自分, 表示, 記述, 関心, 関数, ,

All in One SEO一括、自動入力したった。

2020.07.16

Logging

All in One SEO一括、自動入力したった。そのままです。SEO入力欄にデータを流し込みました。前処理として記事のID番号を列挙してJSONで保存しそのIDデータを使用してSEOタイトル、SEO ディスクリプション、SEO キーワードに記事のタイトル、記事内容、タグをそれぞれ流し込みました。この結果は数ヶ月ぐらいかかると思いますが、良い方向に動いていほしいものです。

ここではJSONデータは記載していませんがプログラム処理から想像出来るかと思います。

<?php
date_default_timezone_set("Asia/Tokyo");
require_once(__DIR__ . '/../wp-load.php');
class db{
    public $db = NULL;
    function __construct()
    {
        $this->db = new PDO('mysql:dbname=DBNAME;host=HOST;charset=utf8;', 'USER', 'PASS');
    }
    public function tbl_update($id,$title,$comment,$keyword){
		//
		$sdb = $this->db->prepare("select * from wp_postmeta where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_title';");
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$ret = $sdb->execute();
		var_dump($sdb->rowCount());
		if($sdb->rowCount()){
			$sdb = Null;
			$sdb = $this->db->prepare("UPDATE wp_postmeta set  wp_postmeta.meta_value = :title where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_title';");
		}else{
			$sdb = Null;
			$sdb = $this->db->prepare("INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES (:id,'_aioseop_title',:title);");
		}
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$sdb->bindParam(":title",$title,PDO::PARAM_STR);
		$ret = $sdb->execute();
		//
		//
		$sdb = $this->db->prepare("select * from wp_postmeta where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_description';");
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$ret = $sdb->execute();
		if($sdb->rowCount()){
			$sdb = Null;
			$sdb = $sdb = $this->db->prepare("UPDATE wp_postmeta set wp_postmeta.meta_value = :comment where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_description';");
		}else{
			$sdb = Null;
			$sdb = $this->db->prepare("INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES (:id,'_aioseop_description' ,:comment);");
		}
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$sdb->bindParam(":comment",$comment,PDO::PARAM_STR);
		$ret = $sdb->execute();
		//
		//
		$sdb = $this->db->prepare("select * from wp_postmeta where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_keywords';");
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$ret = $sdb->execute();
		if($sdb->rowCount()){
			$sdb = Null;
			$sdb = $this->db->prepare("UPDATE wp_postmeta set wp_postmeta.meta_value = :keyword where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_keywords';");
		}else{
			$sdb = Null;
			$sdb = $this->db->prepare("INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES (:id,'_aioseop_keywords' ,:keyword);");
		}
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$sdb->bindParam(":keyword",$keyword,PDO::PARAM_STR);
		$ret = $sdb->execute();
		$sdb = Null;
		$this->db = Null;
        return "{'id':$id,'title':'$title','comment':'$comment','keyword':'$keyword'}";
	}
}
//$_POST["ID"] = 9541;
$obj = (object)json_decode(file_get_contents("./postid.json"));
foreach($obj->rows as $key=>$val){
	$ID = (int)$val->ID;
  $page = get_post($ID);
	$title = mb_strimwidth($page->post_title,0,60,"…");
	$content = $page->post_content;
	$content = wp_strip_all_tags( $content );
	$content = mb_strimwidth(strip_shortcodes( $content ),0,160,"…");
	$keyword = array();
	$posttags = get_the_tags($ID);
	if ( $posttags ) {
	  foreach ( $posttags as $tag ) {
		$keyword[] = $tag->name;
	  }
	}
	$DB = new db();
	print count($keyword)>0?$DB->tbl_update($ID,$title,$content,implode(",",$keyword)):$DB->tbl_update($ID,$title,$content,"");
	$DB = Null;
}

タグ

39, all, Asia, class, construct, date, db, default, DIR, function, ID, in, json, lt, null, once, one, php, public, quot, require, SEO, set, timezone, Tokyo, wp-load, キーワード, ここ, それぞれ, タイトル, タグ, データ, ディスクリプション, プログラム, もの, 一括, 使用, 保存, 入力, 入力欄, 内容, 処理, 列挙, 前処理, 想像, , 方向, 番号, 結果, 自動, 記事, 記載,

bitflyer.comでAPI使ってみたよ、遅っいぞ。

2020.06.05

Logging

bitflyer.comでAPI使ってみたよ、遅っいぞ。自分の回線が悪いのかわからないけれど、データの結果が返却されるまで2?4分ぐらい時間がかかるのです、レスポンスが遅い恐ろしく遅いのだ。
まるでオイラのようだ(´・ω・`)。

ccxtとかも使ってみたら・・アレ大丈夫?
PHPで再度を自作してみた「body部分は間違っているかも。いや間違っているよ・・・?。」とぶつぶつ言いながら制作。

追記:
PHPのレスポンスが遅いのは、LinuxのOSをゴニョゴニョしたからでした。OS入れ直して再度コードを走らすと普通にレスポンスが返ってきました、、、。

返ってきたときには「ほんと、何やねん」とボヤきました?。

PHPのソースコードを記載します。

<?php
date_default_timezone_set('Asia/Tokyo');
class Api_Bitflyer_Class
{
    var $basic_url = "https://api.bitflyer.com";
    public function __construct()
    {
        require_once __DIR__."/../common/init.php";
    }
    /**
     * @param timestamp $timestamp
     * @param string $path
     * @param string $method
     * @param string $body
     */  
    public function api_set($timestamp = "", $path = "/v1/me/getbalance", $method = "GET", $body = "")
    {
        $url = $this->basic_url . $path;
        $data = strtolower($method) === "get" ? $timestamp . $method . $path : $timestamp . $method . $path . (function ($body) {
            if (!is_array($body)) {
                $body = [];
            }
            return json_encode($body);
        })($body);
        $access_singn = hash_hmac("sha256", $data, APISECRET);
        $headers = [
            'ACCESS-KEY: ' . APIKEY,
            'ACCESS-TIMESTAMP: ' . $timestamp,
            'ACCESS-SIGN: ' . $access_singn,
            'Content-Type: application/json',
        ];
        return new class($url, $method, $headers, $body)
        {
            var $url = "";
            var $method = "";
            var $headers = "";
            var $body = "";
            /**
             * @param string $url
             * @param string $method
             * @param string $headers
             * @param string $body
             */              
            public function __construct($url, $method, $headers, $body)
            {
                $this->url = $url;
                $this->method = $method;
                $this->headers = $headers;
                $this->body = $body;
            }
            public function api_run()
            {
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $this->url);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->method);
                curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
                strtolower($this->method) == "post" ? curl_setopt($curl, CURLOPT_POSTFIELDS, $this->body) : "";
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                $response             = curl_exec($curl);
                // $response_info        = curl_getinfo($curl);
                // $response_code        = $response_info['http_code'];
                // $response_header_size = $response_info['header_size'];
                curl_close($curl);
                print date("Y/m/d H:i:s");
                var_dump(json_decode($response));
                // var_dump($response_code);
                // var_dump($response_header_size);
            }
        };
    }
}

$Api_Bitflyer_Class = new Api_Bitflyer_Class();
$Api_Bitflyer_Class->api_set(time(),"/v1/me/getbalance","GET","")->api_run();

PHPとは別にnode.jsでリアルタイムAPIを使用した動画を貼っときます。

bitflyerAPI_PHPcode

なお、よく読んだほうが良いAPI Documentation

bitFlyer Lightning では、HTTP API と Realtime API の 2 種類の API を提供しています。

尚、ビットコイン高くて買えないので、ビットコインの売買したい知人は格安で自動売買のシステム作りますよ。

タグ

2, 39, 4, API, Asia, bitFlyer, body, ccxt, class, com, date, default, Linux, lt, OS, php, set, timezone, Tokyo, アレ, おいら, コード, ゴニョゴニョ, ソース, データ, とき, ほんと, レスポンス, , 再度, 制作, 回線, 時間, 普通, 結果, 自作, 自分, 記載, 返却, 追記, , 部分,

WPの記事を検索し一括カテゴリ変更する方法。

2020.05.25

Logging

WPの記事を検索し一括カテゴリ変更する方法は下記になります。ワードプレスのwp-load.phpを読み込み、下記のようなソースコードのファイルをcommandで実行すると、カテゴリが任意のカテゴリに変更されます。

重要点はwp_set_post_categoriesの引数です。arrayの配列の数値ですが、この数値をカテゴリIDのナンバーに変更することによってカテゴリが更新されます。

企業でご使用する場合はカテゴリ更新部分を一度、コメントアウトしCSVか何かでうまく記事が抽出できているか確認した後に、更新するようにお願い致します、当然ながら不具合等の苦情は受け付けません。自己責任でご使用くださいな。

尚、この下記のコードの意味がわからないという方は下記のURLからそれぞれのワードプレスようのメソッドが何を意味しているか調べてくださいね。
https://elearn.jp/wpman/

<?php
require_once(__DIR__ . '/../wp-load.php');
if ($argv[0]) {
    $args = array(
        'post_type ' => 'post',
        'posts_per_page' =>-1,
        's' => '映画'
    );
    $posts = get_posts($args);
    foreach ($posts as $val) {
        $href =  get_permalink($val->ID);
		$title = get_the_title($val->ID);
		$cnt++;
		echo $cnt.":".$title."\n".$href."\n";
		wp_set_post_categories($val->ID,array(1,2,3));
    }
}

タグ

-Command, 39, array, categories, CSV, DIR, ID, lt, once, php, POST, require, set, url, wp, wp-load, アウト, お願い, カテゴリ, コード, こと, コメント, ご使用, ソース, それぞれ, ナンバー, ファイル, プレス, メソッド, ワード, 一度, 一括, 下記, 不具合, 任意, 企業, , 何か, 使用, 場合, 変更, 実行, 引数, 当然, , 意味, 抽出, 数値, , 方法, 更新, 検索, 確認, 自己, 苦情, 記事, 責任, 部分, 配列, 重要点,

phpのPDOでバインドする時、こうすれば楽。

2020.02.28

Logging

phpのPDOでバインドする時、こうすれば楽ですよね(・(ェ)・)という記述です。前の職場ではsqliでDB接続していたのですが、バインドして作られていたかは忘れてしまいました。ちなみに前の職場のPDOに改修するのは面倒くさいだろうなと感じます。何がめんどくさいかと言えば、今まで導入していたもの全てに対応するというのは、超面倒くさいと思います。

余談:
前の職場を何故辞めたかのお話します。突発的に辞めたと思う人もいるかもしれませんが、基本的に突発的辞めることはないです。突発的に辞めたかのように見えて前々から考えてきっかけを理由に辞めました。具体的な理由に関してはここでは書きません。突発的に辞めたかのように見せかけて計画的です(・(ェ)・)


ソースコードは下記になります。

<?php
ini_set("display_errors",1);
class mysql {
    static $dbh = Null;
    static $host = "localhost";
    static $id = "あいーでぃー";
    static $pass= "パスワード";
    static $dbname = "test";
    static $sql = array(
        "id"=>array("data"=>PDO::PARAM_INT,"val"=>""),
        "name"=>array("data"=>PDO::PARAM_STR,"val"=>"")
    );
    static function connect()
    {
        /* 接続状況をチェックします */
        try {
            static::$dbh = new PDO('mysql:host='.static::$host.';dbname='.static::$dbname.';', static::$id, static::$pass);
            static::$dbh->query('SET NAMES utf8');
          } catch (Exception $e) {
            echo "Failed: " . $e->getMessage();
          }
    }
    static function insert_query(){
        //プリペアドステートメント
        $stmt = static::$dbh->prepare("insert into test1 (id,Name) values(:id,:name);");
        //バインド
        foreach(static::$sql as $key=>&$val){
            $stmt->bindParam(":$key",$val["val"],$val["data"]);
        }
        $stmt->execute();
        $stmt = null;
     }
     static function update_query(){
        //プリペアドステートメント
        $stmt = static::$dbh->prepare("update test1 set Name= :name where id = :id;");
        //バインド
        foreach(static::$sql as $key=>&$val){
            $stmt->bindParam(":$key",$val["val"],$val["data"]);
        }
        $stmt->execute();
        $stmt = null;
     }
     static function select_query(){
        //プリペアドステートメント
        $stmt = static::$dbh->prepare("select * from test1 where id = :id;");
        //バインド
        foreach(static::$sql as $key=>&$val){
            if($key==="id")$stmt->bindParam(":$key",$val["val"],$val["data"]);
        }
        $stmt->execute();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            printf ("%d (%s)<br>", $row["id"], $row["Name"]);
        }
        $stmt = null;
     }
    static function close(){
        static::$dbh = null;
    }
}
mysql::connect();
// for($i = 0 ;$i<=99;$i++){
//     mysql::$sql["id"]["val"] = $i;
//     mysql::$sql["name"]["val"] = "テスト$i";
//     mysql::insert_query();
// }
for($i = 0 ;$i<=99;$i++){
    mysql::$sql["id"]["val"] = $i;
    mysql::$sql["name"]["val"] = "テスト<font color='red'>$i</font>";
    mysql::update_query();
}
for($i = 0 ;$i<=99;$i++){
    mysql::$sql["id"]["val"] = $i;
    mysql::select_query();
}
mysql::close();

タグ

, class, db, dbh, display, errors, ini, lt, MYSQL, PDO, php, quot, set, sqli, static, お話, きっかけ, コード, ここ, こと, ソース, バインド, もの, 下記, , , 余談, 全て, , 前々, 対応, 導入, 接続, 改修, , 理由, 職場, 記述,

月の満ち欠けPHPライブラリを書きました。ちょっと適当なアイコンで表示。

2020.02.22

Logging

月の満ち欠けPHPライブラリを書きました、ご自由にお使いください。

ちょっと適当なアイコンで表示。
もっと正確なアイコンを取り入れたい方はご自身でご自由に変更ください。
月の満ち欠けの計算方法はネットから見つけてきました。
情報を記載していただいた先人の知恵を借りPHPライブラリが出来ました。
ありがとうございます。

<?php
//date_default_timezone_set('Asia/Tokyo');
class moon{
    static public $icon = array(
        "0"=>'?',//朔
        "1"=>'?',//朔
        "2"=>'?',//朔
        "3"=>'?',//三日月
        "4"=>'?',//三日月
        "5"=>'?',//三日月
        "6"=>'?',//三日月
        "7"=>'?',//上弦の月',
        "8"=>'?',//上弦の月',
        "9"=>'?',//上弦の月',
        "10"=>'?',//上弦の月',
        "11"=>'?',//上弦の月',
        "12"=>'?',//十三夜月
        "13"=>'?',//十三夜月
        "14"=>'?',//十三夜月
        "15"=>"?",//望月
        "16"=>"?",//望月
        "17"=>"?",//望月
        "18"=>"?",//望月
        "19"=>"?",//寝待月
        "20"=>"?",//寝待月
        "21"=>"?",//寝待月
        "22"=>"?",//寝待月
        "23"=>'?',//下弦の月
        "24"=>'?',//下弦の月
        "25"=>'?',//下弦の月
        "26"=>"?",//二十六夜月
        "27"=>"?",//二十六夜月
        "28"=>"?",//二十六夜月
        "29"=>"?"//二十六夜月
    );
    static public $res = "0";
    static public $moon_gregorian = array(0,2,0,2,2,4,5,6,7,8,9,10);
    public function main($year=2012,$mon=12,$day=12)
    {
        static::$res = ((($year-11)%19)*11 + static::$moon_gregorian[$mon-1]+$day)%30;
    }
    public function icon(){
        return static::$icon[static::$res];
    }
}

呼び出しはこんな感じで。

<?php
    moon::main($year,$mon,$day);
    $chg = moon::icon();

タグ

0, , 2, , 39, array, Asia, class, date, default, gt, icon, lt, moon, php, public, quot, set, static, timezone, Tokyo, アイコン, ご自身, ネット, ライブラリ, 先人, 変更, 情報, , 方法, , , 正確, 満ち欠け, 知恵, 表示, 計算, 記載, 適当,

画像ファイル系一覧のパスを列挙するバッチ

2019.08.17

Logging

setlocal enabledelayedexpansion
type nul >imglist.txt
set BEFORE_STRING=
set AFTER_STRING=/
set BEFORE_STRING2=F:/
set OUTPUT_FILE=imglist.txt
for /f %%a in ('dir /a-d /s /b *.jpg *.gif') do (
set line=%%a
set RES=!line:%BEFORE_STRING%=%AFTER_STRING%!
echo !RES:%BEFORE_STRING2%=!>>%OUTPUT_FILE%!
)
endlocal

画像ファイル系一覧のパスを列挙するバッチです。
ググりながら作ってみました。
ちなみに勘所はsetlocal enabledelayedexpansion(endlocal)と!です。
どうもforの中の変数をセットするタイミングが関係しているので
上記の文言を使用しないとうまく取り出す事が
できないようです。
遅延環境変数とかいうそうですね。。。
あまり理解していないけれどもorz

タグ

2, a-d, AFTER, BEFORE, DIR, do, echo, enabledelayedexpansion, endlocal, file, For, gif', gt, imglist, in, jpg, line, nul, OUTPUT, res, set, setlocal, string, txt, type, パス, バッチ, ファイル, 一覧, 列挙, 勘所, 画像,

同一TABLEを参照しアップデートする。

2019.04.27

Logging

同一TABLEを参照しアップデートする。
これでアップデートできる事を昨日知りました。

UPDATE demo1,(select chk from demo1 where id=1) as demo2 SET
demo = "2" where id = 1 and chk = demo2.chk;
--------------
--------------
/*
同一TABLEを参照しアップデートする。
table demo1
id,chk
1,123
*/
--------------

タグ

, 2, and, as, chk, demo, from, ID, select, set, TABLE, UPDATE, where, アップデート, これ, , 参照, 同一, 昨日,

VBAオブジェクトを自動生成しイベントを付与する。

2019.01.12

Logging

VBAオブジェクトを自動生成しイベントを付与する。
サンプルコードです。
ダウンロードはこちら
https://zip358.com/tool/sample.zip

Dim chg_class(0 To 5) As chg
Public Sub objset()
Dim obj_ctl As Control
Dim i As Integer
For i = LBound(chg_class) To UBound(chg_class)
    Set obj_ctl = UserForm1.Controls.Add("Forms.TextBox.1", "Box" & i)
    obj_ctl.Top = 10 + 20 * i
    obj_ctl.Width = 200
    obj_ctl.Height = 20
    obj_ctl.Text = "ここを変更してみて、またはダブルクリック(" & i & "番)"
    Set chg_class(i) = New chg
    chg_class(i).set_evn obj_ctl, i
    Set obj_ctl = Nothing
Next i
End Sub
Private WithEvents TextB As MSForms.TextBox
Private index_no As Integer
Public Sub set_evn(hoge_obj As MSForms.TextBox, hoge As Integer)
    Set TextB = hoge_obj
    index_no = hoge
End Sub
Private Sub TextB_Change()
    MsgBox TextB.Text 'UserForm1("Box" & index_no)
End Sub
Private Sub TextB_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    MsgBox TextB.Text 'UserForm1("Box" & index_no)
End Sub
Private Sub TextBox1_Change()
MsgBox TextBox1
End Sub
Private Sub CommandButton1_Click()
End Sub
Private Sub UserForm_Click()
End Sub

タグ

0, , 10, 20, 200, 358, 5, Add, amp, as, Box, chg, class, com, Control, Controls, ctl, Dim, For, Forms, Height, Integer, LBound, obj, objset, public, sample, set, Sub, Text, TextBox, To, tool, TOP, UBound, UserForm, VBA, Width, zip, イベント, オブジェクト, コード, ここ, こちら, サンプル, ダウンロード, 付与, 変更, 自動生成,

さくらレンタルサーバーとかで制限以上のクロンタブ(crontab)を使う方法。

2018.11.08

Logging

さくらレンタルサーバーとかで制限以上のクロンタブ(crontab)を使う方法
10年ぐらいまえのコードを見直して改善したコードが下記になります。
10年前はクラスを使わない方法で構築したのだけど、今回はクラスの概念を
使って構築。ここ何年かで自分のコーディングの技術は上がっているかといえば
そうでもないですが、昔よりかは技術の幅は広がっていると思いたいw
※qiita日付は数年前にUPしたのですけど、コード自体は10年前のコードです。

追記:2022/10/08 修正:詳しくはコチラ
https://qiita.com/question909/items/8f1df9b62ab4fba76243

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

タグ

08, 10, 2022, 39, 5, Asia, class, cron, crontab, date, default, function, if, lt, obj, php, public, qiita, set, timezone, Tokyo, UP, , クラス, クローン, クロン, コーディング, コード, ここ, コチラ, サーバー, さくら, タブ, まえ, レンタル, 下記, 今回, 何年か, 修正, 処理, 分刻み, 制限, 場合, , 技術, 改善, , 方法, 日付, , 有効, 概念, 構築, 無限, 自体, 自分, 負荷, 追記,

昨日の続き、cronPHP(´Д`)、一つのジョブから複数のPHPファイルを実行させる方法。

2015.06.25

Logging

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

 
この頃、ネタがないので手抜き投稿です。気づいた人どのぐらいいるのだろうか?
Qittaに公開しました。https://qiita.com/question909/items/8f1df9b62ab4fba76243

タグ

39, 5, Asia, class, comma, cron, cronphp, date, default, function, gt, if, int, lt, match, obj, php, preg, public, quot, retu, return, set, this, timezone, Tokyo, true, クローン, ジョブ, ファイル, 一つ, 処理, 分刻み, 場合, 実行, 方法, 昨日, 有効, 無限, 複数, 負荷,

cronPHPを作ってみた朝の続き。

2015.06.24

Logging


 
cronPHPを作ってみた朝の続き・・・たぶん、コレだけで十分かと思います(稼働させてないのでどう動くかは不明?)。仕事帰って作りました。この頃、もっと勉強しないとなと思うこの頃です。いまの自分に足りないのは間違いなく技術力です、あとタイピングとか・・・かなり遅いので生産性がかなり低いです。英語を打つのに遅すぎる・・・・。日本語はまぁまぁ早いのですけど。キーを覚えているというよりは何となく覚えているので・・・・なぜ、タイピングできるのか自分でも不思議なのです。
 

追記2022/09/06:詳しくは、こちらを参照くださいませ

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

タグ

06, 09, 2022, 39, 5, Asia, class, cron, cronphp, date, default, function, lt, nbsp, obj, php, public, set, timezone, Tokyo, いま, かなり, キー, クローン, こちら, コレ, ダイビング, 不思議, 不明, 仕事, 処理, 分刻み, 勉強, 参照, 場合, 技術力, 日本語, 有効, , 無限, 生産性, 稼働, 自分, 英語, 負荷, 追記, ,