PHP

PHPのmb_encode_mimeheader()で文字化けを回避する。

mb_encode_mimeheader()で文字列を変換する際は、事前にmb_internal_encoding()にてエンコードを統一しておかなければならない。

ということで以下のような処理が必要になる。

※メール送信クラスより引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected function mem($var) {
    // 関数の存在チェック
    $internalEncoding = function_exists('mb_internal_encoding');
    if($internalEncoding) {
        // 現在のエンコード設定を保存
        $restore = mb_internal_encoding();
        // 変換したい文字エンコードを設定
        mb_internal_encoding('UTF-8');
    }
    // 文字列を変換
    $return = mb_encode_mimeheader($var, 'UTF-8', 'B');
    // 処理後、変更していた文字コードを戻す
    if($internalEncoding) mb_internal_encoding($restore);
    // 値を返却
    return $return;
}

mb_encode_mimeheader()第3引数の’B’は「Base64」エンコードという意味。
‘Q’を指定すると「Quoted-Printable」になる。
デフォルトは’B’。

まぁ実際、関数の存在チェックまではやらなくてもいいと思う(適当)。

PHPでファイルパスからファイル名を取得する。

最後のDS以降のファイル名がサクっとほしい時に使用。

例。

1
2
3
4
$path = '/home/admin/../../targetFile.php';
echo basename($path);
targetFile.php

ちなみに以下の記述で自分のファイル名が得られる。

1
2
3
echo basename(__FILE__);
targetFile.php

まぁ当然なんだけども。

PHPにて相対パスを絶対パスに変換する。

めも。

例えば以下のような感じ。

1
2
3
4
$path = '../../path/to/file.ext'
echo realpath($path);
/home/admin/...../path/to/file.ext

自分用メール送信クラスに添付ファイル送信機能をつけた。

以前の記事←で作成したメール送信クラスに添付ファイル送信機能をつけてみた。

使える全メソッドは下部で解説。
簡単な使い方は関数上部のコメントアウトを参照されたし。

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
<?php
/**
 * sendmailを用いたシンプルなメール送信用クラス
 * 単純に送信したい場合は以下の通り
 * ※to, cc, bcc, のいずれか一つの指定は必須
 *
 * $mail = new simpleMailTransmission();
 *     
 * $res = $mail
 * ->to('to@local.host') // 必要に応じて
 * ->cc('cc@local.host') // 必要に応じて
 * ->Bcc('bcc@local.host') // 必要に応じて
 * ->attachments('/path/to/file.ext') // 添付ファイル設定
 * ->from('from@local.host') // 必須
 * ->subject('タイトルを指定')
 * ->send('本文を指定');
 *
 * ※添付ファイルの詳細設定は、attachments()関数上部のコメントアウトを参照
 *
 */
class simpleMailTransmission {
     
    // 送信先
    protected $to = array();
     
    // メールタイトル
    protected $subject = '';
     
    // メール本文
    protected $message = '';
     
    // ヘッダー情報
    protected $header = '';
     
    // 送信先一時格納変数(複数可)
    protected $_to = array();
     
    // 送信元設定
    protected $_from = array();
     
    // Cc格納変数
    protected $_cc = array();
 
    // Bcc格納変数
    protected $_bcc = array();
 
    // ヘッダー情報一時格納変数
    protected $_header = '';
     
    // テンプレートファイルパス
    protected $_template = '';
     
    // テンプレートに渡す変数
    protected $_viewVars = array();
     
    // 添付ファイル
    protected $_attachments = array();
 
    // 添付ファイル送信用バウンダリヘッダ
    protected $_boundary = null;
     
    // 言語設定
    protected $_lang = 'ja';
     
    // エンコーディング
    protected $_encoding = 'UTF-8';
     
    // キャラセット
    protected $_charset = 'ISO-2022-JP';
     
    // 送信時文字エンコード
    protected $_transferEncoding = '7bit';
     
    // 送信ヘッダー内「X-Mailer」設定
    protected $_xMailer = 'GEKIOKOPUNPUNMARU';
     
    /**
     * 送信先のセット
     * @param unknown_type $email
     * @param unknown_type $name
     * @return multitype:|mailTerminal
     */
    public function to($email = null, $name = null) {
        if($email === null) {
            return $this->_to;
        }
        return $this->_setEmail('_to', $email, $name);
    }
     
    /**
     * 送信先の追加
     * @param unknown_type $email
     * @param unknown_type $name
     * @return mailTerminal
     */
    public function addTo($email, $name = null) {
        return $this->_addEmail('_to', $email, $name);
    }
 
    /**
     * Ccのセット
     * @param unknown_type $email
     * @param unknown_type $name
     * @return multitype:|mailTerminal
     */
    public function cc($email = null, $name = null) {
        if($email === null) {
            return $this->_cc;
        }
        return $this->_setEmail('_cc', $email, $name);
    }
     
    /**
     * Ccの追加
     * @param unknown_type $email
     * @param unknown_type $name
     * @return mailTerminal
     */
    public function addCc($email, $name = null) {
        return $this->_addEmail('_cc', $email, $name);
    }
     
    /**
     * Bccのセット
     * @param unknown_type $email
     * @param unknown_type $name
     * @return multitype:|mailTerminal
     */
    public function bcc($email = null, $name = null) {
        if($email === null) {
            return $this->_bcc;
        }
        return $this->_setEmail('_bcc', $email, $name);
    }
     
    /**
     * Bccの追加
     * @param unknown_type $email
     * @param unknown_type $name
     * @return mailTerminal
     */
    public function addBcc($email, $name = null) {
        return $this->_addEmail('_bcc', $email, $name);
    }
     
    /**
     * セット用メソッド(配列可)
     * @param unknown_type $varName
     * @param unknown_type $email
     * @param unknown_type $name
     * @return mailTerminal
     */
    protected function _setEmail($varName, $email, $name) {
        if(is_array($email)) {
            $list = array();
            foreach($email as $key => $value) {
                if(is_int($key)) {
                    $key = $value;
                }
                if(self::email($key)) {
                    $list[$key] = $value;
                }
            }
            $this->{$varName} = $list;
            return $this;
        }
        if(self::email($email)) {
            if($name === null) {
                $name = $email;
            }
            $this->{$varName} = array($email => $name);
        }
        return $this;
    }
     
    /**
     * 追加用メソッド(配列可)
     * @param unknown_type $varName
     * @param unknown_type $email
     * @param unknown_type $name
     * @return mailTerminal
     */
    protected function _addEmail($varName, $email, $name) {
        if(is_array($email)) {
            $list = array();
            foreach($email as $key => $value) {
                if(is_int($key)) {
                    $key = $value;
                }
                if(self::email($key)) {
                    $list[$key] = $value;
                }
            }
            $this->{$varName} = array_merge($this->{$varName}, $list);
            return $this;
        }
        if(self::email($email)) {
            if($name === null) {
                $name = $email;
            }
            $this->{$varName}[$email] = $name;
        }
        return $this;
    }
     
    /**
     * 送信元の設定
     * @param unknown_type $email
     * @param unknown_type $name
     * @return multitype:|mailTerminal
     */
    public function from($email = null, $name = null) {
        if($email === null) {
            return $this->_from;
        }
        return $this->_setEmailSingle('_from', $email, $name);
    }
     
    /**
     * 単一の値であることを保障するためのセット関数
     * @param unknown_type $varName
     * @param unknown_type $email
     * @param unknown_type $name
     * @return mailTerminal
     */
    protected function _setEmailSingle($varName, $email, $name) {
        $current = $this->{$varName};
        $this->_setEmail($varName, $email, $name);
        if(count($this->{$varName}) !== 1) {
            $this->{$varName} = $current;
        }
        return $this;
    }
     
    /**
     * メールタイトルのセット
     * @param unknown_type $subject
     * @return string|mailTerminal
     */
    public function subject($subject = null) {
        if($subject === null) {
            return $this->subject;
        }
        $this->subject = (string)$subject;
        return $this;
    }
     
    /**
     * テンプレートファイルパスの指定
     * @param unknown_type $template
     * @return string|mailTerminal
     */
    public function template($template = false) {
        if($template === false) {
            return $this->_template;
        }
        $this->_template = $template;
        return $this;
    }
     
    /**
     * テンプレートファイルに渡す変数を設定
     * @param unknown_type $viewVars
     * @return multitype:|mailTerminal
     */
    public function viewVars($viewVars = null) {
        if($viewVars === null) {
            return $this->_viewVars;
        }
        $this->_viewVars = array_merge($this->_viewVars, (array)$viewVars);
        return $this;
    }
     
    /**
     * 添付ファイルの設定
     *
     * $mail->attachments('/path/to/file.ext');
     *
     * $mail->attachments(array('customName.ext' => '/path/to/file.ext'));
     *
     * $mail->attachments(array('customName.ext' => array(
     *      'file' => '/path/to/file.ext',
     *      'mimetype' => 'image/jpg',
     *      'contentId' => 'qwerty',
     *      'contentDisposition' => false
     * ));
     *
     */
    public function attachments($attachments = null) {
        if($attachments === null) {
            return $this->_attachments;
        }
        $attach = array();
        foreach((array)$attachments as $name => $fileInfo) {
            if(!is_array($fileInfo)) {
                $fileInfo = array('file' => $fileInfo);
            }
            if(empty($fileInfo['file'])) {
                return 'File not specified.';
            }
            $fileInfo['file'] = realpath($fileInfo['file']);
            if($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
                return 'File not found.';
            }
            if(is_int($name)) {
                $name = basename($fileInfo['file']);
            }
            if(!isset($fileInfo['mimetype'])) {
                $fileInfo['mimetype'] = 'application/octet-stream';
            }
            $attach[$name] = $fileInfo;
        }
        $this->_attachments = $attach;
        return $this;
    }
     
    /**
     * 添付ファイルの追加
     * @param unknown_type $attachments
     * @return simpleMailTransmission
     */
    public function addAttachments($attachments) {
        $current = $this->_attachments;
        $this->attachments($attachments);
        $this->_attachments = array_merge($current, $this->_attachments);
        return $this;
    }
     
    /**
     * ヘッダーバウンダリの生成
     * ※要添付ファイル
     */
    protected function _createBoundary() {
        if (!empty($this->_attachments)) {
            $this->_boundary = md5(uniqid(time()));
        }
    }
     
    /**
     * 添付ファイルがある場合、
     * メッセージにバウンダリーを挿入
     * @return string
     */
    protected function _addBoundaries() {
 
        $this->_createBoundary();
        $msg = '';
     
        $contentIds = array_filter((array)self::_extract($this->_attachments, '{s}.contentId'));
        $hasInlineAttachments = count($contentIds) > 0;
        $hasAttachments = !empty($this->_attachments);
         
        $boundary = $relBoundary = $textBoundary = $this->_boundary;
     
        if ($hasInlineAttachments) {
            $msg .= '--'.$boundary."\n";
            $msg .= 'Content-Type: multipart/related; boundary="rel-'.$boundary.'"'."\n\n";
            $relBoundary = $textBoundary = 'rel-'.$boundary;
        }
        if (isset($this->message)) {
            if ($textBoundary !== $boundary || $hasAttachments) {
                $msg .= '--'.$textBoundary."\n";
                $msg .= 'Content-Type: text/plain; charset='.$this->_charset."\n";
                $msg .= 'Content-Transfer-Encoding: '.$this->_transferEncoding."\n\n";
            }
            $msg .= $this->message."\n\n";
        }
        if ($hasInlineAttachments) {
            $attachments = $this->_attachInlineFiles($relBoundary);
            $msg .= $attachments."\n";
            $msg .= '--'.$relBoundary.'--'."\n\n";
        }
        if ($hasAttachments) {
            $attachments = $this->_attachFiles($boundary);
            $msg .= $attachments."\n";
        }
        if($hasAttachments) {
            $msg .= '--'.$boundary.'--'."\n\n";
        }
        return $msg;
    }
     
    /**
     * コンテンツIDを持つ添付ファイルの追加
     * @param unknown_type $boundary
     * @return multitype:string unknown
     */
    protected function _attachInlineFiles($boundary) {
        $msg = '';
        foreach($this->_attachments as $filename => $fileInfo) {
            if(empty($fileInfo['contentId'])) continue;
            $data = $this->_readFile($fileInfo['file']);
            $msg .= '--'.$boundary."\n";
            $msg .= 'Content-Type: '.$fileInfo['mimetype']."\n";
            $msg .= 'Content-Transfer-Encoding: base64'."\n";
            $msg .= 'Content-ID: <'.$fileInfo['contentId'].'>'."\n";
            $msg .= 'Content-Disposition: inline; filename="'.$filename.'"'."\n\n";
            $msg .= $data."\n\n";
        }
        return $msg;
    }
     
    /**
     * コンテンツIDを持たない添付ファイルの追加
     * @param unknown_type $boundary
     * @return multitype:string
     */
    protected function _attachFiles($boundary) {
        $msg = '';
        foreach($this->_attachments as $filename => $fileInfo) {
            if (!empty($fileInfo['contentId'])) continue;
            $data = $this->_readFile($fileInfo['file']);
     
            $msg .= '--'.$boundary."\n";
            $msg .= 'Content-Type: '.$fileInfo['mimetype']."\n";
            $msg .= 'Content-Transfer-Encoding: base64'."\n";
            if (!isset($fileInfo['contentDisposition']) || $fileInfo['contentDisposition']) {
                $msg .= 'Content-Disposition: attachment; filename="'.$filename.'"'."\n\n";
            }
            $msg .= $data."\n\n";
        }
        return $msg;
    }
     
    /**
     * 添付するファイルの読み込み(エンコード)
     * @param unknown_type $path
     * @return string
     */
    protected function _readFile($path) {
        return chunk_split(base64_encode(file_get_contents($path)));
    }
     
    /**
     * メールアドレスのバリデーション設定
     * @param unknown_type $check
     * @return boolean
     */
    protected function email($check) {
        $hostName = '(?:[_a-z0-9][-_a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,})';
        $regex = '/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@'.$hostName.'$/i';
        return self::_check($check, $regex);
    }
     
    /**
     * メールの送信開始トリガー
     * @param unknown_type $plainMessage
     * @return string|Ambigous <boolean, multitype:boolean >
     */
    public function send($plainMessage = null) {
        if(empty($this->_from)) {
            return 'From is not specified.';
        }
        if(empty($this->_to) && empty($this->_cc) && empty($this->_bcc)) {
            return 'You need to specify at least one destination for to, cc or bcc.';
        }
        if(!file_exists($this->_template)) {
            $this->message = self::mce($plainMessage);
        } else {
            $this->message = self::mce($this->createMessage());
        }
        if(!empty($this->_attachments)) $this->message = $this->_addBoundaries();
         
        $this->header = $this->createHeader();
        $this->to = $this->createTo();
 
        return self::_send();
    }
     
    /**
     * 送信処理
     * @return boolean|multitype:boolean
     */
    protected function _send() {
        mb_language($this->_lang);
        mb_internal_encoding($this->_encoding);
         
        if(!empty($this->_attachments)) return self::_sendWithAttachments();
         
        if(empty($this->to)) {
            return mb_send_mail(null, $this->subject, $this->message, $this->header);
        } else {
            $_errors = array();
            foreach($this->to as $to) {
                if(!mb_send_mail($to, $this->subject, $this->message, $this->header)) $_errors[$to] = false;
            }
            if(empty($_errors)) return true;
            return $_errors;
        }
    }
     
    protected function _sendWithAttachments() {
        $this->message = str_replace("\n", "\r\n", $this->message);
        $this->header = str_replace("\n", "\r\n", $this->header);
        if(empty($this->to)) {
            return mail(null, self::mem($this->subject), $this->message, $this->header);
        } else {
            $_errors = array();
            foreach($this->to as $to) {
                if(!mail($to, self::mem($this->subject), $this->message, $this->header)) $_errors[$to] = false;
            }
            if(empty($_errors)) return true;
            return $_errors;
        }
    }
     
    /**
     * 追加ヘッダーの生成
     * @return string
     */
    protected function createHeader() {
        foreach($this->_from as $email => $name) $this->_header .= 'From: '.self::mem($name).' <'.$email.'>'."\n";
        if(!empty($this->_cc)) {
            $this->_header .= 'Cc: ';
            foreach($this->_cc as $email => $name) {
                $this->_header .= self::mem($name).' <'.$email.'>'.",";
            }
            $this->_header = self::trimLastChar($this->_header)."\n";
        }
        if(!empty($this->_bcc)) {
            $this->_header .= 'Bcc: ';
            foreach($this->_bcc as $email => $name) {
                $this->_header .= self::mem($name).' <'.$email.'>'.",";
            }
            $this->_header = self::trimLastChar($this->_header)."\n";
        }
        $this->_header .= 'X-Mailer: '.$this->_xMailer."\n";
        if(!empty($this->_attachments)) {
            $this->_header .= 'MIME-Version: 1.0'."\n";
            $this->_header .= 'Content-Type: multipart/mixed; boundary='.$this->_boundary."\n";
            $this->_header .= 'Content-Transfer-Encoding: '.$this->_transferEncoding."\n";
        }
        return $this->_header;
    }
     
    /**
     * 送信先ヘッダーの生成
     * @return multitype:string
     */
    protected function createTo() {
        $t = array();
        if(!empty($this->_to)) {
            foreach($this->_to as $email => $name) {
                $t[] = self::mem($name).' <'.$email.'>';
            }
        }
        return $t;
    }
     
    /**
     * テンプレートより本文の生成
     * @return Ambigous <string, mixed>
     */
    protected function createMessage() {
        $b = '';
        $tmp = file_get_contents($this->_template);
        if($tmp) {
            $varArray = array();
            if(!empty($this->_viewVars)) {
                foreach($this->_viewVars as $varName => $value) $varArray['{%'.$varName.'%}'] = $value;
            }
            $b = str_replace(array_keys($varArray) ,array_values($varArray), $tmp);
        }
        return $b;
    }
     
    /**
     * バリデーションの実行
     * @param unknown_type $check
     * @param unknown_type $regex
     * @return boolean
     */
    protected function _check($check, $regex) {
        if(preg_match($regex, $check)) return true;
        return false;
    }
     
    protected function mem($var) {
        $internalEncoding = function_exists('mb_internal_encoding');
        if($internalEncoding) {
            $restore = mb_internal_encoding();
            mb_internal_encoding($this->_encoding);
        }
        $return = mb_encode_mimeheader($var, $this->_encoding, 'B');
        if($internalEncoding) mb_internal_encoding($restore);
        return $return;
    }
     
    protected function mce($var) {
        return mb_convert_encoding($var, $this->_charset);
    }
     
    protected function trimLastChar($var) {
        return substr($var, 0, -1);
    }
     
    /**
     * 配列の中から指定した文字列を抽出する
     *
     * - `{n}` Matches any numeric key, or integer.
     * - `{s}` Matches any string key.
     *
     * @param array $data
     * @param unknown_type $path
     * @return multitype:|array|Ambigous <multitype:multitype: , multitype:unknown >
     */
    protected function _extract(array $data, $path) {
        if(empty($path) || !preg_match('/[{]/', $path)) return $data;
        $tokens = explode('.', $path);
        $_key = '__set_item__';
        $context = array($_key => array($data));
        foreach($tokens as $token) {
            $next = array();
            foreach($context[$_key] as $item) {
                foreach((array)$item as $k => $v) { 
                    if(self::_matchToken($k, $token)) {
                        $next[] = $v;
                    }
                }
            }  
            $context = array($_key => $next);
        }
        return $context[$_key];
    }
     
    /**
     * トークンに対するキーチェック
     * @param unknown_type $key
     * @param unknown_type $token
     * @return boolean
     */
    protected function _matchToken($key, $token) {
        if($token === '{n}') return is_numeric($key);
        if($token === '{s}') return is_string($key);
        return ($key === $token);
    }
}

用意した全メソッドの使い方は以下の通り。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$mail = new simpleMailTransmission();
$res = $mail
->to('to@local.host')
->addTo('addTo@local.host')
->addTo('addTo2@local.host')
->cc('cc@local.host')
->addCc('addCc@local.host')
->addCc('addCc2@local.host')
->bcc('bcc@local.host')
->addBcc('addBcc@local.host')
->addBcc('addBcc2@local.host')
->from('from@local.host')
->subject('mailSubjectHere.')
->template('/path/to/template.ext')
->viewVars($params)
->attachments('/path/to/file1.ext')
->addAttachments('/path/to/file2.ext')
->addAttachments('/path/to/file3.ext')
->send();
 
var_dump($res);

複数のTo、Cc、Bcc、添付ファイルの送信に対応。
テンプレートの文法、変数の渡し方は前回の記事を参照されたし。

PHPのmail()関数とmb_send_mail()関数の違い。

メモ。

■mb_send_mail()

自動でヘッダーに以下を追加してくれる。

1
2
3
MIME-Version: 1.0
Content-Type: text/plain; charset=ISO-2022-JP
Content-Transfer-Encoding: 7bit

また、mb_language()の設定に基づき、第1引数から第3引数までを自動でエンコードしてくれる。
mb_languag(‘ja’)ならiso-2022-jp、mb_languag(‘uni’)ならutf-8へ変換。
ヘッダーに関してはmb_encode_mimeheader()してくれるという至れり尽くせりっぷり。

■mail()

全部自分でやれや。

 

 

 

 

 

 

( ゚д゚ )

 

 

こっちみn(ry

 

 

 

まぁ添付ファイルを送りたい際はヘッダーがplainだと問題あるのでmail()使うしかないんですけどね。

PHP、file_exists()のおさらい。

file_exists ? ファイルまたはディレクトリが存在するかどうか調べる。

 

ファイルまたはディレクトリが存在するかどうか調べる。

 

ファイルまたはディレクトリが存在するかどうか調べる。

 

ファイルまたはディレクトリが存在するかどうか調べる。

 

関数名に騙されないこと!!!
十分注意されたし!!!

 

PHPで行うスマートな文字列置換方法の考察。

テンプレートファイルなんかの文字列をスマートに置換する案のメモ。

1, 配列のキーに置換対象の文字列を、バリューに置換する文字列をセットする。

2, テンプレート読み込み

3, array_keys()、array_values()、str_replace()を使い一気に置換。

例えば以下のような感じ。

■テンプレート側

1
2
3
1個目:{%foo%}
2個目:{%bar%}
3個目:{%baz%}

■PHP側

1
2
3
4
5
6
7
8
9
10
11
12
13
$template = file_get_contents('/path/to/template.ext');
 
$vars = array(
    'foo' => 'hoge',
    'bar' => 'fuga',
    'baz' => 'piyo'
);
 
foreach($vars as $varName => $value) $varArray['{%'.$varName.'%}'] = $value;
 
$str = str_replace(array_keys($varArray) ,array_values($varArray) , $template);
 
var_dump($str);

いかがなものか。

PHPにて配列を変数に変換する方法。

extract()関数を用いると配列のKeyを変数名に、値をValueとして変換してくれる。
フレームワークなどでよく用いられる。

以下使用例。

1
2
3
4
5
6
7
8
9
10
11
12
13
$array = array(
    'foo' => 'hoge',
    'bar' => 'fuga',
    'baz' => 'piyo'
);
 
extract($array);
 
var_dump($foo);
var_dump($bar);
var_dump($baz);
string(4) "hoge" string(4) "fuga" string(4) "piyo"

変換した変数がすでに定義されていた場合も、変換後の値で上書きされるので注意。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$foo = 'GEKIOKO_PUNPUN_MARU';
 
$array = array(
    'foo' => 'hoge',
    'bar' => 'fuga',
    'baz' => 'piyo'
);
 
// 第2引数の「EXTR_OVERWRITE」は明示的に上書きモードで固定するためのもの。
// 指定しなければ通常このモードで動作する(模様)。
extract($array, EXTR_OVERWRITE);
 
var_dump($foo);
var_dump($bar);
var_dump($baz);
string(4) "hoge" string(4) "fuga" string(4) "piyo"

変数の上書きを許可したくない場合は、第2引数へ「EXTR_SKIP」を渡せばよい。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$foo = 'GEKIOKO_PUNPUN_MARU';
$bar = '';
 
$array = array(
    'foo' => 'hoge',
    'bar' => 'fuga'
);
 
extract($array, EXTR_SKIP);
 
var_dump($foo);
var_dump($bar);
string(19) "GEKIOKO_PUNPUN_MARU" string(0) ""

「EXTR_PREFIX_SAME」を渡すと、変数の衝突が起きた際、第3引数に指定した値をプレフィックスとして先頭に追加してくれる。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$foo = 'GEKIOKO_PUNPUN_MARU';
$bar = '';
 
$array = array(
    'foo' => 'hoge',
    'bar' => 'fuga'
);
 
extract($array, EXTR_PREFIX_SAME, 'pre');
 
var_dump($foo);
var_dump($bar);
// [prefix] + [_] + [key]、というように連結される
var_dump($pre_foo);
var_dump($pre_bar);
string(19) "GEKIOKO_PUNPUN_MARU" string(0) "" string(4) "hoge" string(4) "fuga"

「EXTR_PREFIX_ALL」を渡すと、衝突の有無に関わらず全てがプレフィックス付きの変数となる。

1
2
3
4
5
6
7
8
9
10
11
$array = array(
    'foo' => 'hoge',
    'bar' => 'fuga'
);
 
extract($array, EXTR_PREFIX_ALL , 'pre');
 
var_dump($pre_foo);
var_dump($pre_bar);
string(4) "hoge" string(4) "fuga"