>  기사  >  백엔드 개발  >  PHP 바이너리 스트림이 잘못된 문자를 출력하는 경우 수행할 작업

PHP 바이너리 스트림이 잘못된 문자를 출력하는 경우 수행할 작업

藏色散人
藏色散人원래의
2022-10-21 09:37:141931검색

PHP 바이너리 스트림의 잘못된 출력에 대한 해결 방법: 1. 로컬 "conn.php" 및 "print.php" 파일을 엽니다. 2. "ob_clean"을 사용하여 헤더 내용을 지우고 "mysql_close"와 같은 코드를 수정합니다. ();ob_clean(); 헤더("콘텐츠 유형:$type");".

PHP 바이너리 스트림이 잘못된 문자를 출력하는 경우 수행할 작업

이 튜토리얼의 운영 환경: Windows 7 시스템, PHP 버전 8.1, Dell G3 컴퓨터.

PHP의 바이너리 스트림 출력이 왜곡되면 어떻게 해야 하나요?

최근에 PHP를 사용하여 mysql에서 바이너리 파일을 개발하고 읽고 출력하던 중 문자가 깨지는 문제에 직면했습니다.

바이너리 파일을 출력할 때는 일반적으로 다음 방법을 사용합니다.

<?php
if(!isset($id) or $id=="") die("error: id none");
//定位记录,读出
$conn=mysql_connect("127.0.0.1","***","***");
if(!$conn) die("error : mysql connect failed");
mysql_select_db("test",$conn);
$sql = "select * from receive where id=$id";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num<1) die("error: no this recorder");
$data = mysql_result($result,0,"file_data");
$type = mysql_result($result,0,"file_type");
$name = mysql_result($result,0,"file_name");
mysql_close($conn);
//先输出相应的文件头,并且恢复原来的文件名
header("Content-type:$type");
header("Content-Disposition: attachment; filename=$name");
echo $data;
?>

위 방법에는 문제가 없습니다. 그러나 데이터베이스 연결을 별도의 파일에 캡슐화하면 문제가 발생합니다. 위의 코드를 2개의 파일로 다시 작성합니다.

//conn.php
<?php
function Open_DB(){
$conn=mysql_connect("127.0.0.1","***","***");
if(!$conn) die("error : mysql connect failed");
mysql_select_db("test",$conn);
}
?>
//print.php
<?php
if(!isset($id) or $id=="") die("error: id none");
//定位记录,读出
require_once(&#39;conn.php&#39;);
Open_DB();
$sql = "select * from receive where id=$id";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num<1) die("error: no this recorder");
$data = mysql_result($result,0,"file_data");
$type = mysql_result($result,0,"file_type");
$name = mysql_result($result,0,"file_name");
mysql_close();
header("Content-type:$type");
header("Content-Disposition: attachment; filename=$name");
echo $data;
?>

이때 print.php를 호출하여 단어 파일을 열면 문자가 깨져서 생성됩니다. 문제는 "require_once('conn.php')" 문에 있습니다. PHP가 이 명령문을 호출하면 헤더에 출력되며 이는 다음 두 헤더 명령문에 영향을 미쳐 워드 파일의 데이터 흐름을 파괴합니다. 따라서 열린 워드 파일은 깨질 수 있습니다.

해결책은 ob_clean을 사용하여 헤더 내용을 지우는 것입니다. 다시 작성된 print.php는 다음과 같습니다

//print.php
<?php
if(!isset($id) or $id=="") die("error: id none");
//定位记录,读出
require_once(&#39;conn.php&#39;);
Open_DB();
$sql = "select * from receive where id=$id";
$result = mysql_query($sql);
$num=mysql_num_rows($result);
if($num<1) die("error: no this recorder");
$data = mysql_result($result,0,"file_data");
$type = mysql_result($result,0,"file_type");
$name = mysql_result($result,0,"file_name");
mysql_close();
ob_clean();
header("Content-type:$type");
header("Content-Disposition: attachment; filename=$name");
echo $data;
?>

학습 권장 사항: "PHP Video Tutorial"

위 내용은 PHP 바이너리 스트림이 잘못된 문자를 출력하는 경우 수행할 작업의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.