This is my code
$actual_name = pathinfo($filename,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$filetype=$_FILES['file']['type'];
$target="../wp-content/themes/childtheme/img/";
if($filetype=='image/jpeg' or $filetype=='image/png' or
$filetype=='image/gif')
{
$i = 1;
while(file_exists($target.$actual_name.".".$extension)){
$actual_name = $original_name.$i;
$filename = $actual_name.".".$extension;
$i++;
}
$target = $target.basename( $filename ) ;
move_uploaded_file($_FILES['file']['tmp_name'],$target);
$insert="INSERT INTO EnterSchool(SliderImg ) VALUES('".$target."' )";
if (mysqli_query($db, $insert)) {
echo "saved ";
}
else {
echo "Error: " . $insert . "" . mysqli_error($db);
}
$db->close();
}}
html
<input type="file" name="file" id="file" >
Related
I'm a PHP beginner and i managed to muscle up a code which has a person upload up to 4 documents to a designated folder on a server. I'm now having trouble writing code which takes these 4 document names and adds them to that person's column with the rest of input data. I believe the right approach is to go with a "foreach" loop which increments variable name every time it goes through uploaded file names. I've tried doing this with $documentname[$i] = $file_name; but it's not working.
This is what I have so far:
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
$i=1;
foreach ($_FILES['files']['tmp_name'] as $key => $value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$documentname[$i] = $file_name;
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
echo "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
} else {
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
echo "No files selected.";
}}
And this is the sql code:
if (isset($_POST['signup'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$documentname1 = $_POST['documentname1'];
$documentname2 = $_POST['documentname2'];
$documentname3 = $_POST['documentname3'];
$documentname4 = $_POST['documentname4'];
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
So the question is: is it possible to iterate through the uploaded files name array and assign each file name a variable like #documentname1,#documentname2,... to write these names in the database?
Thank you in advance!
Change your code to look like this. And also use prepared statement - PDO
if (isset($_POST['signup'])) {
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countfiles = count($_FILES['files']['name']);
$doc_name = [];
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
for ($i=0;$i<$countfiles;$i++) {
$file_tmpname = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$doc_name[] += $_FILES['files']['name'][$i];
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
$error[] = "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
$success[] = "{$file_name} uspješno uploadan <br />";
} else {
$error[] = "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
$error[] = "Error uploading {$file_name} ";
$error[] = "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
$error[] = "No files selected.";
}}
if (!isset($error)) {
$documentname1 = $doc_name[0]
$documentname2 = $doc_name[1]
$documentname3 = $doc_name[2]
$documentname4 = $doc_name[3]
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
}
}
to show errors on your html
if(isset($error)){
foreach($error as $error){
echo '<div class="alert alert-danger" role="alert">
<button class="close" data-dismiss="alert"></button>' .$error.'<br /> </div>';
}
}
to show success
if(isset($success)){
foreach($success as $success){
echo '<div class="alert alert-success" role="alert">
<button class="close" data-dismiss="alert"></button>' .$success.'<br /> </div>';
}
}
I just extend a column on my db table. So I try to put data on that table. I have 10 more column on that table. There is a column name _source_ and if its value become 1 then my new column input data correctly. but if its value became 2 then my new column show null. I check and re-check my function from last two days. I can't understand what I am missing!
Here is my full function PHP code:
function regular_upload($inputname, $ftp_server){
global $site_url;
$ok=1;
$upload_name = $inputname;
// AICI VERIFICAM DACA A FOST ADAUGATA O FILA
if (!isset($_FILES[$upload_name])) {
//header('Location: index.php');
echo 'No upload found in \$_FILES for ' . $upload_name;
$ok=0;
//exit();
} else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) {
// echo $uploadErrors[$_FILES[$upload_name]['error']];
echo "<p class='error'>No files</p>";
$ok=0;
//exit();
} else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name'])) {
echo "<p class='error'>Upload failed is_uploaded_file test.</p>";
$ok=0;
//exit();
} else if (!isset($_FILES[$upload_name]['name'])) {
$ok=0;
echo "<p class='error'>File has no name.</p>";
//exit();
}
// DACA ADULT NU E NUMERIC DIEEEEE
if (isset($_POST['adult']) && is_numeric($_POST['adult']) && $_POST['adult'] >= 0 && $_POST['adult'] <= 1) {
$adult = $_POST['adult'];
} else {
die("You didn't specify if your file(s) are Adult or Non-Adult");
}
if(is_numeric($_POST['thumb_size_contaner'])) {
$thumbnail_size = $_POST['thumb_size_contaner'];
} else {
die("Injection detected");
}
if($ok == 1) {
// verificare tipul de imagini - un fel de whitelist
$imageinfo = getimagesize($_FILES[$upload_name]['tmp_name']);
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpg') {
echo "<p class='error'>Sorry, we only accept GIF, JPEG and PNG images</p>";
$ok=0;
//exit();
}
}
if($ok == 1) {
// blacklist ce nu tre sa fie
$filename = strtolower($_FILES[$upload_name]['name']);
$blacklist = array('php', 'php3', 'php4', 'phtml','exe'); #example of black list
foreach ($blacklist as $item) {
if(preg_match("/$item\$/i", $filename)) {
echo "<p class='error'>We do not allow uploading PHP files</p>";
$ok=0;
//exit();
}
}
}
if($ok == 1) {
// de aici setam dimensiunea maxima a imaginii
list($width, $height, $type, $attr) = getimagesize($_FILES[$upload_name]['tmp_name']);
if ($width > MAX_UPLOAD_WIDTH || $height > MAX_UPLOAD_HEIGHT)
{
echo "<p class='error'>Maximum width and height exceeded. Please upload images below ".MAX_UPLOAD_WIDTH." x ".MAX_UPLOAD_HEIGHT." px size</p>";
$ok=0;
//exit();
}
}
if($ok == 1) {
$q = "SELECT img, thumb FROM sources WHERE id = '1'";
$result = mysql_query($q);
if(mysql_num_rows($result) > 0) {
$rowSources = mysql_fetch_array($result);
} else {
die("Something went wrong : ". mysql_error());
}
$data_year = date('Y');
$data_month = date('m');
$data_day = date('d');
if($ftp_server == 0) {
$dir = $rowSources['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb = $rowSources['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
if(!file_exists($dir) OR !is_dir($dir)){
mkdir($dir, 0777, true);
}
if(!file_exists($dirthumb) OR !is_dir($dirthumb)){
mkdir($dirthumb, 0777, true);
}
} else {
$q = "SELECT * FROM ftp_logins
INNER JOIN sources ON ftp_logins.source_id = sources.id
WHERE ftp_logins.id = $ftp_server
";
$result = mysql_query($q);
if(!$result) {
echo mysql_error();
}
$rowFTP = mysql_fetch_assoc($result);
$dir = $rowFTP['img'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dir2 = $rowFTP['img2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb = $rowFTP['thumb'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$dirthumb2 = $rowFTP['thumb2'] . "/" . $data_year . "/" . $data_month . "/" . "$data_day";
$FTP = new FTP();
$FTP->connect($rowFTP['host'], $rowFTP['user'], $rowFTP['pass']);
global $ftp_conn_id;
if(!$FTP->directory_exists($ftp_conn_id, "/". $dir)) {
$FTP->mkdir_recusive($ftp_conn_id, "/". $dir);
}
if(!$FTP->directory_exists($ftp_conn_id, "/". $dirthumb)) {
$FTP->mkdir_recusive($ftp_conn_id, "/". $dirthumb);
}
}
//$uniquenumber = uniqid('', true);
$uniquenumber = uniqid();
$view_id = uniqid();
$target = $dir;
$extension = pathinfo($_FILES[$upload_name]['name'], PATHINFO_EXTENSION);
//$filename = $_FILES['uploaded']['name'];
$nameimage = $uniquenumber . "." . $extension;
$target = $target . "/" . $uniquenumber . "." . $extension;
$uploaded_size = $_FILES[$upload_name]['size'];
//echo $uploaded_size;
//This is our size condition
if ($uploaded_size > MAX_UPLOAD_SIZE*1024) { // IN KB
echo "<p class='error'>Your file is too large.</p>";
$ok=0;
}
}
//This is our limit file type condition
if ($ok==0) {
echo "<p class='error'>Sorry your file was not uploaded </p>";
} else {
//If everything is ok we try to upload it
if($ftp_server == 0) {
if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $target)) {
echo "<p class='success'> ". basename( $_FILES[$upload_name]['name']). " has been succesfuly uploaded </p>";
//aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
$thumbnail_size_final = 180;
switch($thumbnail_size) {
case 1:
$thumbnail_size_final = SMALL_THUMB;
break;
case 2:
$thumbnail_size_final = MEDIUM_THUMB;
break;
case 3;
$thumbnail_size_final = LARGE_THUMB;
break;
case 4;
$thumbnail_size_final = LARGER_THUMB;
break;
case 5;
$thumbnail_size_final = COVER_THUMB;
break;
}
// aici se face resizeul imaginilor
$target_thumb = $dirthumb;
$resizeuploadpatch = $target_thumb . "/" . $uniquenumber . "." . $extension ;
$image = new SimpleImage();
$image->load($target);
if($width > $thumbnail_size_final) {
$image->resizeToWidth($thumbnail_size_final);
}
$image->save($resizeuploadpatch);
$data = date('Y-m-d');
//$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
//$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;
//INSERARE IN BAZA DE DATE
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
} else {
$user_id = 0;
}
if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
$qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
$resultQg = mysql_query($qG);
if($resultQg && mysql_num_rows($resultQg) > 0){
$gallery = $_POST['set_gallery'];
} else {
$gallery = 0;
}
} else {
$gallery = 0;
}
$titlename = basename( $_FILES[$upload_name]['name']);
$titlename2 = $view_id;
$q = "INSERT INTO images (`id_user`, `titlename`, `gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
('{$user_id}', '{$titlename}', '{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
$result = mysql_query($q);
$id_inserted = mysql_insert_id();
if(!$result) {
die("Database error : " . mysql_error());
}
if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
$download_links = filter($_POST['download_links']);
$download_links = trim($download_links);
$q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
$result = mysql_query($q);
if(!$result) {
die("Database error : " . mysql_error());
}
}
?>
<div id="uploadedimage">
<a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo $site_url . "/" . $resizeuploadpatch; ?>" alt="uploaded_image" /></a>
</div>
<div id="uploadcodes">
<label>BB Code:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL] "; ?>">
<br /> <br />
<label>HTML:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a> "; ?>">
<br /> <br />
<label>Link:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
<?php
if(DIRECT_LINK_SHOW == 1) {
echo "
<br /> <br />
<label>Direct Link to image:</label><br />
<input type='text' onclick='this.select();' value='{$site_url}/{$dir}/{$nameimage}'>
";
}
?>
</div>
<?php
global $BBCode_global;
global $HTMLCode_global;
global $DirectLink_global;
global $DirectLinkToImg_global;
$BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]";
$HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a>";
$DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
$DirectLinkToImg_global[] = "{$site_url}/{$dir}/{$nameimage}";
echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$site_url}/{$resizeuploadpatch}[/IMG][/URL]</div>";
echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$site_url}/{$resizeuploadpatch}' alt='image' /></a></div>";
echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$site_url}/{$dir}/{$nameimage}</div>";
} else {
echo "<p class='error'>Sorry, there was a problem uploading your file.</p>";
}
} else { // if FTP SERVER
$ftp_temp_img = "cache/ftp/".$nameimage."";
$ftp_temp_thumb = "cache/ftp/thumb/".$nameimage."";
if(move_uploaded_file($_FILES[$upload_name]['tmp_name'], $ftp_temp_img)) {
//aici se transforma RESIZE PENTRU THUMBNAIL din $_POST[''];
$thumbnail_size_final = 180;
switch($thumbnail_size) {
case 1:
$thumbnail_size_final = SMALL_THUMB;
break;
case 2:
$thumbnail_size_final = MEDIUM_THUMB;
break;
case 3;
$thumbnail_size_final = LARGE_THUMB;
break;
case 4;
$thumbnail_size_final = LARGER_THUMB;
break;
case 5;
$thumbnail_size_final = COVER_THUMB;
break;
}
// aici se face resizeul imaginilor
$image = new SimpleImage();
$image->load($ftp_temp_img);
if($width > $thumbnail_size_final) {
$image->resizeToWidth($thumbnail_size_final);
}
$image->save($ftp_temp_thumb);
}
if (ftp_put($ftp_conn_id, "/".$dir . "/$nameimage/", $ftp_temp_img, FTP_BINARY)) {
//echo "successfully uploaded image $ftp_temp_img in $target\n";
} else {
//echo "There was a problem while uploading $ftp_temp_img in $target\n";
}
if (ftp_put($ftp_conn_id, "/".$dirthumb . "/$nameimage/", $ftp_temp_thumb, FTP_BINARY)) {
//echo "successfully uploaded image $ftp_temp_thumb in $ftp_temp_thumb\n";
} else {
//echo "There was a problem while uploading $ftp_temp_thumb in $dirthumb\n";
}
$FTP->disconnect($ftp_conn_id);
unlink($ftp_temp_img);
unlink($ftp_temp_thumb);
$data = date('Y-m-d');
//$ImageId = $randomnumber . "-" . $basenameFilesUploaded;
//$ThumbSpreImagine = $website . "/" . $thumb . "/" . $ImageId;
//INSERARE IN BAZA DE DATE
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
} else {
$user_id = 0;
}
if(isset($_SESSION['user_id']) && isset($_POST['set_gallery']) && is_numeric($_POST['set_gallery']) && strlen($_POST['set_gallery']) > 0) {
$qG = "SELECT id FROM galleries WHERE id = {$_POST['set_gallery']} AND id_user = {$_SESSION['user_id']}";
$resultQg = mysql_query($qG);
if($resultQg && mysql_num_rows($resultQg) > 0){
$gallery = $_POST['set_gallery'];
} else {
$gallery = 0;
}
} else {
$gallery = 0;
}
$titlename = basename( $_FILES[$upload_name]['name']);
$titlename2 = $view_id;
$q = "INSERT INTO images (`id_user`, `titlename`, `gallery`,`name`,`view_id`, `date_added`, `last_view`, `source`, `adult`, `thumb_size`, `ftp`) VALUES
('{$user_id}', '{$titlename}', '{$gallery}','{$nameimage}', '{$view_id}', '{$data}', '{$data}', '1', '{$adult}', '{$thumbnail_size}', '{$ftp_server}')";
$result = mysql_query($q);
$id_inserted = mysql_insert_id();
if(!$result) {
die("Database error : " . mysql_error());
}
if(isset($_POST['download_links']) && strlen($_POST['download_links']) > 2) {
$download_links = filter($_POST['download_links']);
$download_links = trim($download_links);
$q = "INSERT INTO images_opt (`id_img`, `download_links`) VALUES ('{$id_inserted}', '{$download_links}')";
$result = mysql_query($q);
if(!$result) {
die("Database error : " . mysql_error());
}
}
?>
<div id="uploadedimage">
<a target='_blank' href="<?php echo "{$site_url}/img-{$view_id}.html"; ?>"><img border="0" src="<?php echo "{$rowFTP['url']}/{$dirthumb2}/{$nameimage}"; ?>" alt="uploaded_image" /></a>
</div>
<div id="uploadcodes">
<label>BB Code:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL] "; ?>">
<br /> <br />
<label>HTML:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a> "; ?>">
<br /> <br />
<label>Link:</label><br />
<input type='text' onclick="this.select();" value="<?php echo "{$site_url}/img-{$view_id}.html "; ?>">
<?php
if(DIRECT_LINK_SHOW == 1) {
echo "
<br /> <br />
<label>Direct Link to image:</label><br />
<input type='text' onclick='this.select();' value='{$rowFTP['url']}/{$dir2}/{$nameimage}'>
";
}
?>
</div>
<?php
global $BBCode_global;
global $HTMLCode_global;
global $DirectLink_global;
global $DirectLinkToImg_global;
$BBCode_global[] = "[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]";
$HTMLCode_global[] = "<a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a>";
$DirectLink_global[] = "{$site_url}/img-{$view_id}.html";
$DirectLinkToImg_global[] = "{$rowFTP['url']}/{$dir2}/{$nameimage}";
echo "<div style='display:none;' class='ajax_BBCode'>[URL={$site_url}/img-{$view_id}.html][IMG]{$rowFTP['url']}/{$dirthumb2}/{$nameimage}[/IMG][/URL]</div>";
echo "<div style='display:none;' class='ajax_HTMLCode'><a href='{$site_url}/img-{$view_id}.html'><img src='{$rowFTP['url']}/{$dirthumb2}/{$nameimage}' alt='image' /></a></div>";
echo "<div style='display:none;' class='ajax_DirectLink'>{$site_url}/img-{$view_id}.html</div>";
echo "<div style='display:none;' class='ajax_DirectLinkToImg'>{$rowFTP['url']}/{$dir2}/{$nameimage}</div>";
} // ftp end
} // ELSE IF EVERYTING IS OK, IF ERROR = 0
} // END FUNCTION
I am really frustrated with this and I can't find what is causing the error.
Here is the database screenshot:
This is simple html file code
<form action="upme.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<button type="submit">Upload</button>
</form>
This is simple PHP file code
<?php
$IMG = isset($_POST['files']) ? $_POST['files'] : array();
if (!empty($IMG))
{
$uploads_dir = 'images/';
foreach ($IMG["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $IMG["tmp_name"][$key];
$name = $IMG["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/".$name);
$name_array=mysql_real_escape_string($name);
$value_insert[] = "('" . $name_array . "')";
}
}
$values_insert = implode(',', $value_insert);
$query = "INSERT INTO upload (FILE_NAME) VALUES" . $values_insert;
$result = mysql_query($query);
}else{
echo 'empty array';
}
?>
when i use this code its give me 'empty array' error but file not upload.
<?php
$IMG = isset($_FILES['files']) ? $_FILES['files'] : array();
if (!empty($IMG))
{
$uploads_dir = 'images/';
$value_insert = '';
foreach ($IMG["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $IMG["tmp_name"][$key];
$name = $IMG["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/".$name);
$name_array=mysql_real_escape_string($name);
$value_insert .= $name_array . ",";
}
}
$values_insert = rtrim($value_insert, ',');
$query = "INSERT INTO upload (FILE_NAME) VALUES" . $values_insert;
$result = mysql_query($query);
}else{
echo 'empty array';
}
?>
here is the demo code
<?php
$IMG = isset($_FILES['files']) ? $_FILES['files'] : array();
if (!empty($IMG))
{
$uploads_dir = 'images/';
$i = 1;
foreach ($IMG["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $IMG["tmp_name"][$key];
$name = $IMG["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/".$name);
$name_array=mysql_real_escape_string($name);
if ($i == 1) {
$query = "INSERT INTO upload (FILE_NAME) VALUES" . $name_array;
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
$i++;
}
}
}else{
echo 'empty array';
}
?>
I trying to make script which upload multiple images into folder on server and save name and some other info in database. The script is working fine until I tried to add parameters to save type, size and category. I I remove this 3 lines below it is working.
$fileSize = $_FILES['user_files']['size'];
$fileType = $_FILES['user_files']['type'];
$album = $_POST['image_album'];
This is the script and I would like someone to help me with this.
if (isset($_POST["sub2"])) {
// include resized library
require_once('php-image-magician/php_image_magician.php');
$msg = "";
$valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
if (count($_FILES["user_files"]) > 0) {
$folderName = "uploads/";
$sql = "INSERT INTO images (image_name, image_size, image_type, image_album) VALUES (:img, :size, :type, :album)";
$stmt = $pdo->prepare($sql);
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
$filepath = $folderName . $filename;
$fileSize = $_FILES['user_files']['size']; <---- // THIS
$fileType = $_FILES['user_files']['type']; // THIS
$album = $_POST['image_album']; // AND THIS
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
$emsg .= "Error while uploading - <strong>" . $_FILES["user_files"]["name"][$i] . "</strong><br>";
$counter++;
} else {
$smsg .= "Image <strong>" . $_FILES["user_files"]["name"][$i] . "</strong> is added. <br>";
$magicianObj = new imageLib($filepath);
$magicianObj->resizeImage(100, 100);
$magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);
/* * ****** insert into database starts ******** */
try {
$stmt->bindValue(":img", $filename);
$stmt->bindValue(":size", $fileSize);
$stmt->bindValue(":type", $fileType);
$stmt->bindValue(":album", $album);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// file uplaoded successfully.
} else {
// failed to insert into database.
}
} catch (Exception $ex) {
$emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
}
/* * ****** insert into database ends ******** */
}
} else {
$emsg .= "This file <strong>" . $_FILES["user_files"]["name"][$i] . "</strong> isn't image. <br>";
}
}
}
And this is the form
<form name="f2" action="" method="post" enctype="multipart/form-data">
<fieldset>
Album
<select name="image_album">
<option value="1">Album 1</option>
<option value="2">Album 2</option>
<option value="3" >Album 3</option>
<option value="4" >Album 4</option>
<option value="5">Album 5</option>
</select>
<input class="files" name="user_files[]" type="file" ><span><a href="javascript:void(0);" class="add" >Add more</a></span>
<div><input type="submit" class="submit" name="sub2" value="Качи" /> </div>
</fieldset>
</form>
Please am trying to upload docs, .docx, .pdf, .jpg files using php but each time I click on the upload button, I get this message: "uploadedFile format not supported! uploaded".
Please where is the problem coming from? It is supposed to be either 'uploaded' or 'file format not supported'.
Thanks.
<?php
require_once "include/db_handle.php";
if (isset($_POST['upload'])) {
if (!empty($_FILES['_file']['name'])) {
if ($_FILES['_file']['type'] == 'application/msword') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".doc";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".doc";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/pdf') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".pdf";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".pptx";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'image/jpeg') {
$upload_folder = "./profile_pix/";
$pic_name = time() . ".jpg";
$pic_path = $upload_folder . $pic_name;
require_once "include/resize.php";
if (move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path)) {
$image = new Resize($pic_path);
$image->resizeImage(180, 180, 'crop');
$image->saveImage($pic_path);
//thumbnail
$image = new Resize($pic_path);
$image->resizeImage(50, 50, 'crop');
$image->saveImage($upload_folder . "thumb/" . $pic_name);
}
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
else{
echo "File format not supported!";
}
}
}
?>
HTML Form
<p class="points" > Add Files</p>
<form name="" action="" method="post" enctype="multipart/form-data">
<input type="file" name= "_file" />
<input type= "submit" name="upload" value="upload"/>
</form>