Im trying to upload a csv file then insert its contents into my database. I can successfully upload the file but I am having an error in my insert query. Here's a part of the code:
//Upload the file
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
$files = pathinfo($file_path,PATHINFO_EXTENSION);
$uploadstatus = 1;
$found = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// check if the file being submitted is a csv file
$file_type=$_FILES['uploaded_file']['type'];
if ($files=="CSV") {
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$uploadstatus = 1;
echo "<script type='text/javascript'>alert('File upload successful.')</script>";
} else{
echo "<script type='text/javascript'>alert('File upload failed. Please check then re-upload file.')</script>";
}
}
$filename = $_FILES['uploaded_file']['name'];
if (file_exists($file_path.$filename) && $uploadstatus) {
if (!$found) {
include('conn.php');
//get the file
$handle = fopen($filename,"r");
do {
if (isset($data[0])) {
$data0 = mysql_real_escape_string($data[0]); //rcode
$data1 = mysql_real_escape_string($data[1]); //pcode
$data2 = mysql_real_escape_string($data[2]); //mcode
$data3 = mysql_real_escape_string($data[3]); //bcode
$data4 = mysql_real_escape_string($data[4]); //ecode
$data5 = mysql_real_escape_string($data[5]); //filetype
$data6 = mysql_real_escape_string($data[6]); //rec_count
$data7 = mysql_real_escape_string($data[7]); //gs_count
$data8 = mysql_real_escape_string($data[8]); //be_count
$data9 = mysql_real_escape_string($data[9]); //qc_count
$data10 = mysql_real_escape_string($data[10]); //tt_count
$data11 = mysql_real_escape_string($data[11]); //rm_count
$data12 = mysql_real_escape_string($data[12]); //sc_count
$data13 = mysql_real_escape_string($data[13]); //in_count
$data14 = mysql_real_escape_string($data[14]); //en_count
$data15 = mysql_real_escape_string($data[15]); //co_count
$data16 = mysql_real_escape_string($data[16]); //ve_count
$data17 = mysql_real_escape_string($data[17]); //editing
$query = "INSERT INTO tbltest (rcode,pcode,mcode,bcode,ecode,filetype,rec_count,gs_count,be_count,qc_count,tt_count,rm_count,sc_count,in_count,en_count,co_count,ve_count,ed_count)
VALUES ('$data0','$data1','$data2','$data3','$data4','$data5','$data6','$data7','$data8','$data9','$data10','$data11','$data12','$data13','$data14','$data15','$data16','$data17') ON DUPLICATE KEY UPDATE rec_count=values(rec_count),gs_count=values(gs_count),be_count=values(be_count),qc_count=values(qc_count),tt_count=values(tt_count),rm_count=values(rm_count),sc_count=values(sc_count),in_count=values(in_count),en_count=values(en_count),co_count=values(co_count),ve_count=values(ve_count),ed_count=values(ed_count)";
mysql_query ($query,$connect);
}
} while ($data = fgetcsv($handle,1000,"|"));
}
}
}
The result of the echo is the correct file, but I get an error that says fopen(): failed to open stream: No such file or directory and fgetcsv() expects parameter 1 to be resource, boolean given.
You're trying to open a file that doesn't exist.
The function move_uploaded_file does exactly what it says - it moves a file that has been uploaded. Once you've called this function the file no longer exists in the temporary upload area.
Change this bit:
$filename = $_FILES['uploaded_file']['name'];
if (file_exists($file_path.$filename) && $uploadstatus) {
if (!$found) {
include('conn.php');
//get the file
$handle = fopen($filename,"r");
to:
$filename = $file_path;
if (file_exists($filename) && $uploadstatus) {
if (!$found) {
include('conn.php');
//get the file
$handle = fopen($filename,"r");
files are NOT stored under their original name.
This is the actual file:
$_FILES['userfile']['tmp_name']
Read more in the fine manual:
http://be2.php.net/manual/en/features.file-upload.post-method.php
Related
I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;
Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer
<?php
require_once("database.php");
if(#$_POST['upload']) {
$file_name = $_FILES['cvs']['name'];
$file_type = $_FILES['cvs']['type'];
$file_temp_loc = $_FILES['cvs']['tmp_name'];
$file_error_msg = $_FILES['cvs']['error'];
$file_size = $_FILES['cvs']['size'];
/* 1. file upload handling */
if(!$file_temp_loc) { // if not file selected
echo "Error: please browse for a file before clicking the upload button.";
exit();
}
if(!preg_match("/\.(csv)$/i", $file_name)) { // check file extension
echo 'Error: your file is not CSV.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
if($file_size > 5242880) { // file check size
echo "Error: you file was larger than 5 Megabytes in size.";
exit();
}
if($file_error_msg == 1) { //
echo "Error: an error occured while processing the file, try agian.";
exit();
}
$move_file = move_uploaded_file($file_temp_loc, "\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/{$file_name}"); // temp loc, file name
if($move_file != true) { // if not move to the temp location
echo 'Error: File not uploaded, try again.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
$csvFile = '\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/'.$file_name;
$csvFileLength = filesize($csvFile);
$csvSeparator = ",";
$handle = fopen($csvFile, 'r');
$count = '';
while($data = fgetcsv($handle, $csvFileLength, $csvSeparator)) { // while for each row
$count += count($data[0]); // count imported
mysql_query("INSERT INTO `csv_data` (`product_title`, `product_price`) VALUES ( '$data[0]', '$data[1]' )");
}
fclose($handle);
unlink($csvFile); // delete cvs after imported
header('Location: index.php?success=1&count='.$count);
exit();
}
?>
please check the spelling of file field's name .. it must be csv in html and you called it cvs
$file_name = $_FILES['csv']['name'];
$file_type = $_FILES['csv']['type'];
$file_temp_loc = $_FILES['csv']['tmp_name'];
$file_error_msg = $_FILES['csv']['error'];
$file_size = $_FILES['csv']['size'];
i'm trying to create multiple uploading with BLOB.
The above code gives me the following error
Warning: fopen(C:\xampp\tmp\php4FC4.tmp): failed to open stream: No such file or directory
PHP script
$jumlah_file = count($_FILES['userfile']['name']);
$path = pathinfo($_SERVER['PHP_SELF']);
for ($i = 0; $i < $jumlah_file; $i++)
{
$tmp_file = $_FILES['userfile']['tmp_name'][$i];
$filetype = $_FILES['userfile']['type'][$i];
$filesize = $_FILES['userfile']['size'][$i];
$filename = $_FILES['userfile']['name'][$i];
$destination = $path['dirname'].
'/data/'.$filename;
move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'].$destination);
}
$fp = fopen($tmp_file, 'r'); // ERROR LINE
$content = fread($fp, filesize($tmp_file));
$content = addslashes($content);
fclose($fp);
if (!get_magic_quotes_gpc())
{
$fileName = addslashes($filename);
}
$query = mysql_query("INSERT INTO `konveksi`.`foto` (`id_foto`, `id_daftar`, `id_pesanan`, `foto`) VALUES (NULL, '15', '1','$content');");
mysql_query($query) or die('Error, query failed');
what must I do? Please excuse me if this is stupid question, I am very new to PHP.
You already moved the file using move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'].$destination); before the $fp = fopen($tmp_file, 'r');. Afterwards the file is located elsewhere.
The correct code is :
$jumlah_file = count($_FILES['userfile']['name']);
$path = pathinfo($_SERVER['PHP_SELF']);
for ($i = 0; $i < $jumlah_file; $i++)
{
$tmp_file = $_FILES['userfile']['tmp_name'][$i];
$filetype = $_FILES['userfile']['type'][$i];
$filesize = $_FILES['userfile']['size'][$i];
$filename = $_FILES['userfile']['name'][$i];
$destination = $path['dirname'].
'/data/'.$filename;
$fp = fopen($tmp_file, 'r');
$content = fread($fp, filesize($tmp_file));
$content = addslashes($content);
fclose($fp);
move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'].$destination);
}
if (!get_magic_quotes_gpc())
{
$fileName = addslashes($filename);
}
$query = mysql_query("INSERT INTO `konveksi`.`foto` (`id_foto`, `id_daftar`, `id_pesanan`, `foto`) VALUES (NULL, '15', '1','$content');");
mysql_query($query) or die('Error, query failed');
I made a simple script to insert files as BLOB (mediumblob) in MySQL Database.
The script works fine, the file is uploaded and saved into the table but when I download the file and I try to open it, it says: "File type HTML document (text/html) is not supported"!
This means there was an error while saving the file's type!
Here is my code, please tell me what can be wrong in it:
upload.php :
if (isset($_POST['upload']))
{
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$p = $cnx->prepare('INSERT INTO commandes (name, size, type, content) VALUES(:name, :size, :type, :content)');
$p->execute(array('name'=>$fileName, 'size'=>$fileSize, 'type'=>$fileType, 'content'=>$content));
echo "<br>File $fileName uploaded<br>";
}
}
Download.php :
$p = $cnx->prepare('SELECT cmd_id, name FROM commandes');
$p->setFetchMode(PDO::FETCH_OBJ);
$p->execute();
if($p->rowCount() == 0)
{
echo "0 Element <br />";
}
else
{
while($data = $p->fetch())
{
?>
<?php echo $data->name;?> <br>
<?php
}
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = $cnx->prepare('SELECT * FROM commandes WHERE cmd_id = :cmd_id');
$q->setFetchMode(PDO::FETCH_OBJ);
$q->execute(array('cmd_id'=>$id));
while($getFile = $q->fetch())
{
header("Content-length: $getFile->size");
header("Content-type: $getFile->type");
header("Content-Disposition: download; filename=$getFile->name");
echo $getFile->pdf;
exit;
}
}
Thank you!
What is the output for the response headers?
Can you ensure that "Content-type" is "Content-Type"
Also, using a debugger to inspect the response is really valuable.
http://fiddler2.com/get-fiddler