顯示具有 程式-php 標籤的文章。 顯示所有文章
顯示具有 程式-php 標籤的文章。 顯示所有文章

2016年9月6日 星期二

預設日期+2日 (避開六日) (PHP & DB 作法)


需求: 預設日期為「核准日」+2 (避開週六日) , 這邊提供兩種做法參考: 

PHP Solution1:
// Reference PHP Official Site URL: http://php.net/manual/en/function.date.php 
// date function format about the N , 1 (for Monday) through 7 (for Sunday)
// This function will add working day to a given timestamp
function addworkinday($timestamp,$daystoadd){
    
     
$dayoftheweek date("N",$timestamp);
     
$sum =$dayoftheweek +$daystoadd;
    
while (
$sum >= 6) {
    
     
$daystoadd=$daystoadd+1;
    
$sum=$sum-1;
}
return 
$timestamp +(60*60*24*$daystoadd);

}
?>


My SQL DB Solution1:
Describe: 
        Try to use the WEEKDAY() funtion
        Return the weekday index for date  (0 = Monday, 1 = Tuesday, … 6 = Sunday)

直接查閱出特定日期的 day of week ex: 

Mode
First day of week
Range
Week 1 is the first week …
0
Sunday
0-53
with a Sunday in this year
1
Monday
0-53
with 4 or more days this year
2
Sunday
1-53
with a Sunday in this year
3
Monday
1-53
with 4 or more days this year
4
Sunday
0-53
with 4 or more days this year
5
Monday
0-53
with a Monday in this year
6
Sunday
1-53
with 4 or more days this year
7
Monday
1-53
with a Monday in this year

Example: 
mysql> SELECT WEEK('2008-02-20');
        -> 7
mysql> SELECT WEEK('2008-02-20',0);
        -> 7
mysql> SELECT WEEK('2008-02-20',1);
        -> 8
mysql> SELECT WEEK('2008-12-31',1);
        -> 53



Best Regards & thanks. 
George Huang 烤蕃薯 2016

2016年8月2日 星期二

[PHP] ftp_connect() FTP 連線&上傳範例

Solution1: 
Reference URL特別注意 ftp_put上傳兩個變數別弄錯, 說明如下: 
$remote_file
The remote file path. 是目的地端, 也是FTP端的目錄Path. 
$local_file
The local file path. 是程式執行端的本地端,來源檔. 
mode
The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

程式範例-Start
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
程式範例-End

Solution2: 

    /*
    $ftp_server = "ftp.*****.com";
    $ftp_user = "******";
    $ftp_password = "*****";
    */

    $ftp_server = "ftp.gnu.org";
    $ftp_user = "anonymous";
    $ftp_password = "none";


    /* connect */
    $ftp_connection = @ftp_connect($ftp_server);
    if (!$ftp_connection) die('could not connect.');

    /* login */
    $ftp_login = @ftp_login($ftp_connection, $ftp_user, $ftp_password);
    if (!$ftp_login) die('could not login.');

    /* enter passive mode */
    $ftp_passive = @ftp_pasv($ftp_connection, true);
    if (!$ftp_passive) die('could not enable passive mode.');

    /* get listing */
    $ftp_listing = ftp_nlist($ftp_connection, "."); 
    foreach ($ftp_listing as $file){
        echo "
".$file."
";
    }

    ftp_close($ftp_connection);

Solution3: 
function getFtpConnection($uri)
{
    
// Split FTP URI into:
    // $match[0] = ftp://username:password@sld.domain.tld/path1/path2/
    // $match[1] = username
    // $match[2] = password
    // $match[3] = sld.domain.tld
    // $match[4] = /path1/path2/
    
preg_match("/ftp:\/\/(.*?):(.*?)@(.*?)(\/.*)/i"$uri$match);

    
// Set up a connection
    
$conn ftp_connect($match[3]);

    
// Login
    
if (ftp_login($conn$match[1], $match[2]))
    {
        
// Change the dir
        
ftp_chdir($conn$match[4]);

        
// Return the resource
        
return $conn;
    }

    
// Or retun null
    
return null;
}



Solution4: 

$Ftp_host='000.000.000.000';
$Ftp_port=21;
$Ftp_user='xxxxxx';
$Ftp_pass='aaaaaa';
$Ftp_dir='';
$ftp_link=ftp_connect($Ftp_host,$Ftp_port) or die("No Link");
$login = ftp_login($ftp_link ,$Ftp_user,$Ftp_pass);
ftp_pasv($ftp_link,true);

$alist = ftp_nlist ($ftp_link, "out"); //list out/ 內的所有檔案
while(list($l,$r)=each($alist)){
echo $l.','.$r; //$l=資料序0,1,2... , $r=檔名 out/aaa.xxx
}
@ftp_put($ftp_link, $putFile, $file_Name, FTP_BINARY);    //上傳 $putFile=目地, $file_Name=來源
@ftp_get($ftp_link, $File_Name, $r, FTP_BINARY)    //取回 $File_Name=目地, $r=來源
ftp_delete ($ftp_link,$r); //刪除檔案


Solution5:
// Download a file and store the data in $data
$data = file_get_contents('ftp://username:password@ftp.domain.tld/somefile.txt');

// Loop the contents of the root directory
$dp = opendir('ftp://username:password@ftp.domain.tld/');
while ($file = readdir($dp)) {
  // Do stuff
}
closedir($dp);

// Upload a file
file_put_contents('ftp://username:password@ftp.domain.tld/somefile.txt','This is the file data');

// Upload a file from the local file system
$local = fopen('/path/to/my/file.ext','r');
$remote = fopen('ftp://username:password@ftp.domain.tld/somefile.txt','w');
stream_copy_to_stream($local,$remote);

Other Note: Ref URL.
#1 如需要PHP Create Folder 可以參考如下:
if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}
#2 FTP Create Folder. Ref URL.
// try to create the directory $dirif (ftp_mkdir($conn_id$dir)) {
 echo 
"successfully created $dir\n";
} else {
 echo 
"There was a problem while creating $dir\n";
}


#3,// 確認目前位置
echo "Current directory: " . ftp_pwd($conn_id) . "\n";



Reference:
1. 介紹 ftp-connect
http://php.net/manual/en/function.ftp-connect.php
2. 介紹ftp-login
http://php.net/manual/en/function.ftp-login.php
3. 介紹 PHP ftp_nlist 函式
http://www.w3school.com.cn/php/func_ftp_nlist.asp
4. Nice solution example. (Same the solution1 )
http://stackoverflow.com/questions/8302460/ftp-login-not-authorizing-through-php-methods
5. PHP Create Folder
http://stackoverflow.com/questions/2303372/create-a-folder-if-it-doesnt-already-exist
6. How To Copy Files Around FTP Using PHP
http://stackoverflow.com/questions/4853269/how-to-copy-files-around-ftp-using-php




2016年6月2日 星期四

strtotime做日期及時間加減計算-[php]

strtotime做日期及時間加減計算-[php] 

範例1:
$today = '2016-06-02';
//年
echo date("Y-m-d", strtotime($today."+3 year"));
//月
echo date("Y-m-d", strtotime($today."-1 month"));
//週
echo date("Y-m-d", strtotime($today."+10 week"));
//日
echo date("Y-m-d", strtotime($today."+10 day"));
//時
echo date("Y-m-d", strtotime($today."+2 hour"));
//分
echo date("Y-m-d", strtotime($today."+20 minute"));
//秒
echo date("Y-m-d", strtotime($today."+5 seconds"));
範例2:
//加1天5秒
echo date("Y-m-d", strtotime($today."+1 day 5 seconds"));
//加1週減2天
echo date("Y-m-d", strtotime($today."+1 week -2 day"));
範例3:
echo date( "Y-m-d", strtotime( "2016-01-31 +1 month" ) );  // PHP:  2016-03-02
echo date( "Y-m-d", strtotime( "2016-01-31 +2 month" ) );  // PHP:  2009-03-31
 // MySQL:  2016-02-28
SELECT DATE_ADD( '2016-01-31', INTERVAL 1 MONTH );
注意事項:
若只有指定日期而未指定時間,默認日期當天00:00:00為時間。

Reference: 
1. PHP官方 - strtotime
http://php.net/manual/en/function.strtotime.php


2016年5月26日 星期四

特殊字元寫到DB變成亂碼 -Solution解法


Qussion問題描述: 特殊字元寫到DB會變成亂碼 or ?問號
範例問題字碼: 字碼「é」會存成「é不知有碰過類似的問題嗎?


Answer解答1: 如果您使用的PHP + PDO 連線 + Mysql, 可用此方式.  在DB連線的Config設定中加上這行'SET NAMES UTF8' 實際程式範例如下:

// This is PDO Connection Method
// Connect to Potato Member Center
$HOST_DB="xxx.rds.amazonaws.com";
$DB_NAME="xxx";
$DB_USER="xxx";
$DB_PASS="xxx";

try {
    $db_conn = new PDO("mysql:host=$HOST_DB;dbname=$DB_NAME", $DB_USER, $DB_PASS);
    $db_conn->query('SET NAMES UTF8');  // 重要,可避免呈現亂碼.
} catch (PDOException $e) {
    echo "Could not connect to database";
}

Answer解答2: 您可以在寫入DB資料前加上此函式htmlentities( $str , ENT_QUOTES, "UTF-8"),如此即可以正確將字碼轉成UTF-8再儲存至DB即可。


Reference參考:
1. PHP htmlentities() 函数
http://www.w3school.com.cn/php/func_string_htmlentities.asp

2. 官方網站說明htmlentities — Convert all applicable characters to HTML entities
http://php.net/manual/en/function.htmlentities.php



George Huang 烤蕃薯@Taipei 2016

2016年5月24日 星期二

PHPExcel 使用注意事項 與 Demo範例說明

PHPExcel 使用注意事項 與 Demo範例說明

PHPExcel官網:http://www.codeplex.com/PHPExcel
PHPExcel官方下載: http://phpexcel.codeplex.com/releases/

重要指令彙整:
//合併儲存隔
$objPHPExcel->getActiveSheet()->mergeCells("A1:D2");

//設定漸層背景顏色雙色(灰/白)
$objPHPExcel->getActiveSheet()->getStyle("A1:D1")->applyFromArray(
    array(
   "font"    => array(
    "bold"   => true
   ),
   "alignment" => array(
    "horizontal" => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
   ),
   "borders" => array(
   "top" => array(
"style" => PHPExcel_Style_Border::BORDER_THIN
)
   ),
   "fill" => array(
"type"    => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
  "rotation"   => 90,
"startcolor" => array(
"rgb" => "DCDCDC"
),
"endcolor"   => array(
"rgb" => "FFFFFF"
)
)
    )
);

//設定字型大小 
$objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->setSize(10);

//設定字體顏色 
$objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE);

//設定背景顏色單色 
$objPHPExcel->getActiveSheet()->getStyle("A5:D6")->applyFromArray(
    array("fill" => array(
    "type"     => PHPExcel_Style_Fill::FILL_SOLID,
    "color"     => array("rgb" => "D1EEEE")
    ),
)
    );

// 增加些資料上來
echo date('H:i:s') , " Add some data" , EOL;
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello 番薯!')
            ->setCellValue('B2', 'world 芋頭!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');

// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'This is the testing. ')
            ->setCellValue('A5', '烤翻薯-許功蓋 中文測試!');


#Excel實際輸出截圖


Referene: 
1. PHPExcel 資源
   PHPExcel官網:http://www.codeplex.com/PHPExcel
   PHPExcel官方下載: http://phpexcel.codeplex.com/releases/
2. 隨意窩-hugh77417051
http://blog.xuite.net/hugh77417051/wretch/181832737-%E3%80%90PHP%E3%80%91PHPExcel+%E4%BD%BF%E7%94%A8%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A0%85+%E8%88%87+Demo+%E5%8C%AF%E5%87%BA+xls+xlsx

3. PHP官方fputcsv — Format line as CSV and write to file pointer
http://php.net/manual/en/function.fputcsv.php

4. 中文PHP fputcsv()函数教學
http://www.w3school.com.cn/php/func_filesystem_fputcsv.asp


George Huang烤蕃薯 @ Taipei