Error uploading docs, pdf, jpg using php - php

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>

Related

upload all fields with the image file upload optional PHP MySQLI

I have searched far and wide and cannot find an answer to my question in terms that I can understand. I am trying to make my code upload all text input fields and if not image is in the file input, then upload all except the image and upload all including the image when an image is present. Below is my working code for when an image is present. All help will be greatly appreciated.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
if(!empty($_FILES["uploadedimage"]["tmp_name"])) {
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate=mysqli_real_escape_string($con, $_POST['edate']);
$eDesc=mysqli_real_escape_string($con, $_POST['edesc']);
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['uploadedimage']['name'])));
$date = date("d-m-Y");
$imagename = $date."-".time().".".$file_ext;
$target_path = "event_images/".$imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if($move) {
if($_FILES['uploadedimage']===false){
$not = "NULL";
}ELSE{
$not = $imagename;
}
$sql =mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'".$not."','".$eTitle."','".$eDate."','".$eDesc."')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
}
else {
$msg = "Not uploaded because of error #".$_FILES["file"]["error"];
}
}
else {
$msg = "Failed to Upload<br/>Not uploaded because of error #".$_FILES["file"]["error"];
}
?>
<?=$msg;?>
Following code should work the way you need it.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate = mysqli_real_escape_string($con, $_POST['edate']);
$eDesc = mysqli_real_escape_string($con, $_POST['edesc']);
$date = date("d-m-Y"); // where is this used?
$not = null;
if (!empty($_FILES["uploadedimage"]["tmp_name"])) {
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.', $_FILES['uploadedimage']['name'])));
$imagename = $date . "-" . time() . "." . $file_ext;
$target_path = "event_images/" . $imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if ($move) {
$not = $imagename;
} else {
$msg = "Not uploaded because of error #" . $_FILES["file"]["error"];
}
}
$sql = mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'" . $not . "','" . $eTitle . "','" . $eDate . "','" . $eDesc . "')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
?>

After renaming uploaded image, broken image is shown when fetched from database

If I upload a same named image, my code works fine to rename it in my location but when it's fetched from database, the duplicate image is broken. My code for renaming and storing the image is:
insert_image.php
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $location);
while(file_exists($location)) {
$increment++;
$location = $name. $increment . '.' . $extention;
//print_r($location);
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}
any kind of better suggestions will be really helpful.
In location variable (inside while loop) your are storing only file name. You also want full path. change your code as below
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $name);
while(file_exists($location)) {
$increment++;
$location = realpath(dirname(__FILE__)).'/images/'.$name. $increment . '.' . $extention;
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}

how to save image in wordpress folder while using custom template

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" >

PHP/Mysql input value on column become null when another column value change

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:

Script for multiple image upload doesn't work properly

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>

Categories