<?php /* rss用フィードを作成するcgiファイル * index.html, atom.xml, index.rdf */ $RSS_FEED_NUM = 10; // RSSのフィード数 //1 . RSSヘッダー作成 $rss = ''; $rss = $rss . '<?xml version="1.0" encoding="utf-8" ?>'; $rss = $rss . '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" ' . 'xmlns:content="http://purl.org/rss/1.0/modules/content/" xml:lang="ja">'; $rss = $rss . '<channel>'; $rss = $rss . '<title>YoheiM.NET - 世の中をさらに便利に面白く</title>'; $rss = $rss . '<link>http://www.yoheim.net/</link>'; $rss = $rss . '<description>YoheiM.NET - 世の中をさらに便利に、面白く</description>'; $rss = $rss . '<dc:creator>yoheiM</dc:creator>'; //2. RSSのデータ部分を好きな数だけ作成する。今回は10個。 // フィードに出力するファイルパスの配列を取得 $file_list = getFeedList(); // FEED数分作成する for ($i = 0; $i < $RSS_FEED_NUM; $i++){ // ブログタイトルを取得 $fPath = $file_list[$i]; $f = fopen($fPath, "rb"); $title = fgets($f); fclose($f); $title = getTitle($fPath); // blog urlを取得 $blogURL = getURL($fPath); // ブログの中身を取得する $content = ''; $fPath = $file_list[$i]; $fp = fopen($fPath, "rb"); while (!feof($fp)){ $buf = fgets($fp); $content = $content . $buf; } fclose($fp); // 作成日時を作成 // ファイルの更新日時を使う date_default_timezone_set('Asia/Tokyo'); $pubDate = date("D, d M Y H:i:s", filetime($fPath)); // Feed作成 $item = ''; $item = $item . '<item>'; $item = $item . '<title>' . $title . '</title>'; $item = $item . '<link>' . $blogURL . '</link>'; $item = $item . '<description><![CDATA['; $item = $item . $content; $item = $item . ']]></description>'; $item = $item . '<dc:creator>yoheiM</dc:creator>'; $item = $item . '<pubDate>'. $pubDate . '</pubDate>'; $item = $item . '</item>'; $rss = $rss . $item; } // 3, RSSの絞めタグなどを作成 $rss = $rss . '</channel>'; $rss = $rss . '</rss>'; // 4, RSSファイルとして認識されうるファイルを3個くらい出力 $f = fopen("index.xml", "wb"); fwrite($f, $rss); fclose($f); $f = fopen("atom.xml", "wb"); fwrite($f, $rss); fclose($f); $f = fopen("index.rdf", "wd"); fwrite($f, $rss); fclose($f); // end echo "OK\n"; ?>
make a xml file
<?php include_once './RssFeed.php'; include_once './RssItem.php'; $rss = new RssFeed(); $rss->title('サイトタイトル'); $rss->description('サイトの説明文です'); $rss->link('http://example.com/'); $rss->atomLink('http://example.com/rss.xml'); $item = new RssItem(); $item->title('記事1'); $item->description('ここに要約が入ります'); $item->link('http://example.com/1'); $item->guid('http://example.com/1'); $item->pubDate('2016-01-02 12:23:34'); $rss->addItem($item); header('Content-type:application/rss+xml'); echo $rss->saveXML();
<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <title>サイトタイトル</title> <description><![CDATA[サイトの説明文です]]></description> <link>http://example.com/</link> <atom:link href="http://example.com/rss.xml" rel="self" type="application/rss+xml"/> <item> <title>記事1</title> <description><![CDATA[ここに要約が入ります]]></description> <link>http://example.com/1</link> <guid isPermaLink="true">http://example.com/1</guid> <pubDate>Sat, 02 Jan 2016 12:23:34 +0900</pubDate> </item> </channel> </rss>
file_put_contents($file, $xml);
RSS1.0
シンプルな記述。テキスト配信向き
RDFシリーズを元にして制作。
はてなRSSは1.0。FC2も1.0。
RSS2.0
配信する文章の色を変えたり、リンクを仕込めるなど、グラフィック面でいろいろ出来る。コンテンツ配信向き
XMLシリーズを元にして制作されている。
<?php // ライブラリの読み込み require_once "./Item.php" ; require_once "./Feed.php" ; require_once "./RSS2.php" ; // エイリアスの作成 use \FeedWriter\RSS2 ; // インスタンスの作成 $feed = new RSS2 ; // チャンネル情報 $feed->setTitle( "SYNCER" ) ; // チャンネル名 $feed->setLink( "https://syncer.jp" ) ; // URLアドレス $feed->setDescription( "知識と感動を同期(Sync)するブログ" ) ; // チャンネル紹介テキスト $feed->setImage( "SYNCER" , "https://syncer.jp","https://syncer.jp/images/DHFgXv5Rfe4d1Lej1lnQfuffZtzsj/assets/logo/490x196.png" ) ; // ロゴなどの画像 $feed->setDate( date( DATE_RSS , time() ) ) ; // フィードの更新時刻 $feed->setChannelElement( "language" , "ja-JP" ) ; // 言語 $feed->setChannelElement( "pubDate" , date(\DATE_RSS, strtotime("2014-11-23 15:30")) ) ; // フィードの変更時刻 $feed->setChannelElement( "category" , "Blog" ) ; // カテゴリー // アイテム(1つだけ登録) $item = $feed->createNewItem() ; $item->setTitle( "PHPでRSS、AtomのFeedを作成する方法" ) ; // タイトル $item->setLink( "https://syncer.jp/how-to-make-feed-by-php" ) ; // リンク $item->setDescription( "PHPを使って、RSS、Atomのフィード・ファイルを作成する方法を解説します。" ) ; // 紹介テキスト $item->setDate( strtotime("2014-11-23 18:30") ) ; // 更新日時 $item->setAuthor( "あらゆ" , "info@syncer.jp" ) ; // 著者の連絡先(E-mail) $item->setId( "https://syncer.jp/how-to-make-feed-by-php" , true ) ; // 一意のID(第1引数にURLアドレス、第2引数にtrueで通常は大丈夫) $feed->addItem( $item ) ; // コードの生成 $xml = $feed->generateFeed() ; // ファイルの保存場所を設定 $file = "./rss2_2.xml" ; // ファイルの保存を実行 @file_put_contents( $file , $xml ) ;
<rss version="2.0"> <channel> <title>SYNCER</title> <link>https://syncer.jp</link> <description> <![CDATA[ 知識と感動を同期(Sync)するブログ ]]> </description> <image> <title>https://syncer.jp</title> <link> https://syncer.jp/images/DHFgXv5Rfe4d1Lej1lnQfuffZtzsj/assets/logo/490x196.png </link> <url>SYNCER</url> </image> <lastBuildDate>Wed, 14 Dec 2016 21:30:07 +0900</lastBuildDate> <language>ja-JP</language> <pubDate>Sun, 23 Nov 2014 15:30:00 +0900</pubDate> <category>Blog</category> <item> <title>PHPでRSS、AtomのFeedを作成する方法</title> <link>https://syncer.jp/how-to-make-feed-by-php</link> <description> <![CDATA[ PHPを使って、RSS、Atomのフィード・ファイルを作成する方法を解説します。 ]]> </description> <pubDate>Sun, 23 Nov 2014 18:30:00 +0900</pubDate> <author>info@syncer.jp (あらゆ)</author> <guid isPermaLink="true">https://syncer.jp/how-to-make-feed-by-php</guid> </item> </channel> </rss>
Insert DB-API
Inserts in DB API pg = psycopg2.connect("dbname=somedb") c = pg.cursor() c.execute("insert into names values('Jennifer Smith')") pg.commit() import sqlite3 db = sqlite3.connect("testdb") c = db.cursor() c.execute("insert into balloons values ('blue', 'water') ") db.commit() db.close()
DB data attack
‘); delete from posts;–
spam table
<script> setTimeout(function() { var tt = document.getElementById('content'); tt.value = "<h2 style='color: #FF6699; font-family: Comic Sans MS'>Spam, spam, spam, spam,<br>Wonderful spam, glorious spam!</h2>"; tt.form.submit(); }, 2500); </script>
Python DB-API
Python DB-API is a library method call sqlite and data.
writing DB-API
import sqlite3 conn = sqlite3.connect("Cookies") cursor = conn.cursor() cursor.execute( "select host_key from cookies limit 10") results = cursor.fetchall() print results conn.close()
Watch how DB-API work below.
import sqlite3 # Fetch some student records from the database. db = sqlite3.connect("students") c = db.cursor() query = "select name, id from students;" c.execute(query) rows = c.fetchall() # First, what data structure did we get? print "Row data:" print rows # And let's loop over it too: print print "Student names:" for row in rows: print " ", row[0] db.close()
Result
Row data:
[(u’Jade Harley’, 441304), (u’Harry Evans-Verres’, 172342), (u’Taylor Hebert’, 654321), (u’Diane Paiwonski’, 773217), (u’Melpomene Murray’, 102030), (u’Robert Oliver Howard’, 124816), (u’Hoban Washburne’, 186753), (u’Trevor Bruttenholm’, 162636), (u’Jonathan Frisby’, 917151)]
Student names:
Jade Harley
Harry Evans-Verres
Taylor Hebert
Diane Paiwonski
Melpomene Murray
Robert Oliver Howard
Hoban Washburne
Trevor Bruttenholm
Jonathan Frisby
order by [ASC | DESC]
postgres
restart
sudo /etc/rc.d/init.d/postgresql restart
[vagrant@localhost web]$ psql -U postgres
psql (8.4.20)
“help” でヘルプを表示します.
postgres=#
sql join on
QUERY = ''' select animals.name from animals join diet on animals.species = diet.species where food = 'fish'; '''
having
QUERY = ''' select species, count(*) as num from animals group by species having num = 1; '''
QUERY = ''' select species, count(*) as num from animals group by species having num = 1; ''' QUERY = ''' select diet.food, count(*) as num from animals join diet on animals.species = diet.species group by food having num = 1; '''
python sql
QUERY = ''' select name, birthdate from animals where species = 'gorilla'; '''
+———+————+
| name | birthdate |
+=========+============+
| Max | 2001-04-23 |
| Dave | 1988-09-29 |
| Becky | 1979-07-04 |
| Liz | 1998-06-12 |
| George | 2011-01-09 |
| George | 1998-05-18 |
| Wendell | 1982-09-24 |
| Bjorn | 2000-03-07 |
| Kristen | 1990-04-25 |
+———+————+
select name, birthdate from animals where species = ‘gorilla’ and name = ‘Max’
否定
QUERY = ''' select name, birthdate from animals where species != 'gorilla' and name != 'Max'; '''
between文
QUERY = ''' select name from animals where species = 'llama' AND birthdate between '1995-01-01' AND '1998-12-31'; '''
query
QUERY = "select max(name) from animals;" QUERY = "select * from animals limit 10;" QUERY = "select * from animals where species = 'orangutan' order by birthdate;" QUERY = "select name from animals where species = 'orangutan' order by birthdate desc;" QUERY = "select name, birthdate from animals order by name limit 10 offset 20;" QUERY = "select species, min(birthdate) from animals group by species;" QUERY = ''' select name, count(*) as num from animals group by name order by num desc limit 5; '''
Limit count Offset skip
limit is how many rows to return
offset is how far into the results to start
Order by columns DESC
columns is which columns to sort by, separated with commas
DESC is sort in reverse order(descending)
Group by columns
columns is which columns to use as groupings when aggregating
QUERY = "select count(*) as num, species from animals group by species order by num desc;"
insert
INSERT_QUERY = ''' insert into animals (name, species, birthdate) values ('yoshi', 'opposum', '2016-12-13'); '''
How Queries Happen
although same RDB principle, different environments.
mysql, postgresql, oracle, etc
-> TCP/IP network with DB server and data on disk
sqlite
-> DB library and data on disk
php mysql で画像アップロード
<?php /* html特殊文字をエスケープする関数 */ function h($str) { return htmlspecialchars($str, ENT_QUOTES, 'utf-8'); } // xhtmlとしてブラウザに認識させる //(ie8以下はサポート対象外) header('Content-Type: application/xhtml+xml; charset=utf-8'); try { // データベースに接続 $pdo = new PDO( 'mysql:host=localhost;dbname=test;charset=utf8', 'root', '', [ PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ] ); /* アップロードがあったとき */ if (isset($_FILES['upfile']['error']) && is_int($_FILES['upfile']['error'])){ // バッファリングを開始 ob_start(); try { // $_FILES['upfile']['error']の値を確認 switch ($_FILES['upfile']['error']){ case UPLOAD_ERR_OK: // ok break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException('ファイルが選択されていません', 400); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException('ファイルサイズが大きすぎます', 400); default: throw new RuntimeException('その他のエラーが発生しました', 500); } // $_FILES['upfile']['mime']の値はブラウザ側で偽装可能なので // MIMEタイプを自前でチェックする if (!$info = getimagesize($_FILES['upfile']['tmp_name'])){ throw new RuntimeException('有効な画像ファイルを指定してください', 400); } if (!in_array($info[2], [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG], true)){ throw new RuntimeException('未対応の画像形式です', 400); } // サムネイルをバッファに出力 $create = str_replace('/', 'createfrom', $info['mime']); $output = str_replace('/', '', $info['mime']); if ($info[0] >= $inf0[1]){ $dst_w = 120; $dst_h = ceil(120 * $info[1] / max($info[0], 1)); } else { $dst_w = ceil(120 * $info[0] / max($info[1], 1)); $dst_h = 120; } if (!$src = @$create($_FILES['upfile']['tmp_name'])){ throw new RuntimeException('画像リソースの生成に失敗しました', 500); } $dst = imagecreatetruecolor($dst_w, $dst_h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $dst_w, $dst_h, $info[0], $info[1]); $output($dst); imagedestroy($src); imagedestroy($dst); // INSERT処理 $stmt = $pdo->prepare('INSERT INTO image(name,type,raw_data,thumb_data,date) VALUES(?,?,?,?,?)'); $stmt->execute([ $_FILES['upfile']['name'], $info[2], file_get_contents($_FILES['upfile']['tmp_name']), ob_get_clean(), (new DateTime('now', new DateTimeZone('Asia/Tokyo')))->format('Y-m-d H:i:s'), ]); $msgs[] = ['green', 'ファイルは正常にアップロードされました']; } catch (RuntimeException $e){ while(ob_get_level()){ ob_end_clean(); } http_response_code($e instanceof PDOException ? 500 : $e->getCode()); $msgs[] = ['red', $e->geteMessage()]; } } elseif (isset($_GET['id'])){ try { $stmt = $pdo->prepare('SELECT type, raw_data FROM iamge WHERE id = ? LIMIT 1'); $stmt->bindValue(1, $_GET['id'], PDO::PARAM_INT); $stmt->execute(); if (!$row = $stmt->fetch()){ throw new RuntimeException('該当する画像は存在しません', 404); } header('X-Content-Type-Options: nosniff'); header('Content-Type: ' . image_type_to_mime_type($row['type'])); echo $row['raw_data']; exit; } catch (RuntimeException $e){ http_response_code($e instanceof PDOException ? 500 : $e->getCode()); $msgs[] = ['red', $e->getMessage()]; } } $rows = $pdo->query('SELECT id,name,type,thumb_data,data From image ORDER BY date DESC')->fetchAll(); } catch(PDOException $e){ http_response_code(500); $msgs[] = ['red', $e->getMessage()]; } ?> <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>画像アップロード</title> <style><![CDATA[ fieldset { margin: 10px; } legend { font-size: 12px; } img { border: none; float: left; } ]]></style> </head> <body> <form enctype="multipart/form-data" method="post" action=""> <fieldset> <legend>画像ファイルを選択(GIF, JPEG, PNGのみ対応)</legend> <input type="file" name="upfile" /><br> <input type="submit" value="送信" /> </fieldset> </form> <?php if (!empty($msgs)): ?> <fieldset> <legend>メッセージ</legend> <?php foreach ($msgs as $msg): ?> <ul> <li style="color:<?=h($msg[0])?>;"><?=h($msg[1])?></li> </ul> <?php endforeach; ?> </fieldset> <?php endif; ?> <?php if (!empty($rows)): ?> <fieldset> <legend>サムネイル一覧(クリックすると原寸大表示)</legend> <?php foreach ($rows as $i => $row): ?> <?php if ($i): ?> <hr /> <?php endif; ?> <p> <?=sprintf( '<a href="?id=%d"><img src="data:%s;base64,%s" alt="%s" /></a>', $row['id'], image_type_to_mime_type($row['type']), base64_encode($row['thumb_data']), h($row['name']) )?><br> ファイル名: <?=h($row['name'])?><br /> 日付: <?=h($row['date'])?><br clear="all"> </p> <?php endforeach; ?> </fieldset> <?php endif; ?> </body> </html>