国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Maison développement back-end tutoriel php php 使用PHPEXcel導(dǎo)出表數(shù)據(jù)

php 使用PHPEXcel導(dǎo)出表數(shù)據(jù)

Jul 25, 2016 am 08:41 AM

項(xiàng)目中需要將表中的數(shù)據(jù)導(dǎo)出,在網(wǎng)上找了找發(fā)現(xiàn)phpexcel蠻好用的.特此分享

PHPEXCEL

  1. if(!defined('BASEPATH')) exit('No direct script access allowed');
  2. //物資發(fā)料單明細(xì)
  3. class Read_write{
  4. /**
  5. * $name:選擇的類型(CSV,EXCEL2003,2007)
  6. * $titles:標(biāo)題數(shù)組
  7. * $querys:查詢返回的數(shù)組 $query->result_array();
  8. * $filename:保存的文件名稱
  9. */
  10. function write_Factory($titles,$querys,$filename,$name="EXCEL2003"){
  11. $CI = &get_instance();
  12. $filename=mb_convert_encoding($filename, "GBK","UTF-8");
  13. switch ($name) {
  14. case "CSV":
  15. $CI->excel->write_CSV($titles,$querys,$filename);
  16. break;
  17. case "EXCEL2003":
  18. $CI->excel->write_EXCEL2003($titles,$querys,$filename);
  19. break;
  20. case "EXCEL2007":
  21. $CI->excel->write_EXCEL2007($titles,$querys,$filename);
  22. break;
  23. }
  24. }
  25. /**
  26. * $name:
  27. */
  28. function read_Facotry($filePath,$sql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
  29. $CI = &get_instance();
  30. $name=$this->_file_extend($filePath);
  31. switch ($name) {
  32. case "csv":
  33. $CI->excel->read_CSV($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
  34. break;
  35. case "xls":
  36. $CI->excel->read_2003Excel($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
  37. break;
  38. case "xlsx":
  39. $CI->excel->read_EXCEL2007($filePath,$sql,$sheet,$curRow,$riqi,$merge,$mergeCol);
  40. break;
  41. }
  42. $CI->mytool->import_info("filePath=$filePath,sql=$sql");
  43. }
  44. /**
  45. * 2012-1-14 讀取工作薄名稱(sheetnames)
  46. */
  47. function read_sheetNames($filePath){
  48. $CI = &get_instance();
  49. $name=$this->_file_extend($filePath);
  50. $sheetnames;
  51. switch ($name) {
  52. case "csv":
  53. $sheetnames=$CI->excel->read_CSV_Sheet($filePath);
  54. break;
  55. case "xls":
  56. $sheetnames=$CI->excel->read_2003Excel_Sheet($filePath);
  57. break;
  58. case "xlsx":
  59. $sheetnames=$CI->excel->read_EXCEL2007_Sheets($filePath);
  60. break;
  61. }
  62. return $sheetnames;
  63. }
  64. //讀取文件后綴名
  65. function _file_extend($file_name){
  66. $extend =explode("." , $file_name);
  67. $last=count($extend)-1;
  68. return $extend[$last];
  69. }
  70. //-----------------------------------------------預(yù)備保留
  71. //2011-12-21新增CVS導(dǎo)出功能
  72. public function export_csv($filename,$title,$datas, $delim = ",", $newline = "\n", $enclosure = '"'){
  73. $CI = &get_instance();
  74. $cvs= $this->_csv_from_result($title,$datas,$delim,$newline,$enclosure);
  75. $CI->load->helper('download');
  76. $name=mb_convert_encoding($filename, "GBK","UTF-8");
  77. force_download($name, $cvs);
  78. }
  79. /**
  80. * @param $titles:標(biāo)題
  81. * @param $datas:數(shù)據(jù)
  82. */
  83. function _csv_from_result($titles,$datas, $delim = ",", $newline = "\n", $enclosure = '"'){
  84. $out = '';
  85. // First generate the headings from the table column names
  86. foreach ($titles as $name){
  87. $name=mb_convert_encoding($name, "GBK","UTF-8");
  88. $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
  89. }
  90. $out = rtrim($out);
  91. $out .= $newline;
  92. // Next blast through the result array and build out the rows
  93. foreach ($datas as $row)
  94. {
  95. foreach ($row as $item)
  96. {
  97. $item=mb_convert_encoding($item, "GBK","UTF-8");
  98. $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
  99. }
  100. $out = rtrim($out);
  101. $out .= $newline;
  102. }
  103. return $out;
  104. }
  105. }
復(fù)制代碼

PHPEXCEL?~?13KB????下載(28)

  1. /**
  2. * PHPExcel
  3. *
  4. * Copyright (C) 2006 - 2010 PHPExcel
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. *
  20. * @category PHPExcel
  21. * @package PHPExcel
  22. * @copyright Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)
  23. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  24. * @version 1.7.4, 2010-08-26
  25. */
  26. /** Error reporting */
  27. error_reporting(E_ALL);
  28. date_default_timezone_set ('Asia/Shanghai');
  29. /** PHPExcel */
  30. require_once 'Classes/PHPExcel.php';
  31. require_once 'Classes/PHPExcel/IOFactory.php';
  32. /**
  33. * 輸出到頁(yè)面上的EXCEL
  34. */
  35. /**
  36. * CI_Excel
  37. *
  38. * @package ci
  39. * @author admin
  40. * @copyright 2011
  41. * @version $Id$
  42. * @access public
  43. */
  44. class CI_Excel
  45. {
  46. //列頭,Excel每列上的標(biāo)識(shí)
  47. private $cellArray = array(
  48. 1=>'A', 2=>'B', 3=>'C', 4=>'D', 5=>'E',
  49. 6=>'F', 7=>'G', 8=>'H', 9=>'I',10=>'J',
  50. 11=>'K',12=>'L',13=>'M',14=>'N',15=>'O',
  51. 16=>'P',17=>'Q',18=>'R',19=>'S',20=>'T',
  52. 21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',
  53. 26=>'Z',
  54. 27=>'AA', 28=>'AB', 29=>'AC', 30=>'AD', 31=>'AE',
  55. 32=>'AF', 33=>'AG', 34=>'AH', 35=>'AI',36=>'AJ',
  56. 37=>'AK',38=>'AL',39=>'AM',40=>'AN',41=>'AO',
  57. 42=>'AP',43=>'AQ',44=>'AR',45=>'AS',46=>'AT',
  58. 47=>'AU',48=>'AV',49=>'AW',50=>'AX',51=>'AY',
  59. 52=>'AZ', 53=>'BA', 54=>'BB', 55=>'BC', 56=>'BD', 57=>'BE',
  60. 58=>'BF', 59=>'BG', 60=>'BH', 61=>'BI', 62=>'BJ', 63=>'BK', 64=>'BL');
  61. private $E2003 = 'E2003';
  62. private $E2007 = 'E2007';
  63. private $ECSV = 'ECSV';
  64. private $tempName; //當(dāng)讀取合并文件時(shí),如果第二行為空,則取第一行的名稱
  65. /*********************************導(dǎo)出數(shù)據(jù)開始****************************************************/
  66. /**
  67. * 生成Excel2007文件
  68. */
  69. function write_EXCEL2007($title='',$data='',$name='')
  70. {
  71. $objPHPExcel=$this->_excelComm($title,$data,$name);
  72. // Redirect output to a client’s web browser (Excel2007)
  73. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8');
  74. header("Content-Disposition: attachment;filename=$name.xlsx");
  75. header('Cache-Control: max-age=0');
  76. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
  77. $objWriter->save('php://output'); //output 允許向輸出緩沖機(jī)制寫入數(shù)據(jù),和 print() 與 echo() 的方式相同。
  78. exit;
  79. }
  80. /**
  81. * 生成Excel2003文件
  82. */
  83. function write_EXCEL2003($title='',$data='',$name=''){
  84. $objPHPExcel=$this->_excelComm($title,$data,$name);
  85. //Redirect output to a client’s web browser (Excel5)
  86. header('Content-Type: application/vnd.ms-excel;charset=UTF-8');
  87. header("Content-Disposition: attachment;filename=$name.xls");
  88. header('Cache-Control: max-age=0');
  89. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  90. $objWriter->save('php://output');
  91. }
  92. /**
  93. * 生成CSV文件
  94. */
  95. function write_CSV($title='',$data='',$name=''){
  96. $objPHPExcel=$this->_excelComm($title,$data,$name);
  97. header("Content-Type: text/csv;charset=UTF-8");
  98. header("Content-Disposition: attachment; filename=$name.csv");
  99. header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
  100. header('Expires:0');
  101. header('Pragma:public');
  102. $objWriter = new PHPExcel_Writer_CSV($objPHPExcel,'CSV');
  103. $objWriter->save("php://output");
  104. exit;
  105. }
  106. function _excelComm($title,$data,$name){
  107. // Create new PHPExcel object
  108. $objPHPExcel = new PHPExcel();
  109. $objPHPExcel=$this->_writeTitle($title,$objPHPExcel);
  110. $objPHPExcel=$this->_writeDatas($data,$objPHPExcel);
  111. $objPHPExcel=$this->_write_comm($name,$objPHPExcel);
  112. return $objPHPExcel;
  113. }
  114. //輸出標(biāo)題
  115. function _writeTitle($title,$objPHPExcel){
  116. //表頭循環(huán)(標(biāo)題)
  117. foreach ($title as $tkey => $tvalue){
  118. $tkey = $tkey+1;
  119. $cell = $this->cellArray[$tkey].'1'; //第$tkey列的第1行,列的標(biāo)識(shí)符(a..z)
  120. // Add some data //表頭
  121. // $tvalue=mb_convert_encoding($tvalue, "UTF-8","GBK");
  122. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cell, $tvalue); //設(shè)置第$row列的值(標(biāo)題)
  123. }
  124. return $objPHPExcel;
  125. }
  126. //輸出內(nèi)容
  127. function _writeDatas($data,$objPHPExcel){
  128. //內(nèi)容循環(huán)(數(shù)據(jù)庫(kù)查詢的返回值)
  129. foreach($data as $key =>$value) {
  130. $i = 1;
  131. foreach ($value as $mkey =>$mvalue){ //返回的類型是array([0]=>array());,所以此處要循環(huán)它的value,也就是里面的array
  132. $rows = $key+2; //開始是第二行
  133. $mrow = $this->cellArray[$i].$rows; //第$i列的第$row行
  134. // $mvalue=mb_convert_encoding($mvalue, "GBK","UTF-8");
  135. // print_r($mrow."--->".$mvalue);
  136. $objPHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($mrow, $mvalue);
  137. $i++;
  138. }
  139. }
  140. return $objPHPExcel;
  141. }
  142. function _write_comm($name,$objPHPExcel){
  143. // Rename sheet(左下角的標(biāo)題)
  144. //$objPHPExcel->getActiveSheet()->setTitle($name);
  145. // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  146. $objPHPExcel->setActiveSheetIndex(0); //默認(rèn)顯示
  147. return $objPHPExcel;
  148. }
  149. /*********************************導(dǎo)出數(shù)據(jù)結(jié)束****************************************************/
  150. /*********************************讀取數(shù)據(jù)開始****************************************************/
  151. /**
  152. * 使用方法,$insertSql:insert xx (x1,x2,x3,x4) value (
  153. */
  154. // function _comm_insert($objReader,$filePath,$insertSql,$sheet=2,$curRow=2,$riqi=TRUE){
  155. function _comm_insert($objPHPExcel,$insertSql,$curRow,$merge=FALSE,$mergeCol='B'){
  156. $CI = &get_instance();
  157. $currentSheet = $objPHPExcel->getSheet();//得到指定的激活
  158. /**取得一共有多少列*/
  159. $allColumn = $currentSheet->getHighestColumn();
  160. /**取得一共有多少行*/
  161. $allRow = $currentSheet->getHighestRow();
  162. $size=strlen($allColumn);//如果超出Z,則出現(xiàn)不執(zhí)行下去
  163. $esql="";
  164. for($currentRow = $curRow;$currentRow $sql=$insertSql;
  165. if($size==2){
  166. $i=1;
  167. $currentColumn='A';
  168. while ($i $address = $currentColumn.$currentRow;
  169. $temp=$currentSheet->getCell($address)->getCalculatedValue();
  170. $sql.='"'.$temp.'"'.",";
  171. $currentColumn++;
  172. $i++;
  173. }
  174. for($currentColumn='AA';$currentColumn $address = $currentColumn.$currentRow;
  175. $sql.='"'.$currentSheet->getCell($address)->getCalculatedValue().'"'.",";
  176. }
  177. }else{
  178. for($currentColumn='A';$currentColumn if($merge){//如果是讀取合并的值,則判斷,如果此行的值為NULL,則把前面的tempName賦值給$temp;
  179. if($currentColumn==$mergeCol){//這里先指定從B列的名字開始讀取合并了的值。以后遇到不同的再調(diào)整。
  180. $temp=$currentSheet->getCell($mergeCol.$currentRow)->getCalculatedValue();
  181. if(empty($temp)){
  182. $temp=$this->tempName;
  183. }else{
  184. $this->tempName=$temp;
  185. }
  186. }else{
  187. $address = $currentColumn.$currentRow;//getValue()
  188. $temp=$currentSheet->getCell($address)->getCalculatedValue();
  189. }
  190. }else{
  191. $address = $currentColumn.$currentRow;//getValue()
  192. $temp=$currentSheet->getCell($address)->getCalculatedValue();
  193. }
  194. $sql=$sql.'"'.$temp.'"'.",";
  195. }
  196. }
  197. $esql=rtrim($sql,",").')';
  198. //echo($esql);
  199. //return;
  200. $CI->db->simple_query($esql);
  201. }
  202. }
  203. /**
  204. * $filePath:讀取文件的路徑
  205. * $insertSql:拼寫的SQL
  206. */
  207. function read_EXCEL2007($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
  208. $objs=$this->_get_PHPExcel($this->E2007,$filePath,$sheet,$insertSql,$riqi);
  209. $this->_comm_insert($objs["EXCEL"],$objs["SQL"],$curRow,$merge,$mergeCol);
  210. }
  211. /**
  212. * 讀取2003Excel
  213. */
  214. function read_2003Excel($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
  215. $objs=$this->_get_PHPExcel($this->E2003,$filePath,$sheet,$insertSql,$riqi);
  216. $this->_comm_insert($objs["EXCEL"],$objs["SQL"],$curRow,$merge,$mergeCol);
  217. }
  218. /**
  219. * 讀取CSV
  220. */
  221. function read_CSV($filePath,$insertSql,$sheet=0,$curRow=2,$riqi=TRUE,$merge=FALSE,$mergeCol="B"){
  222. $objs=$this->_get_PHPExcel($this->ECSV,$filePath,$sheet,$insertSql,$riqi,$mergeCol);
  223. $this->_comm_insert($objs["EXCEL"],$objs["SQL"],$curRow,$merge);
  224. }
  225. //--------------------------------讀取工作薄信息開始
  226. /**
  227. * 讀取Excel2007工作薄名稱
  228. */
  229. function read_EXCEL2007_Sheets($filePath){
  230. return $this->_get_sheetnames($this->E2007,$filePath);
  231. }
  232. /**
  233. * 讀取2003Excel工作薄名稱
  234. */
  235. function read_2003Excel_Sheet($filePath){
  236. return $this->_get_sheetnames($this->E2003,$filePath);
  237. }
  238. /**
  239. * 讀取CSV工作薄名稱
  240. */
  241. function read_CSV_Sheet($filePath){
  242. return $this->_get_sheetnames($this->ECSV,$filePath);
  243. }
  244. //--------------------------------讀取工作薄信息結(jié)束
  245. /**
  246. * 2012-1-14 --------------------------
  247. */
  248. //讀取Reader流
  249. function _get_Reader($name){
  250. $reader=null;
  251. switch ($name) {
  252. case $this->E2003:
  253. $reader = new PHPExcel_Reader_Excel5();
  254. break;
  255. case $this->E2007:
  256. $reader = new PHPExcel_Reader_Excel2007();
  257. break;
  258. case $this->ECSV:
  259. $reader = new PHPExcel_Reader_CSV();
  260. break;
  261. }
  262. return $reader;
  263. }
  264. //得到$objPHPExcel文件對(duì)象
  265. function _get_PHPExcel($name,$filePath,$sheet,$insertSql,$riqi){
  266. $reader=$this->_get_Reader($name);
  267. $PHPExcel= $this->_init_Excel($reader,$filePath,$sheet);
  268. if($riqi){ //如果不需要日期,則忽略.
  269. $insertSql=$insertSql.'"'.$reader->getSheetTitle().'"'.",";//第一個(gè)字段固定是日期2012-1-9
  270. }
  271. return array("EXCEL"=>$PHPExcel,"SQL"=>$insertSql);
  272. }
  273. //得到工作薄名稱
  274. function _get_sheetnames($name,$filePath){
  275. $reader=$this->_get_Reader($name);
  276. $this->_init_Excel($reader,$filePath);
  277. return $reader->getAllSheets();
  278. }
  279. //加載文件
  280. function _init_Excel($objReader,$filePath,$sheet=''){
  281. $objReader->setReadDataOnly(true);
  282. if(!empty($sheet)){
  283. $objReader->setSheetIndex($sheet);//讀取第幾個(gè)Sheet。
  284. }
  285. return $objReader->load("$filePath");
  286. }
  287. //-------------------------------2012-1-14
  288. }
  289. /*********************************讀取數(shù)據(jù)結(jié)束****************************************************/
復(fù)制代碼

[PHP]代碼

  1. ------------------------導(dǎo)入操作------------------------
  2. /**
  3. * $sql="INSERT INTO ".mymsg::WY_MMB." (dizhi,xingming) VALUES (";
  4. */
  5. //先上傳再讀取文件
  6. function upByFile($sql, $url, $curRow = 2, $RIQI = true,$merge = FALSE,$mergeCol='B')
  7. {
  8. $CI = &get_instance();
  9. $config['allowed_types'] = '*'; //充許所有文件
  10. $config['upload_path'] = IMPORT; // 只在文件的路徑
  11. $CI->load->library('upload', $config);
  12. if ($CI->upload->do_upload()) { //默認(rèn)名是:userfile
  13. $data = $CI->upload->data();
  14. $full_name = $data['full_path']; //得到保存后的路徑
  15. $full_name = mb_convert_encoding($full_name, "GBK", "UTF-8");
  16. $sheet = $CI->input->post("sheet"); //讀取第x列圖表
  17. if (empty($sheet)) {
  18. $sheet = 0;
  19. }
  20. $CI->read_write->read_Facotry($full_name, $sql, $sheet, $curRow, $RIQI,$merge,$mergeCol); //執(zhí)行插入命令
  21. }
  22. $this->alert_msg(mymsg::IMPORT_SUCCESS, site_url($url));
  23. }
  24. ------------------------------導(dǎo)出操作----------------------------------
  25. //導(dǎo)出指定的表字段
  26. public function show_export(){
  27. //-----數(shù)據(jù)庫(kù)字段
  28. $field=implode(",",$this->input->post("listCheckBox_show"));//數(shù)據(jù)庫(kù)字段
  29. //顯示名稱
  30. $titleArray=$this->input->post("listCheckBox_field");//顯示的字段名稱(字段Comment注解名,因?yàn)閭鬟M(jìn)來(lái)的有些空數(shù)組,所以必須過(guò)濾)
  31. $title=array();
  32. foreach ($titleArray as $key => $value) {
  33. if (!empty($value)) {
  34. $title[]=$value;
  35. }
  36. }
  37. //---數(shù)據(jù)庫(kù)表名
  38. $table=$this->input->post("tableName");
  39. //--數(shù)據(jù)庫(kù)表名稱(Comment注釋)
  40. $show_name=$this->input->post("tableComment");
  41. //--導(dǎo)出類型
  42. $type=$this->input->post("type");
  43. //--where 年月
  44. $y_month=$this->input->post("year_month");
  45. if(!empty($y_month)){
  46. $where["riqi"]=$y_month;
  47. $datas=$this->mcom_model->queryByWhereReField($field,$where,$table);
  48. }else{
  49. //--寫出的數(shù)據(jù)
  50. $datas=$this->mcom_model->queryByField($field,$table);
  51. }
  52. //---開始導(dǎo)出
  53. $this->read_write->write_Factory($title,$datas,$show_name,$type);
  54. }
復(fù)制代碼

php, PHPEXcel


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefa?on, veuillez contacter admin@php.cn

Outils d'IA chauds

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

échangez les visages dans n'importe quelle vidéo sans effort grace à notre outil d'échange de visage AI entièrement gratuit?!

Article chaud

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Tutoriel PHP
1502
276
Porce de variable PHP expliquée Porce de variable PHP expliquée Jul 17, 2025 am 04:16 AM

Les problèmes et les solutions courants pour la portée de la variable PHP incluent: 1. La variable globale ne peut pas être accessible dans la fonction, et elle doit être transmise en utilisant le mot-clé ou le paramètre global; 2. La variable statique est déclarée avec statique, et elle n'est initialisée qu'une seule fois et la valeur est maintenue entre plusieurs appels; 3. Des variables hyperglobales telles que $ _get et $ _post peuvent être utilisées directement dans n'importe quelle portée, mais vous devez faire attention au filtrage s?r; 4. Les fonctions anonymes doivent introduire des variables de portée parents via le mot clé Utiliser, et lorsque vous modifiez les variables externes, vous devez passer une référence. La ma?trise de ces règles peut aider à éviter les erreurs et à améliorer la stabilité du code.

Comment gérer les téléchargements de fichiers en toute sécurité dans PHP? Comment gérer les téléchargements de fichiers en toute sécurité dans PHP? Jul 08, 2025 am 02:37 AM

Pour gérer en toute sécurité les téléchargements de fichiers PHP, vous devez vérifier la source et taper, contr?ler le nom et le chemin du fichier, définir les restrictions du serveur et traiter les fichiers multimédias deux fois. 1. Vérifiez la source de téléchargement pour empêcher le CSRF via le jeton et détecter le type de mime réel via FINFO_FILE en utilisant le contr?le de liste blanche; 2. Renommez le fichier à une cha?ne aléatoire et déterminez l'extension pour la stocker dans un répertoire non Web en fonction du type de détection; 3. La configuration PHP limite la taille de téléchargement et le répertoire temporaire Nginx / Apache interdit l'accès au répertoire de téléchargement; 4. La bibliothèque GD résait les images pour effacer des données malveillantes potentielles.

Commentant le code en php Commentant le code en php Jul 18, 2025 am 04:57 AM

Il existe trois méthodes courantes pour le code de commentaire PHP: 1. Utiliser // ou # pour bloquer une ligne de code, et il est recommandé d'utiliser //; 2. Utiliser /.../ pour envelopper des blocs de code avec plusieurs lignes, qui ne peuvent pas être imbriquées mais peuvent être croisées; 3. Compétences combinées Commentaires tels que l'utilisation / if () {} / pour contr?ler les blocs logiques, ou pour améliorer l'efficacité avec les touches de raccourci de l'éditeur, vous devez prêter attention aux symboles de fermeture et éviter les nidification lorsque vous les utilisez.

Comment les générateurs fonctionnent-ils en PHP? Comment les générateurs fonctionnent-ils en PHP? Jul 11, 2025 am 03:12 AM

AgeneratorInphpisamemory-EfficientwaytoterateOrgedatasetsByyieldingValuesonEatatimeIntedofreturningThemallAtonce.1.GeneratorsUsEtheieldKeywordToproduceValuesondemand, ReducingMemoryUsage.2.TheyAreusefulForHandlingBigloops, ReadingLargeFiles, OR OR.

Conseils pour écrire des commentaires PHP Conseils pour écrire des commentaires PHP Jul 18, 2025 am 04:51 AM

La clé pour rédiger des commentaires PHP est de clarifier l'objectif et les spécifications. Les commentaires devraient expliquer "pourquoi" plut?t que "ce qui a été fait", en évitant la redondance ou trop de simplicité. 1. Utilisez un format unifié, tel que DocBlock (/ * /) pour les descriptions de classe et de méthode afin d'améliorer la lisibilité et la compatibilité des outils; 2. Soulignez les raisons de la logique, telles que pourquoi les sauts JS doivent être sortis manuellement; 3. Ajoutez une description d'une vue d'ensemble avant le code complexe, décrivez le processus dans les étapes et aidez à comprendre l'idée globale; 4. Utilisez TODO et FIXME Rationalement pour marquer des éléments et des problèmes de taches pour faciliter le suivi et la collaboration ultérieurs. De bonnes annotations peuvent réduire les co?ts de communication et améliorer l'efficacité de la maintenance du code.

Apprendre PHP: un guide du débutant Apprendre PHP: un guide du débutant Jul 18, 2025 am 04:54 AM

Toléarnphpeffective, startBySettingUpAlocalServerERironmentUsingToolsLILYXAMPPANDACODEDITERLIGHILLEVSCODE.1) INSTRUSITIONXAMPFORAPACHE, MYSQL, ANDPHP.2) USACODEDEDITORFORSYNTAXSUPPORT.3)

Comment accéder à un caractère dans une cha?ne par index en php Comment accéder à un caractère dans une cha?ne par index en php Jul 12, 2025 am 03:15 AM

En PHP, vous pouvez utiliser des crochets ou des accolades bouclées pour obtenir des caractères d'index spécifiques à la cha?ne, mais les crochets sont recommandés; L'index commence à partir de 0 et l'accès à l'extérieur de la plage renvoie une valeur nulle et ne peut pas se voir attribuer une valeur; MB_substr est nécessaire pour gérer les caractères multi-octets. Par exemple: $ str = "Hello"; echo $ str [0]; sortie h; et les caractères chinois tels que MB_substr ($ str, 1,1) doivent obtenir le résultat correct; Dans les applications réelles, la longueur de la cha?ne doit être vérifiée avant le boucle, les cha?nes dynamiques doivent être vérifiées pour la validité et les projets multilingues recommandent d'utiliser des fonctions de sécurité multi-octets uniformément.

Tutoriel d'installation rapide PHP Tutoriel d'installation rapide PHP Jul 18, 2025 am 04:52 AM

Toinstallphpquickly, usexAmpPonWindowsorHomebrewonMacos.1.onwindows, downloadAndInstallxAmppp, selectComponents, startapache et placefilesInhtdocs.2.

See all articles