如果php以圖片,zip,exe等文件輸出到瀏覽器,而前面還輸出了其他字符,就會有亂碼。
代碼很簡單,網上都能找到,但在我機子上就是顯示不出來,顯示出的一直是這個php文件路徑,費了點時間才搞定,原來是<?php這個標簽前面有多的空格,刪除即可。
網上查了下,有這樣一說:
如果php以圖片,zip,exe等文件輸出到瀏覽器,而前面還輸出了其他字符,那就會是你看到的亂碼。
應該是輸出圖片前有輸出空格或其他字符造成的,可以檢查一下輸出圖片前有沒有其他字符,如果是utf-8編碼記得保存為無BOM的文件。
相關代碼如下:
<?php /** * 讀取圖片內容 輸出至瀏覽器 * edit by www.jbxue.com */ class imgdata{ public $imgsrc; public $imgdata; public $imgform; public function getdir($source){ $this->imgsrc = $source; } public function img2data(){ $this->_imgfrom($this->imgsrc); return $this->imgdata=fread(fopen($this->imgsrc,'rb'),filesize($this->imgsrc)); } public function data2img(){ header("content-type:$this->imgform"); echo $this->imgdata; //echo $this->imgform; //imagecreatefromstring($this->imgdata); } public function _imgfrom($imgsrc){ $info=getimagesize($imgsrc); //var_dump($info); return $this->imgform = $info['mime']; } } $n = new imgdata; $n -> getdir("1.jpg"); $n -> img2data(); $n -> data2img(); ?>
