[英]How to move an uploaded file and upload the path into mySQL database? Using PHP
[英]How do we upload a file to mysql database using php
我需要將一個空靈捕獲文件上傳到MySQL數據庫中。 問題是,它不是通過html表單手動完成的。 因此,我不能使用enctype="multipart/form-data"
和$_FILES
上傳文件。
有沒有一種方法可以僅使用PHP將文件上傳到MySQL數據庫。
此致Mithun
“不,我有從我的應用程序動態生成的文件,需要自動上傳”
您將必須模擬POST請求-嘗試使用套接字,如以下示例所示:
<?php
$filename = 'C:/tmp/myphoto.jpg';
$handler = 'http://www.example.com/upload.php';
$field = 'image';
$res = send_file($filename, $handler, $field);
if ($res) {
echo 'done.';
} else {
echo 'something went wrong.';
}
?>
function send_file($fname, $handler, $field)
{
/* check if file exists */
if (!file_exists($fname)) {
echo 'file not found.';
return false;
}
/* get file's extension */
preg_match("/\.([^\.]+)$/", $fname, $matches);
$ext = $matches[1];
/* guess mimetype from file's extension
please add some more mimetypes here */
switch(strtolower($ext)) {
case "doc":
$mime = "application/msword";
break;
case "jpeg":
case "jpg":
case "jpe":
$mime = "image/jpeg";
break;
case "gif":
$mime = "image/gif";
break;
case "pdf":
$mime = "application/pdf";
break;
case "png":
$mime = "image/png";
break;
case "txt":
default:
$mime = "text/plain";
break;
}
/* get hostname and path of remote script */
$host = parse_url($handler, PHP_URL_HOST);
$path = parse_url($handler, PHP_URL_PATH);
/* setup request header and body */
$boundary = "---------" . str_replace(".", "", microtime());
$reqbody = "--$boundary\r\n"
. "Content-Disposition: form-data; name=\"$field\"; filename=\"$fname\"\r\n"
. "Content-Type: $mime\r\n\r\n"
. file_get_contents($fname) . "\r\n"
. "--$boundary--\r\n";
$bodylen = strlen($reqbody);
$reqhead = "POST $path HTTP/1.1\r\n"
. "Host: localhost\r\n"
. "Content-Type: multipart/form-data; boundary=$boundary\r\n"
. "Content-Length: $bodylen\r\n"
. "Connection: Close\r\n\r\n";
/* open socket connection to remote host on port 80 */
$fp = fsockopen($host, 80, $errno, $errmsg, 30);
/* check the connection */
if (!$fp) {
print "Cannot connect to $host!\n";
return false;
}
/* send request */
fwrite($fp, $reqhead);
fwrite($fp, $reqbody);
/* read response */
$res = "";
while(!feof($fp)) {
$res .= fgets($fp, 4096);
}
fclose($fp);
/* separate header and body */
$neck = strpos($res, "\r\n\r\n");
$head = substr($res, 0, $neck);
$body = substr($res, $neck+4);
/* check HTTP status */
$lines = explode("\r\n", $head);
preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $lines[0], $m);
$status = $m[2];
if ($status == 200) {
return(true);
} else {
return(false);
}
}
您如何創建文件? 我很確定如果沒有fopen('yourfilename.txt','w')會創建一個文件。 然后,您可以將文件名插入mysql數據庫。
也許很容易
$data = file_get_contents("yourFile.dat");
然后將“數據”變量插入數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.