Saturday, June 14, 2008

MVC コントローラー URLによる動的にモジュールを呼ぶ

----- test.php
<?php

/*
e.g
test.php/c=user_proile/m=register/

*/

$path_info = explode('/', $_SERVER['PATH_INFO']);
while(list($cnt,$path) = each($path_info)) {
if ($path == "") continue;
list($key,$value) = explode('=', $path);
if ($key =="c") {
$MyClass = $value;
continue;
}
if ($key =="m") {
$MyMethod = $value;
continue;
}

$_GET[$key] = $value;
}

// overloading is also ok, if PHP5.
if ($MyClass != "" && is_file($MyClass.".php")) {
include_once($MyClass.".php");
if (class_exists($MyClass)) {
$MyModel = new $MyClass;
if (method_exists($MyModel,"dispatch")) {
$MyModel->dispatch($MyMethod);
}
}
}


?>
-----user_proile.php

<?php
class user_proile
{
function dispatch($action)
{
echo $action;

}


}
?>

refer to:
2008/03/php-mvc-controller.html

2005/01/pathinfo.html

Thursday, June 12, 2008

PHP4 でのRSS リーダー sample

http://keithdevens.com/software/phpxml
からPHP XML Libraryをとってくる。


<?php // Load and parse the XML document

$url = 'http://hogehoge/blog/?feed=rss2';

$xml_data1 = file_get_contents($url) or die();

require_once('xml.php');
$xml_array = XML_unserialize($xml_data1);
$items = $xml_array['rss']['channel']['item'];
unset ($xml_array);
unset ($xml_data1);

foreach ($items as $item) {
echo "<h3><a href='" . $item['link'] . "'>" . $item['title'] . "</a></h3>";
echo "<p>" . mb_strimwidth($item['description'], 0, 60, "...",'utf8') . "</p>";
break;

}
unset ($items);


?>

php ファイル名の一覧の取得

<?php

$regex = "([^\/]+).mp3$";
$dir =".";
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ( preg_match ( "/".$regex."/", $file, $matches) ) {
echo $file;
$files[] = $file;
// $matches[1]で名前だけとるのもあり。
}
}
closedir($handle);
}

?>

Tuesday, June 10, 2008

rss reader by PHP5 (sample)

<?php

$feed = 'http://test.com/?feed=rss2';
$rss = simplexml_load_file($feed);
$title = $rss->channel->title;
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>

<h1><?php echo $title; ?></h1>

<?php
foreach ($rss->channel->item as $item) {
echo "<h3><a href='" . $item->link . "'>" . $item->title . "</a></h3>";
$pdate = $item->pubDate;
echo date("Y/m/d G:H:i",strtotime($pdate));
echo "<p>" . $item->description . "</p>";
echo "<p>" . $item->category . "</p>";
}
?>

</body>
</html>

Wednesday, June 04, 2008

WordPressで独自ページをつくるサンプル

<?php

define('WP_USE_THEMES', false);
require('wp-blog-header.php'); // 共通関数を使うため
get_header();// テンプレートを仕様

$sql = "SELECT category_count FROM " .$wpdb->categories . " WHERE cat_ID=1" ;
echo $wpdb->get_var($sql);
get_footer(); // テンプレートを仕様

?>

-------------------------------
<?php
require('wp-blog-header.php'); // 共通関数を使うため
$option = 'cat=3&showposts=100&year=2008&order=ASC';

?>
<?php query_posts($option); ?>
<?php if(have_posts()):while(have_posts()):the_post(); ?>
<p><?php the_time('Y.m.d'); ?></p>
<p><a href="detail.php?id=<?php the_ID(); ?>"><?php echo $post->post_title ; ?></a>
</p>
<p><?php the_content(); ?></p>

<?php endwhile;endif; ?>

---------

カテゴリ指定の年ごとのリンクの作成

$category_id = 3;
$sort =" ASC";

$arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS year, count(ID) as posts
FROM $wpdb->posts, $wpdb->term_relationships
WHERE
$wpdb->posts.ID = $wpdb->term_relationships.object_id
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->term_relationships.term_taxonomy_id = '$category_id'
GROUP BY YEAR(post_date) ORDER BY post_date " . $sort);

foreach ($arcresults as $arcresult) {
echo "<li><a href=\"/?year=".$arcresult->year."\">".$arcresult->year."年</a></li>";
}


----
bloggerの投稿するときの文字の確認を入力、読めない

Tuesday, June 03, 2008

PHP memcache のインストール

簡単にインストールできると思ったら失敗したのでここに記す。

pecl download memcache

pecl install memcache-2.2.3.tgz << 落としたものにする

インストールに設定したら、php.iniの編集

extension=memcache.so

動かない場合は インストール成功時に表示されるパスを書けばOK
extension="/usr/local/lib/php/extensions/no-debug-non-zts-20060613/memcache.so"

最後にapacheの再起動
再起動をしないとphpは反映されません。

Thursday, March 27, 2008

PHP MVC controllerの勉強

class base {

function __construct() {
}
function dispatch($action){
try{
$this->$action();
}catch( Exception $e ){
$this->errorAction($e->getMessage());
}
}
function errorAction($str=null){
echo "overridden";
}
}

class Front extends Base {

function __construct() {
}

function page() {
throw new Exception( 'Template error.' );
echo "page";
}

function errorAction($str=null){
echo "Front:".$str;
}
}

$f = new Front;
$f->dispatch("page");

Wednesday, January 16, 2008

mod_rewrite 特定のURLを対象外

<Directory "/***">
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\.(cgi|css|gif|jpe?g|png)$


RewriteRule ^(.+)/bookmark/movie/list/([0-9]+)/?$ hoge2.php?page=$1&id=$2&%{QUERY_STRING} [L]
RewriteRule ^(.+)/movie/list/([0-9]+)/?$ hoge.php?page=$1&page2=$2&%{QUERY_STRING} [L]



</Directory>

Tuesday, January 15, 2008

直リンクの禁止 バーチャルドメインの場合

<VirtualHost 192.168.*.*>
ServerName example.com
DocumentRoot /home/example/htdocs
ServerAdmin webmaster@www.hoge.co.jp
ErrorLog logs/error_log
TransferLog logs/access_log

#<Files *.gif>

<Files ~ "\.(tbz|tgz|bz2|gz|tar|lzh|zip|mag|png|jpeg|jpg|gif)$">

SetEnvIf referer "^http://example\.com" RefOk
Order Deny,Allow
Deny from all
Allow from env=RefOk
</Files>

</VirtualHost>

Monday, January 07, 2008

年齢 MYSQL PHP

select (YEAR(CURDATE())-YEAR(birth))- (RIGHT(CURDATE(),5) <RIGHT(birth,5)) AS age from hoge

----

PHPの場合

<?php
$birthday = '1990-01-12';
$lapse = getdate(mktime()-mktime(0,0,0,substr($birthday,5,2),
substr($birthday,8,2),substr($birthday,0,4)));
$age = $lapse['year']-1990;
echo $age;
?>
~

Thursday, January 03, 2008

javascript 日付チェック

if(!chkDate(document.form.year.value,document.form.month.value,document.form.day.value)) {
alert("日付を正しく入力してください。");
return false;
}


function chkDate(y,m,d){
var date1 = new Date(y,m-1,d);
if(date1.getFullYear() == y && date1.getMonth() == m-1 && date1.getDate() == d){
return true;
}
return false;
}

Thursday, December 27, 2007

PHP のCookie

"/" があると動かないときがある。
setcookie("TestCookie", $value, time()+3600, "/", ".example.com", 1);
その場合は なしで確認。
$expire = time()+60*60*24*180;// 180days
setcookie( COOKIE_U, $u_ca , $expire);
setcookie(COOKIE_U_COMMON , $c1 , $expire);

Thursday, December 20, 2007

javascript パスワード

function checkP() {
if(!document.formP.password.value){
alert("現在のパスワードを入力してください");
return false;
}else if(!document.formP.password1.value){
alert("新しいパスワードを入力してください");
return false;
}else if(!document.formP.password2.value){
alert("新しいパスワード確認を入力してください");
return false;
}else if(!document.formP.password.value.match(/^[a-zA-Z\d]+$/i)){
alert("今のパスワードには半角英数字しか使用できません。");
return false;
}else if(!document.formP.password1.value.match(/^[a-zA-Z\d]+$/i)){
alert("新しいパスワードには半角英数字しか使用できません。");
return false;
}else if(!document.formP.password2.value.match(/^[a-zA-Z\d]+$/i)){
alert("新しいパスワード確認には半角英数字しか使用できません。");
return false;
}else if(document.formP.password1.value.length < 4){
alert("新しいパスワードには4文字以上入力してください");
return false;
}else if(document.formP.password1.value.length < 4){
alert("新しいパスワードには4文字以上入力してください");
return false;
}else if(document.formP.password1.value != document.formP.password2.value){
alert("新しいパスワード確認が一致しません");
return false;
}else{
return true;
}
}

Monday, December 17, 2007

メールアドレスのチェック javascript

<SCRIPT LANGUAGE="javascript">
function check() {

var matchemail=/[!#-9A-~]+@+[a-z0-9]+.+[^.]$/i;

if(!document.step.mail.value) {
alert("メールアドレスを入力してください");
return false;
}else if( !(document.step.mail.value.match(matchemail))){
alert("メールアドレスが不正です。") ;
return false;
}else if(check_zenkaku(document.step.mail.value)){
alert("全角文字が使用されております。");
return false;
}else if( document.step.mail.value.match(/(docomo|ezweb|vodafone|softbank)\.ne.jp$/i)){
alert("申し訳ございませんが、携帯電話のメールアドレスはご使用できません。") ;
return false ;
}else{
return true;
}
}

function check_zenkaku(elm){
var txt=elm;
for(i=0;i<txt.length;i++){
if(escape(txt.charAt(i)).length>=4){
return true;
break;
}
}
return false ;
}

</SCRIPT>

Friday, December 14, 2007

jquery.js でHTMLファイルのインクルード

PHPなどで使用しているHTMLファイルのインクルードをjquery.js
を使って行う例

これでfooterやheaderなど同じような箇所をコピペしなくてもよくなり、
メンテナンスが楽になります。

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript"><!--
$(function(){
$("#header_js").load("header.html");
});
// --></script>

</head>

<body>
<div id="header_js"></div>

Wednesday, December 12, 2007

checkbox すべてをON・OFF PHPの場合

function checkAll() {
if(document.myForm.checkall.checked){
for(i=0;i if (document.myForm.elements[i].name == "ch[]"){
document.myForm.elements[i].checked = true;
}
}
}else{
for(i=0;i if (document.myForm.elements[i].name == "ch[]"){
document.myForm.elements[i].checked = false;
}
}
}
}

-----

<input type="checkbox" name="checkall" value="" onclick="checkAll(); ">
<input type="checkbox" name="ch[]" value="1">
<input type="checkbox" name="ch[]" value="2">

Sunday, November 25, 2007

prototype.js Ajax.RequestのonCompleteにパラメータ

はてなに出ていたソースをそのまま引用です。

http://q.hatena.ne.jp/1174489396
javascriptってすごいですね。

<html>
<head>
<title></title>
<script language="javascript" src="prototype.js" charset="utf-8"></script>
<script language="javascript">
<!--
function ajax1(id){
new Ajax.Request(
'test.txt',
{ onComplete : function(req){
Seiko(id, req);
}
});
}
function Seiko(id, req){
$(id).innerHTML = req.responseText;
}
//-->
</script>
</head>
<body>
<div id="test"></div>
<button onclick="ajax1('test');">TEST</button>
</body>
</html>

Monday, October 29, 2007

プレビューのサンプル

<HTML>
<HEAD><TITLE>プレビュー</TITLE>
<script type="text/javascript" src="/prototype.js"></script>
<SCRIPT LANGUAGE="JavaScript">
<!--
function Preview()
{
// IE ONLY
// canvas.innerHTML =document.getElementById("body").value;
// prototype
var body = document.form.body.value.replace(/\x0D\x0A|\x0D|\x0A/g,'<br>')
$('canvas').innerHTML = body ;
}
//-->
</SCRIPT>

</HEAD>
<BODY>
<form name="form">
<textarea name="body" rows="10" onmouseup="Preview();" onkeydown="Preview();" onkeyup="Preview();" style="width:570px"></textarea>
</form>

<div id="canvas"></div>


</BODY>
</HTML>

Friday, October 19, 2007

mecab 0.96 インストール

tar xvzf mecab-0.96.tar.gz
cd mecab-0.96
./configure
./make
./make install

vi /etc/ld.so.conf
/usr/local/lib を追加
ldconfig を実行

tar xvzf mecab-ipadic-2.7.0-20070801.tar.gz
cd mecab-ipadic-2.7.0-20070801
./configure --with-charset=utf8 または ./configure --enable-utf8-only
make
make install

Sunday, October 14, 2007

ペーストできない入力

<input type="text" name="mailaddress2" maxlength="256" size="100" value="" onpaste="return false;" >

Thursday, May 10, 2007

Smarty MySQLとの連携方法1のちょっと改造した場合

appendからassignにSmartyの呼び出し方法を変更しましたが、結果はそれほど変わらず、Smartyの場合、Smarty文法の方が優先されるようだ。

ちょっと改造した方法

require_once( 'MySmarty.class.php');
$objSmarty =& new MySmarty;


if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}

if (!(mysql_select_db("test"))) {
die;
}

$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}

$i=0;
while ($item = mysql_fetch_array($rs)) {


$arg[]=array(
'id'=>$item['id'],
'name'=>$item['name'],
'cell'=>$item['tel'],
'email'=>$item['email'],
);

}
mysql_close($cn);

$objSmarty->assign('contacts', $arg);

$objSmarty->display('hoge1.tmpl');

Smarty MySQLとの連携方法1

Smarty MySQLとの連携方法2

PHP-HTML::Templateを使った方法

http://phphtmltemplate.sourceforge.net/のPerlのHTML::Templateライクなテンプレートの方法を紹介します。

1回目のアクセスはSmartyより早いですが、2回目以降はSmartyの方が早いです。あたり前か

--php

include("template.php");
$f1 = "templates/htmlhtml.tmpl";// テンプレートファイル
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
while ($item = mysql_fetch_array($rs)) {
$arg[]=array(
'id'=>$item['id'],
'name'=>$item['name'],
'cell'=>$item['tel'],
'email'=>$item['email'],
);
}
mysql_close($cn);
$options = array("filename"=>$f1, "debug"=>0, "die_on_bad_params"=>0);
$template =& new Template($options);
$template->AddParam('loop', $arg);
$template->EchoOutput();

---html---
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
<TMPL_LOOP NAME="loop">
<p>
<TMPL_VAR NAME="name">
<TMPL_VAR NAME="id">
<TMPL_VAR NAME="cell">
<TMPL_VAR NAME="email">
</p>
</TMPL_LOOP>
</body>
</html>

Smarty MySQLとの連携方法2

前回紹介した方法より若干速度が速い。ただしプログラム側にデータベースのカラムを追加する必要がある。

array配列を使用したSmaryのassignのサンプル sectionの場合
---php---

if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}

$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}

$id= array();
$name= array();
$tel= array();
$email= array();

while ($item = mysql_fetch_array($rs)) {
array_push($id,$item['id']);
array_push($name,$item['name']);
array_push($tel,$item['tel']);
array_push($email,$item['email']);
}

$objSmarty->assign('id',$id);
$objSmarty->assign('name',$name);
$objSmarty->assign('tel',$tel);
$objSmarty->assign('email',$email);

mysql_close($cn);
$objSmarty->display('html.tmpl');

---html----
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>

<hr />
{section name=customer loop=$id}
<p>
name: {$name[customer]}<br />
id: {$id[customer]}<br />
cell: {$tel[customer]}<br />
e-mail: {$mail[customer]}
</p>
{/section}


</body>
</html>

Smarty MySQLとの連携方法1

この方法のメリットはデータベースのカラム名はテンプレートのみに記述するのでプログラム管理が簡単になる。ただし、後から紹介する方法の方が速度は若干速い。

--PHP部分--
require_once( 'MySmarty.class.php');
$objSmarty =& new MySmarty;
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
while ($item = mysql_fetch_array($rs)) {
$objSmarty->append('contacts',$item);
}
mysql_close($cn);
$objSmarty->display('hoge1.tmpl');

---hoge1.tmpl---
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>

<hr />
{section name=customer loop=$contacts}
<p>
name: {$contacts[customer].name}
id: {$contacts[customer].id}
cell: {$contacts[customer].tel}
e-mail: {$contacts[customer].email}
</p>
{/section}


</body>
</html>

Smarty 独自ファイルクラス化

PHP5.0/7.Smartyを使う

HTMLファイルの変更がすぐに反映されないので以下を追加

<:?php
require('Smarty/Smarty.class.php');

class MySmarty extends Smarty {

function MySmarty () {

$this->Smarty();

$this->compile_check = true; //  << ここを追加

$mydir = dirname(__FILE__);
$this->template_dir = "$mydir/templates/";
$this->compile_dir = "$mydir/templates_c/";
$this->config_dir = "$mydir/configs/";
$this->cache_dir = "$mydir/cache/";

$this->caching = 0;
}
}
?>

Wednesday, May 09, 2007

apache2 mod_rewriteを後から追加(インストール)

PHPをインストール済みの場合、あとからapacheを再インストールは大変です。
*DSOでインストールされているか?を確認。されていればOK。

/usr/local/apache2/bin/httpd -lを実行

Compiled-in modules:
http_core.c
mod_so.c  これがあれば makeをしないで追加できる

*mod_rewriteをインストール
ソースをDLした場所(例)に
/home//source/httpd-2.2./modules/mappers/mod_rewrite.c
があるか確認

cd /home//source/httpd-2.2./modules/mappers/
$ /usr/local/apache2/bin/apxs -i -a -c ./mod_rewrite.c

apacheの再起動で有効

Tuesday, May 08, 2007

Ethna UTF-8化

/usr/local/lib/php/Ethna/class/Plugin/Validator/以下のPHPもUTF-8化する

smarty install by Pear

pear upgrade PEAR
pear channel-discover pearified.com
pear install pearified/Smarty


vi /usr/local/lib/php.ini
include_path = ".:/usr/local/lib/php:/usr/local/lib/php/Pearified"

/usr/local/apache2/bin/apachectl stop
/usr/local/apache2/bin/apachectl start

Sunday, April 22, 2007

Javascript クラス 継承の例

<script type=text/javascript>
<!--

function Team(name,members){
this.name = name;
this.members = members;
}

Team.prototype.add = function(members){
this.members += members;

};

function TeamAAA (name,members) {
this.name = name;
this.members = members;
}

TeamAAA.prototype = new Team();
TeamAAA.prototype.leave = function(members){
this.members -= members;

};

baseball = new TeamAAA("2軍",11);
baseball.leave(3);
document.write("Team name:"+ baseball.name + ", members:"+baseball.members);

//-->
</script>


JavaScript継承パターンまとめ

Javascript クラス コンストラクトの例

<script type=text/javascript>
<!--

function Team(name,members){
this.name = name;
this.members = members;
}

Team.prototype.add = function(members){
this.members += members;

};

football = new Team("Japan",11);
football.add(3);
document.write("Team name:"+ football.name + ", members:"+football.members);

//-->
</script>

Friday, April 20, 2007

Javascript 多次元配列のソートの例

<script type=text/javascript>
<!--

function sort1(a,b){ return a[1] - b[1] }
function sort2(a,b){ return a[2] - b[2] }

xx = new Array(3, 7, 8, 1);
xx.sort();
document.write(xx);
document.write("<br>");
var persons =
[

[ 'Tanaka' , '32' ,'Japan'] ,
[ 'John' , '38' ,'UK'] ,
[ 'Ken' , '26' ,'France'] ,
[ 'John' , '49' ,'India'] ,

]
persons.sort();

for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
document.write("<br>");
persons.sort(sort1)

for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}

document.write("<br>");
persons.sort(sort2)

for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}


//-->
</script>


意外と遅いらしい。

Thursday, April 19, 2007

Date Javascript

var date = new Date ();
date.setTime(1);
mdate = date.getFullYear() +"/" + (date.getMonth()+1) + "/" + date.getDate();

alert(mdate );

date.getDay // 0から始まる曜日を返す。0は日曜日、6が土曜日

Wednesday, April 18, 2007

無名配列 Anonymous Arrayの例 Javascript

var persons = [
{ Name: "田中", Age: 20 },
{ Name: "山田", Age: 18 },
{ Name: "青木", Age: 15 }
];

for (var i = 0; i < persons.length; i ++) {
   alert(persons[i].Name + ":" +persons[i].Age);
}

連想配列のサンプル JavaScript

連想配列のサンプル

person1 = new Array();
person1["Name"] = "Mike";
document.write(person1["Name"] );

eval

Javascript 半角文字列を数値に
PHP 文字列を PHP コードとして評価する
Perl 例外処理機構として機能する

Thursday, April 12, 2007

切り上げ

use strict;
use POSIX;
print ceil(0.3), "\n";

Wednesday, April 11, 2007

template-toolkit で日本語

CPANモジュールのTemplate::Plugin::Jcodeを使う

Tuesday, April 10, 2007

Exporter

package Constant;
use strict;
BEGIN{
use Exporter;
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

@ISA = qw(Exporter);
@EXPORT = qw(
HOGE
HOGE2
);
%EXPORT_TAGS = ();
@EXPORT_OK = ();
}

use constant HOGE => 'hoge';
use constant HOGE2 => 2;

1
~
-----

#!/usr/local/bin/perl

use Constant;

print HOGE2;

ENDサブルーチン Perl

exitやdieで終了したあとで呼ばれる。
ただし「exec」、「kill -9」または異常終了などがあると呼ばれない。
複数ある場合は文の最後から呼ばれる。


exit;

END{
print "end1\n";
}

END{
print "end2\n";

}

END{
print "end3\n";

}

----- 結果 ----

end3
end2
end1
となる

日付関係

use POSIX 'strftime';

print strftime ("%Y/%m/%d %H:%M:%S", localtime);

参考URL

http://blog.livedoor.jp/dankogai/archives/50180654.html
http://www2u.biglobe.ne.jp/~MAS/perl/waza/strftime.html

ps コマンドで特定のユーザを調べる

ps -u hoge

hogeさんの情報を表示

シグナルを無視

Perl

$SIG{'INT'} = 'IGNORE';

Ctrl+cを無視します。

Friday, April 06, 2007

ダウンロードコンテンツの著作権関連のサンプル

Content-Type: application/vnd.oma.dd+xml
Content-length: 50


image/jpg
http://myserver/dl.cgi?img=picture.jpg
1234


著作権関連のOMAのサンプル

ファイルサイズを求める -s

perlでのサンプル

my $body;

open(MP3, $file) || die("can't open \n $!");
read(MP3, $body, -s $file);
close(MP3);
print $body;

正規表現の例 perl

my $n = 5;
unless ($n =~ /^[1-5]$/) {
print "n is not from one to five";
}else{
print "n is between one and five";
}

Yahoo!ケイタイの動画、転送不可のHTTPヘッダのサンプル

Yahoo!ケイタイの動画、転送不可のHTTPヘッダのサンプル
Content-type: video/3gpp\nContent-length: 100\nx-jphone-copyright: no-store\n\n

サイズ Content-lengthは
-s で求めたりする。

http://developers.softbankmobile.co.jp/dp/tool_dl/web/tech.php
を参照。

Thursday, April 05, 2007

Perl テストプランツールのサンプル

テストプランツールのサンプル

#!/usr/local/bin/perl -w
use strict;
use Data::Dumper;
use Test::More qw(no_plan);

use lib './lib';

BEGIN {
use_ok('Original::Person');# パールモジュール
};

my $p = Original::Person->new('Tom');

is ($p->tel,'0123-123-1234', 'tel number');
is ($p->age,'24', 'age');

prototype.js を使ったチャットシステムの習作

ログファイルのロックやサイズ制限などは入れていないです。

単純にprototype.js の練習用です。

<html>
<head>
<script type="text/javascript" src="./js/prototype-1.5.0.js"></script>
<script type="text/javascript">
//<![CDATA[

function updateResult(req){
$("status").innerHTML = req.responseText ;
}


function update() {
var url = './read.pl';
var params = '';
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params,
onComplete: updateResult
});
}

function execute() {
var url = './write.pl';
var params = Form.serialize($('form1'));
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params
});
}

function adListener() {
periodicalExecuter = new PeriodicalExecuter(update, 1);
}

//]]>
</script>
</head>
<body onload="adListener()">
<form id="form1" onSubmit="execute()">
message <input type="text" name="message" id="d_message" value=""><br>
<input type="submit" value="entry">
</form>
<hr>
<span id="status"></span>
</body>
</html>

-----write.pl

#!/usr/bin/perl -w

# モジュール読み込み
use strict;
use CGI;

print 'Content-Type: text/html', "\n\n";

#オブジェクト作成
my $q = CGI->new;
my $message = $q->param('message');

if ($message){
# ファイルロック処理は入れていない
open(OUTFILE, ">> /tmp/mes.txt");
print OUTFILE $message."\n";
close OUTFILE;
print $message;
}

----read.pl----

#!/usr/bin/perl -w

# モジュール読み込み
use strict;

print 'Content-Type: text/html', "\n\n";

my $file = '/tmp/mes.txt';
if ( -e $file) {
open( READ, $file );
my @lines = <READ>;
close( READ );
my $num = @lines;
my @lists = @lines[$num-5 .. $num-1];# 最後からデータを取得
foreach (@lists) {
print $_,"<br>";
}


}

Wednesday, April 04, 2007

prototype.js のサンプル

----time.pl----

#!/usr/bin/perl

use strict;

print 'Content-Type: text/html', "\n\n";
my ($ss, $mn, $hh, $dd, $mm, $yy) = localtime(time);
$yy += 1900;
$mm++;
my $my_time = sprintf("%04d.%02d.%02d %02d:%02d:%02d", $yy, $mm, $dd, $hh, $mn, $ss);

print $my_time;

---end---

<html>
<head>
<script type="text/javascript" src="./js/prototype-1.5.0.js"></script>
<script type="text/javascript">
//<![CDATA[

function updateResult(req){
$("status").innerHTML = req.responseText ;


}

function update() {
var url = './time.pl';
var params = 'c=time';// つかわないが。。
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params,
onComplete: updateResult
});
}

function adListener() {
periodicalExecuter = new PeriodicalExecuter(update, 1);
}

//]]>
</script>
</head>
<body onload="adListener()">
time :
<span id="status"></span>

</body>
</html>