2009-09-30 4 views
0

Мне нужно загрузить файл с эфирным захватом в базу данных MySQL. Проблема в том, что это не делается вручную через html-форму. Следовательно, я не могу использовать enctype="multipart/form-data" и $_FILES для загрузки файла.Как загрузить файл в базу данных mysql с помощью php

Есть ли способ загрузить файл с использованием PHP в базу данных MySQL.

С уважением, Митхун

+0

Не сделано через форму html? Тогда как он загружается? – Graviton

+0

Что мешает вам загружать форму? – nduplessis

+0

Нет У меня есть файлы, созданные динамически из моего приложения, которые мне нужно загрузить автоматически. Следовательно, я не могу использовать html-форму. – Vidya

ответ

0

«Нет у меня есть файлы, созданные динамически из моего приложения, которые мне нужно загрузить автоматически»

Вы должны имитировать 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); 
} 
} 
0

Как вы создаете файлы ? Я уверен, что использование fopen ('yourfilename.txt', 'w') создаст файл, если его нет. Затем вы можете просто вставить имя файла в свою базу данных mysql.

0

может быть что-то простое;

$data = file_get_contents("yourFile.dat"); 

затем введите переменную data в базу данных.

Смежные вопросы