|  | 
	                
  
    | 
	 
        Upload รูปลงฐานข้อมูลแล้วเชฟในโฟว์เดอร์แต่ไม่ขึ้นรูปครับ     |  
    |  |  
 
	
		|  |  |  |  |  
		|  |  | 
          
            | Code หน้าอัพโหลดรูป Code (PHP)
 
 <?php require_once('Connections/myconnect.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
mysql_select_db($database_myconnect, $myconnect);
$query_Recordset1 = "SELECT p_id FROM tbl_product";
$Recordset1 = mysql_query($query_Recordset1, $myconnect) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ฟอร์มเพิ่มสินค้า</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6"> <br />
      <h4 align="center"> ฟอร์มเพิ่มสินค้า </h4>
      <hr />
      <form action="add_product_db.php" method="POST" enctype="multipart/form-data"  name="addprd" class="form-horizontal" id="addprd">
        <div class="form-group">
          <div class="col-sm-12">
            <p> ชื่อสินค้า</p>
            <input type="text"  name="p_name" class="form-control" required placeholder="ชื่อสินค้า" />
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-12">
            <p> รายละเอียดสินค้า </p>
            <textarea name="p_detail" class="form-control"  rows="3"  required placeholder="รายละเอียดสินค้า"></textarea>
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-3">
            <p> ราคา (บาท) </p>
            <input type="number"  name="p_price" class="form-control" required placeholder="ราคา" />
          </div>
          <input name="pid" type="hidden" id="pid" value="<?php echo $totalRows_Recordset1+1; ?>" />
          <div class="col-sm-8 info">
            <p> ภาพสินค้า </p>
            <input type="file" name="p_img" class="form-control" />
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-12">
            <button type="submit" class="btn btn-primary" name="btnadd"> + เพิ่มสินค้า </button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>
 Code เก็บโฟว์เดอร์ที่เก็บ
 Code (PHP)
 
 <meta charset="UTF-8" />
<?php 
require_once('connect.php');
    //Set ว/ด/ป เวลา ให้เป็นของประเทศไทย
    date_default_timezone_set('Asia/Bangkok');
	//สร้างตัวแปรวันที่เพื่อเอาไปตั้งชื่อไฟล์ที่อัพโหลด
	$date1 = date("Ymd_His");
	//สร้างตัวแปรสุ่มตัวเลขเพื่อเอาไปตั้งชื่อไฟล์ที่อัพโหลดไม่ให้ชื่อไฟล์ซ้ำกัน
	$numrand = (mt_rand());
	
	//รับชื่อไฟล์จากฟอร์ม 
	$p_name = $_POST['p_name'];
	$p_detail = $_POST['p_detail'];
	$p_price = $_POST['p_price'];
	$p_img = (isset($_POST['p_img']) ? $_POST['p_img'] : '');
	$p_id = $_POST['pid'];
		
	$upload=$_FILES['p_img'];
	if($upload <> '') { 
	//โฟลเดอร์ที่เก็บไฟล์
	$path="img/";
	//ตัวขื่อกับนามสกุลภาพออกจากกัน
	$type = strrchr($_FILES['p_img']['name'],".");
	//ตั้งชื่อไฟล์ใหม่เป็น สุ่มตัวเลข+วันที่
	$newname =$numrand.$date1.$type;
	$path_copy=$path.$newname;
	$path_link="img/".$newname;
	//คัดลอกไฟล์ไปยังโฟลเดอร์
	move_uploaded_file($_FILES['p_img']['tmp_name'],$path_copy);  
		
	
	}
			 $sql = "INSERT INTO tbl_product 
					(p_id,
					p_name, 
					p_detail, 
					p_price, 
					p_img) 
					VALUES
					('$p_id',
					 '$p_name',
					 '$p_detail',
					'$p_price',
					'$newname')";
		
		$result = mysql_db_query($database_condb, $sql) or die ("Error in query: $sql " . mysql_error());
	mysql_close();
	if($result){
   
			echo "<script type='text/javascript'>";
			echo  "alert('เพิ่มเรียบร้อย');";
			echo "window.location='showindex1.php';";
			echo "</script>";
	  }
	  else{
		    echo "<script type='text/javascript'>";
			echo  "alert('error');";
				echo "window.location='showindex1.php';";
			echo "</script>";
	  }
	
	
 ?>
 
  
 
 ข้อมูลในฐานข้อมูล
 
  
 
 
 Tag : PHP, MySQL, HTML
 
 
 |  
            |  |  
            | 
              
                |  |  |  |  
                |  | 
                    
                      | Date :
                          2019-05-21 19:18:02 | By :
                          Nirawit | View :
                          2098 | Reply :
                          15 |  |  |  
                |  |  |  |  |  
            |  |  
		            |  |  
		|  |  |  |  |  
  
    | 
 
 
 
        
          |  |  |  |  |  
          |  |  | 
            
              | ถ้าไม่เข้าใจจริงๆ ต้องค่อย ๆ อ่านและทำความเข้าใจครับ ต้องจับประเด็นให้ได้เพราะพวกพี่จะไม่บอกทั้งหมดเพราะอยากให้คนที่ได้เรียนรู้หัดคิดและวิเคราะห์เองครับ
 
 1.พี่เขาแนะนำว่าให้เปิดไฟล์ภาพด้วย text Editor อาจจะเป็น notepad++,Edit Plus หรืออื่นๆ เวลาเปิดภาพก็ให้คลิกขวาที่ภาพแล้วก็รันด้วยโปรแกรม text Editor ครับ
 ลองทำที่ภาพที่เราอัพโหลดขึ้นครับ
 ถ้าภาพนั้นขึ้นแบบนี้
 
 
  
 แสดงว่ามีข้อมูลของภาพครับ ถ้าว่างเปล่าแสดงว่าภาพนั้นยังไงก็เปิดไม่ได้เพราะไม่มีข้อมูลของภาพนั้นเอง
 
 2.พี่เขาบอกว่าให้เปิดแสดงนามสกุลไฟล์ครับ อย่างเช่นของคุณภาพสีฟ้าๆนั้นจะมีแค่ตัวเลข 123456 หากเราเป็นฝั่งทางด้านผู้พัฒนาระบบแล้วสิ่งที่ต้องมองเห็นต้องมากกว่า ผู้ใช้งานทั่วไปครับ
 เราต้องมองเห็นเป็น 123456.jpg หรือนามสกุลอื่นก็ว่าไป
 เพราะบางที่ภาพที่คุณอัพโหลดอาจชื่อว่า 123456.jpg.jpg ประมาณนี้ครับ
 
 หากใช้ win10 ลองตั้งค่าแบบนี้ดูครับ
 
 https://www.it24hrs.com/2016/windows-10-windows-photo-viewer/
 
 |  
              | 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            2019-05-22 09:06:30 | By :
                            nobetaking |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  
 
 
 
        
          |  |  |  |  |  
          |  |  | 
            
              | ตัวอย่างโค้ด upload ที่ผมทำนะ ลองดูละกัน. 
 
 Code (PHP)
 
 <form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="name" value="someFormValue">
    <input type="file" name="image">
    <button type="submit">Upload</button>
</form>
Max file size: <?php echo ini_get('upload_max_filesize') . '<br>'; ?> 
form.php
 
 
 
 
 
 Code (PHP)
 
 <?php
/**
 * @link https://www.php.net/manual/en/features.file-upload.post-method.php $_FILES array reference.
 * @link https://www.php.net/manual/en/features.file-upload.errors.php $_FILES error reference.
 * @link https://www.php.net/manual/en/function.finfo-file.php Finfo (file info) reference.
 * @link https://www.php.net/manual/en/function.filesize.php File size function reference.
 * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types Mime types reference.
 */
if ($_POST) {
    // if method post.
    $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);// ตย.สมมุติกรณีมีฟอร์มฟิลด์อื่นๆมาด้วย.
    // กำหนดตัวแปรสำหรับใช้ตรวจ error ก่อนทำอื่นๆ
    $errorFound = false;
    if (isset($_FILES['image'])) {
        // ถ้ามีการ upload.
        if (
            isset($_FILES['image']['error']) && 
            $_FILES['image']['error'] !== UPLOAD_ERR_OK && 
            $_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE// ถ้าไม่บังคับ upload ก็เอาไว้ ถ้าบังคับก็เอาออก
        ) {
            // ถ้ามี upload error.
            switch ($_FILES['image']['error']) {
                case UPLOAD_ERR_INI_SIZE:
                    $errorMessage = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                    break;
                case UPLOAD_ERR_FORM_SIZE:
                    $errorMessage = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $errorMessage = "The uploaded file was only partially uploaded";
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $errorMessage = "No file was uploaded";
                    break; 
                case UPLOAD_ERR_NO_TMP_DIR:
                    $errorMessage = "Missing a temporary folder";
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $errorMessage = "Failed to write file to disk";
                    break;
                case UPLOAD_ERR_EXTENSION:
                    $errorMessage = "File upload stopped by extension";
                    break;
                default:
                    $errorMessage = "Unknown upload error";
                    break;
            }
            $errorFound = true;
        } elseif ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
            // ถ้าไม่มี upload error.
            // ดึงข้อมูลไฟล์จากของจริง เพื่อใช้ตรวจสอบ ไม่ใช่เอาจาก $_FILES ซึ่งอาจถูกปลอมได้.
            $Finfo = new finfo();
            $fileMime = $Finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME_TYPE);// xxxx/xxxx
            $fileSize = filesize($_FILES['image']['tmp_name']);// in bytes
            $allowedMimes = ['image/gif', 'image/jpeg', 'image/png'];// gif, jpg, jpeg, png.
            unset($Finfo);
            
            if ($fileSize > 1024000) {
                $errorFound = true;
                $errorMessage = 'ขนาดไฟล์ใหญ่เกินกว่า 1 MB.';
            } elseif (!in_array(strtolower($fileMime), $allowedMimes)) {
                $errorFound = true;
                $errorMessage = 'กรุณา upload รูปภาพเท่านั้น.';
            } else {
                // ผ่านเงื่อนไขการตรวจหมดแล้ว, move upload ได้เลย.
                $expUploadFile = explode('.', $_FILES['image']['name']);
                $fileExt = '.' . $expUploadFile[count($expUploadFile) - 1];
                unset($expUploadFile);
                // กำหนดชื่อไฟล์ใหม่ จะใส่ path ไปตรงไหนก็กำหนดตรงนี้
                $newUploadFileName = md5(time()) . $fileExt;
                unset($fileExt);
                $uploadResult = move_uploaded_file($_FILES['image']['tmp_name'], $newUploadFileName);
                if ($uploadResult !== true) {
                    $errorFound = true;
                    $errorMessage = 'ไม่สามารถอัพโหลดได้.';// จะมี warning ให้เปิดแสดง error.
                }
                unset($uploadResult);
            }
            unset($allowedMimes, $Finfo, $fileMime, $fileSize);
        }// endif; ตรวจ upload error.
    }// endif; ถ้ามีการ upload.
    if ($errorFound === false) {
        // ถ้าผ่านการตรวจแล้ว ไม่มี error
        // ทำอย่างอื่น เช่น insert, update DB.
        if (isset($newUploadFileName)) {
            // ถ้ามีการ upload ด้วย กำหนดค่าเพิ่มเติม.
            $data['image'] = $newUploadFileName;
            unset($newUploadFileName);
            // ทดลองเฉยๆ upload ได้แล้วก็ลบทิ้ง.
            unlink($data['image']);
        }
        // INSERT/UPDATE DB ก็ตรงนี้
        print_r($data);// for debug only.
    } else {
        // ถ้าผ่านการตรวจแต่มี error
        if (isset($errorMessage)) {
            // ถ้ามีข้อความ error.
            // จะแสดงธรรมดา (echo) ก็ได้, trigger error ก็ได้, หรือจะใช้ throw exception ก็ได้.
            trigger_error($errorMessage, E_USER_ERROR);
        }
        exit();// หยุดทำงาน หรือจะไม่หยุด แล้วแต่.
    }
}
upload.php
 
 
 
 ถ้า move upload สำเร็จแล้วภาพมีก็คือผ่านแล้ว ค่อยไปทำ insert/update db ต่อ
 
 |  
              | 
 ประวัติการแก้ไข
 2019-05-23 04:27:26
 2019-05-23 04:27:53
 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            2019-05-23 04:25:32 | By :
                            mr.v |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  
 
 
        
          |  |  |  |  |  
          |  |  | 
            
              | ลองเปลี่ยนเป็นแบบนี้ดูหรือยังครับ 
 Code (PHP)
 
 $allowedMimes = [".gif",".jpg",".jpeg",".png"];
 
 อีกอย่างโค้ดที่พี่เขาให้มาเหมือนเป็นการ part ในโฟลเดอร์ของคุณมี
 
 image/gif หรือ ป่าว
 
 ถ้าอ่านที่ตัวแปล มันจะได้ความหมายว่า การอนุญาต
 
 ลองดูครับ
 
 |  
              | 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            2019-05-23 10:27:29 | By :
                            nobetaking |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  
 
        
          |  |  |  |  |  
          |  |  | 
            
              | allowedMimes ใช้ image/jpeg อะไรแบบนี้ถูกแล้วครับ เพราะมันคือ mime type ไม่ใช่ extension. ที่มัน error คุณจขกท.ก็ควรเอา error มาด้วยว่าคืออะไร คนช่วยจะได้รู้และตอบได้ตรงและไว ไม่ใช่ให้มานั่งเดาเอา
 
 ก็เดาว่า error syntax ผิดเพราะคุณใช้ php 5.3 ซึ่งต้องเปลี่ยนจาก short array เป็นแบบเต็ม คือจาก ['image/jpeg', '...']; เป็น array('image/jpeg', '...');
 
 https://www.php.net/manual/en/language.types.array.php
 
 |  
              | 
 ประวัติการแก้ไข
 2019-05-23 10:50:33
 2019-05-23 10:51:04
 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            2019-05-23 10:47:59 | By :
                            mr.v |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  
 
        
          |  |  |  |  |  
          |  |  | 
            
              |  ตอบความคิดเห็นที่ : 9 เขียนโดย : mr.v เมื่อวันที่ 2019-05-23 10:47:59 
 รายละเอียดของการตอบ ::
 CODE ไม่ error ละครับแต่ติดตรงพอรันแล้ว
  Code (PHP) <?php
/**
 * @link https://www.php.net/manual/en/features.file-upload.post-method.php $_FILES array reference.
 * @link https://www.php.net/manual/en/features.file-upload.errors.php $_FILES error reference.
 * @link https://www.php.net/manual/en/function.finfo-file.php Finfo (file info) reference.
 * @link https://www.php.net/manual/en/function.filesize.php File size function reference.
 * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types Mime types reference.
 */
if ($_POST) {
    // if method post.
    $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);// ตย.สมมุติกรณีมีฟอร์มฟิลด์อื่นๆมาด้วย.
    // กำหนดตัวแปรสำหรับใช้ตรวจ error ก่อนทำอื่นๆ
    $errorFound = false;
    if (isset($_FILES['image'])) {
        // ถ้ามีการ upload.
        if (
            isset($_FILES['image']['error']) && 
            $_FILES['image']['error'] !== UPLOAD_ERR_OK && 
            $_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE// ถ้าไม่บังคับ upload ก็เอาไว้ ถ้าบังคับก็เอาออก
        ) {
            // ถ้ามี upload error.
            switch ($_FILES['image']['error']) {
                case UPLOAD_ERR_INI_SIZE:
                    $errorMessage = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                    break;
                case UPLOAD_ERR_FORM_SIZE:
                    $errorMessage = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $errorMessage = "The uploaded file was only partially uploaded";
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $errorMessage = "No file was uploaded";
                    break; 
                case UPLOAD_ERR_NO_TMP_DIR:
                    $errorMessage = "Missing a temporary folder";
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $errorMessage = "Failed to write file to disk";
                    break;
                case UPLOAD_ERR_EXTENSION:
                    $errorMessage = "File upload stopped by extension";
                    break;
                default:
                    $errorMessage = "Unknown upload error";
                    break;
            }
            $errorFound = true;
        } elseif ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
            // ถ้าไม่มี upload error.
            // ดึงข้อมูลไฟล์จากของจริง เพื่อใช้ตรวจสอบ ไม่ใช่เอาจาก $_FILES ซึ่งอาจถูกปลอมได้.
            $Finfo = new finfo();
            $fileMime = $Finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME_TYPE);// xxxx/xxxx
            $fileSize = filesize($_FILES['image']['tmp_name']);// in bytes
            $allowedMimes = array('image/jpeg', '...');;// gif, jpg, jpeg, png.
            unset($Finfo);
            
            if ($fileSize > 1024000) {
                $errorFound = true;
                $errorMessage = 'ขนาดไฟล์ใหญ่เกินกว่า 1 MB.';
            } elseif (!in_array(strtolower($fileMime), $allowedMimes)) {
                $errorFound = true;
                $errorMessage = 'กรุณา upload รูปภาพเท่านั้น.';
            } else {
                // ผ่านเงื่อนไขการตรวจหมดแล้ว, move upload ได้เลย.
                $expUploadFile = explode('.', $_FILES['image']['name']);
                $fileExt = '.' . $expUploadFile[count($expUploadFile) - 1];
                unset($expUploadFile);
                // กำหนดชื่อไฟล์ใหม่ จะใส่ path ไปตรงไหนก็กำหนดตรงนี้
                $newUploadFileName = md5(time()) . $fileExt;
                unset($fileExt);
                $uploadResult = move_uploaded_file($_FILES['image']['tmp_name'], $newUploadFileName);
                if ($uploadResult !== true) {
                    $errorFound = true;
                    $errorMessage = 'ไม่สามารถอัพโหลดได้.';// จะมี warning ให้เปิดแสดง error.
                }
                unset($uploadResult);
            }
            unset($allowedMimes, $Finfo, $fileMime, $fileSize);
        }// endif; ตรวจ upload error.
    }// endif; ถ้ามีการ upload.
    if ($errorFound === false) {
        // ถ้าผ่านการตรวจแล้ว ไม่มี error
        // ทำอย่างอื่น เช่น insert, update DB.
        if (isset($newUploadFileName)) {
            // ถ้ามีการ upload ด้วย กำหนดค่าเพิ่มเติม.
            $data['image'] = $newUploadFileName;
            unset($newUploadFileName);
            // ทดลองเฉยๆ upload ได้แล้วก็ลบทิ้ง.
            unlink($data['image']);
        }
        // INSERT/UPDATE DB ก็ตรงนี้
        print_r($data);// for debug only.
    } else {
        // ถ้าผ่านการตรวจแต่มี error
        if (isset($errorMessage)) {
            // ถ้ามีข้อความ error.
            // จะแสดงธรรมดา (echo) ก็ได้, trigger error ก็ได้, หรือจะใช้ throw exception ก็ได้.
            trigger_error($errorMessage, E_USER_ERROR);
        }
        exit();// หยุดทำงาน หรือจะไม่หยุด แล้วแต่.
    }
}
 |  
              | 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            2019-05-23 11:02:32 | By :
                            Nirawit |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  
 
 
 
 
 
        
          |  |  |  |  |  
          |  |  | 
            
              | ลองเปิดไฟล์ดูครับ ถ้ามีภาพก็คือได้แล้ว 
 |  
              | 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            2019-05-23 11:36:08 | By :
                            mr.v |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  |  |