Copyright © Mike's Blog
Design by Dzignine
2011年12月28日 星期三

php小紀事

最近在做一個FTP下載的控管網頁
找到很多不錯的code 紀錄一下

透過php下載檔案大的作法 這邊把檔案做切割處理
然後在一塊一塊下載 而且還可以限制流量

//這個一定要設定,PHP頁面執行時間,不然載到一半就結束了
ini_set('max_execution_time', '0')

//定義切割大小

define('CHUNK_SIZE', 150*8); // Size (in bytes) of tiles chunk 512KB

// 讀取區塊

function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
      return false;
    }
    while (!feof($handle)) {
      $buffer = fread($handle, CHUNK_SIZE);
      echo $buffer;
      ob_flush();
      flush();
      if ($retbytes) {
        $cnt += strlen($buffer);
      }
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
      return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}

另一個是檔案瀏覽器 是open source的code
超級厲害 功能很完善 而且開發者還在維護中
有手機板 上傳管理 會員登入等功能 Encode Explorer

最後碰到一個問題就是 我想要顯示正確的檔案大小發現超過2G就會有問題
Encode Explorer有修正 可是只能在非windows上環境跑
後來我爬了一下code 只到許多解決辦法 最後挑出這個最好用的方法:

/**
* 這個方法是用curl的方式去讀取檔案大小
* 所以讀取網頁的話會有bug 可以再自行修正
*
*/
function ffilesize($file){
    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    if ($data === false) 
      return false;
    if (preg_match('/Content-Length: (\d+)/', $data, $matches))
      return (float)$matches[1];
}

附上一個小記錄 是關於NetBeans使用class時對於function的註解
加上自行這段註解會在hint中顯示 其實還頗方便的

/**
*
* 這邊是function說明
* @param string $filepath 
* filepath說明
* @return string
* 說明
*
*/
2011年8月24日 星期三

偵測碰撞 & 重力感應

這次開發的app 有一個類似android teeter的小遊戲
一開始沒有做過真的還不知道怎麼下手..像是flash可以用hitTest來偵測碰撞
果然iphone也有一個hitTest 不過..那是用來偵測使用者touch

在沒有頭緒的情況下就去請教google 翻了許多文章後找到了一些方法
好像是如果要做遊戲的話 還是建議使用cocos2d
而我這邊只是簡單的偵測碰撞 所以我利用iphone內建的function
還有一個別人寫的function 實在是非常厲害阿!

CGRectIntersectsRect
可以用來偵測CGRect的碰撞,只是偵測範圍是矩形
if( CGRectIntersectsRect(objA.frame, objB.frame) ){
       NSLog(@"Collision!");
}

另一個是將要被偵測碰撞的圖片 解析透明的地方
然後透過function去偵測point 也就可以不規則形狀的碰撞

-(void) initCollisionMap:(UIImage *)image {
    
    /** Pixel collision detetction initialization **/
    
    //1) Load the image:
    UIImage *collisionImage = [image retain];
    
    //2) Get the image size:
    int width = (int)collisionImage.size.width;
    int height = (int)collisionImage.size.height;
    
    //3) Allocate our array for quick lookups and clear it:
    collisionMap = (unsigned char *)malloc( width * height );
    memset( collisionMap, 0, width * height );
    
    //4) Get access to the raw bits of the image
    CFDataRef imageData = CGDataProviderCopyData( CGImageGetDataProvider
                                                 ( collisionImage.CGImage ) );
    
    const UInt32 *pixels = (const UInt32*)CFDataGetBytePtr( imageData );
    
    //5) Build our collision map:
    for(int j = 0; j < (width * height); j++ )
        if ( pixels[j] & 0xff000000 ) collisionMap[j] |= 1;
    
    //6) Release what we no longer need:
    CFRelease( imageData );
   
}

-(int)collisionForPoint:(CGPoint)point
{
    int x = (int)point.x;
    int y = (int)point.y;
    
    // TODO: check for boundaries here
    
    return collisionMap[(y*480)+x] ;
    
    
}

順便附上使用重力陀螺儀(UIAccelerometer)的使用

//開始啟用重力偵測
//偵測的頻率:10Hz to 100Hz.
 [UIAccelerometer sharedAccelerometer].updateInterval = 1/30;
 [UIAccelerometer sharedAccelerometer].delegate = self;

#pragma mark UIAccelerometerDelgate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
   //do something
}

//關閉
 [UIAccelerometer sharedAccelerometer].delegate = nil;

參考資料
http://snipplr.com/view/54886
http://homepages.ius.edu/rwisman/C490/html/chapter22.htm

2011年8月8日 星期一

一些iphone的小東西

最近在開發iphone一個case
遇到很多小問題 也學到很多實用技巧
在這邊記錄一下 也許以後有幫助

/**
 * 格式化日期
 */
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]];

//顯示結果
//2011-08-08


/**
 * 儲存plist檔案
 */
NSMutableDictionary *log = [[NSMutableDictionary alloc] init];
[log setValue:@"hello world" forKey:@"test"];
[log writeToFile:logPath atomically:YES];


/**
 * 使用get抓檔案
 */
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"你的網址"]];
[NSURLConnection connectionWithRequest:request delegate:self];

//收到網站的回應
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response
//收到網站傳回的資料
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
//網路連線錯誤
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
//網頁資料下載完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

//不過特別注意的是有網路可是伺服器的問題
//網頁一樣資料會被抓下來 不過出現網路錯誤
//可以用response的status code去判斷
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {  
    int statusCode = [(NSHTTPURLResponse *) response statusCode];
    if ( statusCode < 200 && statusCode >207) {
        //http回應不正確
    }
} 


/**
 * UITableView的cell 間隔背景色
 */
UITableView *result = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
result.dataSource = self;
result.delegate = self;

//UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row % 2) {
        cell.backgroundColor = [UIColor whiteColor];
    }
    else {
        
        cell.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:255.0/255.0 blue:201.0/255.0 alpha:1.0];
        
    }
}

2011年7月19日 星期二

簡單的animation

最近在開發iphone的程式 需要開場要有些動畫
在此順便記錄一下 目前試過的作法有兩個CAKeyframeAnimation , CATransition
/**
 * CAKeyframeAnimation  
 * 我覺得這個稍微複雜一點
 * 不過可以設定的比較詳細 必須自己設置 時間 路線
 * 有點像是徒手打造出有path的影格動畫
 * framework: Quartz 2D
 **/
CALayer *myLayer = [CALayer layer];

CAKeyframeAnimation *theAnimation;
theAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];  //類似keyName
theAnimation.beginTime = 0;
/**
 * 附上官網的reference 
 * void CGPathMoveToPoint (
 *  CGMutablePathRef path,
 *  const CGAffineTransform *m,
 *  CGFloat x,
 *  CGFloat y
 * );
 */        
CGMutablePathRef myPath = CGPathCreateMutable();
CGPathMoveToPoint(myPath, nil, 164, 0);
CGPathAddLineToPoint(myPath, nil, 164, 89);
CGPathAddLineToPoint(myPath, nil, 164, 57);
/** ... 類推 設定路線  **/
CGPathCloseSubpath(myPath);

theAnimation.path = myPath;
CGPathRelease(myPath);
        
/** 
 * 設定每個path需要的時間
 * 需要注意的是這裡的時間是用比例來算
 *
 */
NSMutableArray *keyTimes = [[NSMutableArray alloc] init];
[keyTimes addObject:[NSNumber numberWithFloat:0.0]];
[keyTimes addObject:[NSNumber numberWithFloat:0.425]];
[keyTimes addObject:[NSNumber numberWithFloat:1.0]];
        
theAnimation.keyTimes = keyTimes;
[theAnimation release];

theAnimation.duration = 2;
theAnimation.autoreverses = NO;
theAnimation.repeatCount = 0;
theAnimation.delegate = self;

//最後加上去就大功告成拉
[myLayer addAnimation:theAnimation forKey:@"position"];

/**
 * CATransition
 * 感覺上比較簡單使用 可以用在Layer 跟 UIView 上面
 * framework: QuartzCore.framework
 */

CATransition *theAnimation = [CATransition alloc];
theAnimation.duration = 1.0;
theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
theAnimation.type = kCATransitionPush;
theAnimation.subtype = kCATransitionFromLeft;

[song addAnimation:songAnimation forKey:@"fromLeft"];

/**
 * 如果你有附上delegate 就可在動畫結束時偵測到
 * theAnimation.delegate = self;
 */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
      //do something you want
}
2011年5月11日 星期三

php列出所有目錄的檔案

做個紀錄,如題。
if ($handle = opendir('.')) {  //開啟現在的資料夾
      while (false !== ($file = readdir($handle))) {
//避免搜尋到的資料夾名稱是false,像是0
          if ($file != "." && $file != "..") {
//去除掉..跟.
              echo "<a href='$file'>$file</a><br>";              
          }
      }
      closedir($handle);
  }
參考資料: http://www.aixq.com/php-readdir/
2011年5月8日 星期日

用php sdk上傳到粉絲團

$pageid = '208167129000000';   //粉絲團的ID
$albumid = '51226';                      //相簿的AID

// 先取得你管理的權限(account->access_token)
$accounts = $facebook->api('/me/accounts');

// 從陣列中一一讀出,判斷是否是你要的access_token
foreach($accounts['data'] as $account) {
   if($account['id'] == $pageid) {
     $token = $account['access_token'];
   }
}

// 要上傳圖片的路徑
$file = '@' .realpath("test.png");

// 上傳的參數
$args = array(
   'access_token' => $token,
   'image' => $file,
   'aid' => $albumid,
   'message'=>date('Y-m-d H:i:s')
);

// 送出api指令
$data = $facebook->api('/'.$pageid.'/photos', 'post', $args);

//成功後會回傳一個id值
//data(0)
// {
//    [id]:121234324253;
// }
2011年5月6日 星期五

sortable的serialize用法

今天需要用jQuery UI的sortable功能去做資料表排序
做法是先從資料庫抓資料下來然後再回傳新的排序位置回去
看不懂官方的文件 後來爬文一下後
原來用法挺簡單的
$('#sortable').sortable({
  update: function(event, ui){
    alert($(this).sortable('serialize'));
  }
});
重點是在html上面的屬性
<ul id="sortable">
  <li id="sort_1">item 1</li>
  <li id="sort_2">item 2</li>
  <li id="sort_3">item 3</li>
  <li id="sort_4">item 4</li>
</ul>
畫面結果顯示

如果想要自訂屬性也可以
$('#sortable').sortable({
  update: function(event, ui){
    alert($(this).sortable('serialize',
      { attribute: 'myId', key: 'myId' }));
  }
});

html這邊改一下就可以了

<ul id="sortable">
  <li myId="sort_1">item 1</li>
  <li myId="sort_2">item 2</li>
  <li myId="sort_3">item 3</li>
  <li myId="sort_4">item 4</li>
</ul>
記得值要符合格式: foo=1,foo_1,foo-1
2011年5月4日 星期三

強制斷行的語法

有時候從php抓資料來時
資料顯示在表格或div會造成破掉的情形
不知道為什麼會撐爆...只好用css語法把它斷行
目前適用過於table跟div
其他地方沒有用過 可以自行try一下

div{
word-wrap: break-word;  //IE
word-break: break-all;     //Firefox
}
2011年4月30日 星期六

實用的javscript 自動縮放圖片大小

以前做網頁的時候
用php自動抓取圖片出來
想要固定圖片大小通常都會用CSS設定或是直接設定屬性



最近發現這樣作法不是很好
如果圖片寬度小於120px的話就會被拉大
於是用了別的方法



這段javascript是先判斷圖片的長寬比
然後再判斷圖片的寬度或長度
這樣子圖片就可以依照自己想要的長度與寬度自動縮放