I want to store image name only inside mysql table but issue is that it's uploading blank array and giving error
array to string conversion.
if(isset($_POST['prd_submit']) && isset($_FILES['prd_image'])){
// Define Input Variables
$name = user_input($_POST['prd_name']);
$detail = user_input($_POST['prd_detail']);
$image = $_FILES['prd_image'];
$buy_link = user_input($_POST['prd_link']);
$price = user_input($_POST['prd_price']);
$category = $_POST['prd_category'];
$country = $_POST['prd_country'];
// Control Error Inputs
if(empty($name)){
$name_err = "Name is missing";
}
if(empty($detail)){
$detail_err = "Detail is missing";
}
if(empty($price)){
$price_err = "Price is missing";
}
if(empty($buy_link)){
$buy_link_err = "Link is missing";
}
// File Upload Function
$OutFiles = array();
foreach($image as $Index=>$Items){
foreach($Items as $Key=>$Item){
$OutFiles[$Key][$Index] = $Item;
}
}
if($OutFiles[0]['error']){
$image_err = $Errors[$OutFiles[0]['error']];
}else{
foreach($OutFiles as $Index=>$File){
$UploadDir = $DocRoot.'/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.',$imageName);
$file_ext = $file_ext[count($file_ext)-1];
//FILE NAME
$filename = (rand()).'-'.(time()).'.'.$file_ext;
//FILE EXTENTION ERROR
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif"){
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
$OutFiles[$Index]['name'] = $filename;
$uploadok++;
}elseif($uploadok == 0){
$error = "Sorry File is Not Upload";
}else{
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
}
// Insert DB
if($name_err == '' && $detail_err == '' && $image_err == '' && $price_err == '' && $buy_link_err == ''){
$Code = 0;
try{
$insert_data = ("INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$image','$price','$buy_link','$category','$date')");
$insert_data = $conn->query($insert_data);
}catch(PDOException $E){
$Code = $E->getCode();
}
if($Code == 0){
$error = "<div class='alert alert-success'>Your Product Registration Request Has Submitted!</div>";
}elseif($Code == 23000){
$error = "<div class='alert alert-info'>Duplicate Entry</div>";
}else{
$error = "Unabel to enter data";
}
}
To much confuse what thing i'm doing wrong in it and if implode array but how i can implode i just need name only.
Change $image To $filename in your INSERT query.
Because, $image = $_FILES['prd_image']; is an array and you wanted to store the file name which is just uploaded to upload folder. So, use $filename which is uploaded using elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
Query
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
Uploading Multiple File : Move your INSERT Query inside foreach. It will insert into table on every successful upload.
foreach ($OutFiles as $Index => $File) {
$UploadDir = $DocRoot . '/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.', $imageName);
$file_ext = $file_ext[count($file_ext) - 1];
//FILE NAME
$filename = (rand()) . '-' . (time()) . '.' . $file_ext;
//FILE EXTENTION ERROR
if ($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif") {
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} elseif (move_uploaded_file($File['tmp_name'], $UploadDir . $filename)) {
$OutFiles[$Index]['name'] = $filename;
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
$insert_data = $conn->query($insert_data);
$uploadok++;
} elseif ($uploadok == 0) {
$error = "Sorry File is Not Upload";
} else {
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
And, remove try/catch from below as now it's INSERTING on every UPLOAD.
Related
I am creating a social site. I have the option to upload up to 10 images with or without text, and the option to upload text without images.
So below I am trying to see if the user uploaded only text, or text with images. If the user uploaded only text then I want the text to be inserted into it's own separate table. If the user uploaded text with images or just images I want to check for that too. How can I check if the user uploaded images and if so run the images script and if not, jump out of the file ? This is what I have so far.
<input name="files[]" id='files' accept="image/png,image/gif,image/jpeg" type="file" multiple="multiple" />
$date_time = date('Y-m-d_H-i-s');
$img_limit = 10;
$maxsize = 4367463;
if(isset($_POST['submit'])) {
$errors = '';
if ($_POST['title_post'] == '') {
$errors = "Choose a topic.";
} else {
$create_topic = $con->prepare("INSERT INTO subtopic (subtopic, description)
VALUES (?, ?)");
$create_topic->bind_param("ss", $_POST['title_post'], $_POST['description']);
$create_topic->execute();
}
// --------------- CHECK IMAGES ----------****
$file_count = count($_FILES['files']['name']);
if ($file_count > 0) {
if ($file_count > $img_limit) {
$errors = 'Cannot upload more than 10 images';
}
if (!$errors) {
$stmt = $con->prepare("INSERT INTO images (image) VALUES (?)");
$stmt->bind_param('s', $file_path);
// Loop through each file
for( $i=0; $i < $file_count; $i++ ) {
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if ($file_size >= $maxsize) {
$errors = "Your file is too large";
} elseif ($imageFileType != "jpeg" && $imageFileType != "jpg" &&
$imageFileType != "png" && $imageFileType != "gif") {
$errors = "File type not allowed.";
}
//Make sure we have a file path
if (!$errors /* && $file_tmp != "" */) {
$picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
$uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);
$file_path = "uploads/" . $picToUpload;
$stmt->execute();
}
}
}} else {
header('Location: index4.php');
exit();
}
// --------------- CHECK IMAGES ----------****
}
You need to check the current file - for example:
if(!file_exists($_FILES['files']['tmp_name'][0]) || !is_uploaded_file($_FILES['files']['tmp_name'][0])){
}
Where 0 is equal to $i
I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?
this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.
I am creating a real estate web application and now creating a form which i will allow the editor to input data concerning a certain property , among of those inputs is images, but i do not know how to input multiple values in one column in the database.
Here are my codes.
if(!empty($_FILES)){
$photo1 = $_FILES['photo1'];
$photo2 = $_FILES['photo2'];
$photo3 = $_FILES['photo3'];
$photo4 = $_FILES['photo4'];
$photo5 = $_FILES['photo5'];
$photo6 = $_FILES['photo6'];
$photo7 = $_FILES['photo7'];
$photo = [$photo1,$photo2,$photo3,$photo4,$photo5,$photo6,$photo7];
foreach ($photo as $photos) {
$name = $photos['name'];
$nameArray = explode('.',$name);
$filename = $nameArray[0];
$fileEXT = $nameArray[1];
$mime = explode('/', $photos['type']);
$mimeType = $mime[0];
$mimeEXT = $mime[1];
$temploc = $photos['tmp_name'];
$filesize = $photos['size'];
$allowed = array('png','jpg','jpeg','gif',);
$uploadname = md5(microtime()).'.'.$fileEXT;
$uploadpath = LINKURL.'/imgs/photos/'.$uploadname;
$dbpath = '/realeastate/imgs/photos/'.$uploadname;
if($mimeType != 'image'){
$errors[]= 'File must be an image';
}
if(!in_array(strtolower($fileEXT), $allowed)){
$errors[]= 'The photo extension must be jpg,png,jpeg or gif.';
}
if($filesize > 25000000){
$errors[]= 'The file size must be less than 25MB.';
}
if(strtolower($fileEXT) != $mimeEXT && $mimeEXT == 'jpeg' && strtolower($fileEXT) != 'jpg' ){
$errors[]= 'File extension does not match the file.';
}
if(!empty($errors)){
echo show_errors($errors);
} else {
//upload file and insert into database
if (!empty($_FILES)) {
move_uploaded_file($temploc,$uploadpath);
}
if(isset($_GET['edit'])){
$db->query("UPDATE property SET taken ='$taken' WHERE id ='$edit_id'");
}else{
$db->query("INSERT INTO property (category,status,purpose,cover,images,city,place,price,payment,garage,wideness,visit,takenhome,hospital,school,market,bank,church,mosque,government,datetostart,floor) VALUES ('$category','$status','$purpose','$dbpath','$city','$place','$price','$payment','$garage','$wide','$dprice','$adprice','$hospital','$school','$church','$mosque','$government','$opendate','$floor')");
}
}
}
$_SESSION['success'] = 'Property Added successful';
header('Location: house.php');
}
hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}
I've edited this code to go from 1 image upload to 2, but it's ugly--basically just duplicated the previous variables. I want to get up to 8 images, and imagine there's a way to create an array and put it through a loop instead of making an individual instance for each image.
Thanks for any insight..
This is my code so far:
<?PHP
include("inc/header.php");
$back = "<a href='sell.php'>Click Here To Go Back And Try Again</a>";
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0 || $_FILES['userfile2']['size'] > 0 )
{
$title = $_POST['title'];
$description = $_POST['description'];
$category = $_POST['category'];
$price = $_POST['price'];
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$password = $_POST['password'];
// PICTURE UPLOAD SYSTEM
$imagename = basename($_FILES['userfile']['name']);
$imagename2 = basename($_FILES['userfile2']['name']);
if(empty($imagename) || empty($imagename2)) {
$error = 1;
echo"<h2 class='error'>The name of the image was not found.</h2>".$back;
}
if($error != 1 && $noimg != 1)
{
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
$filename2 = stripslashes($_FILES['userfile2']['name']);
$extension2 = substr(strrchr($filename2, '.'), 1);
$extension2 = strtolower($extension2);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
}
if (($extension != "jpg") && ($extension2 != "jpg") && ($extension != "jpeg") && ($extension != "jpeg") && ($extension != "png") && ($extension2 != "png") && ($extension != "gif") && ($extension2 != "gif"))
{
//print error message
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>'.$back.'';
$errors=1;
}
else
{
$time = time();
$newimage = "photos/" . $time . $imagename;
$newimage2 = "photos/" . $time . $imagename2;
$result = #move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
$result2 = #move_uploaded_file($_FILES['userfile2']['tmp_name'], $newimage2);
if(empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error moving the uploaded file.</h2><br/>".$back."";
}
// insert to SQL
$date = date("Y-m-d G:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, price, name, number, email, password, picture, picture2, date, views, authorized ) VALUES ('', '$title', '$description', '$category', '$price', '$name', '$number', '$email', '$password', '$newimage', '$newimage2', '$date', '0', '0')";
mysql_query($query) or die(mysql_error());
}
If you force the inputs into an array by using
<input type='file' name='file[]' />
<input type='file' name='file[]' />
<input type='file' name='file[]' />
then use the following function I found from file-upload.multiple.php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
You will be able to loop through the array very easily, hardly noticing you dealing with multiple files.
if (isset ($_POST['upload'])) {
extract ($_POST, EXTR_PREFIX_ALL, 'post');
$file_ary = reArrayFiles ($_FILES['file']);
$error = 0;
foreach ($file_ary as $file) {
// Test a file is uploaded for each input
if ($file['size'] == 0 || empty ($file['name'])) {
$error = 1;
break;
// Note: If not all input slots are required to be filled,
// replace the above with:
// continue;
// This will stop running this step of the loop here
// and start the next one.
}
// Test file format
if (!in_array ($file['type'], array (
'image/jpg', 'image/png',
'image/jpeg', 'image/gif')) {
$error = 2;
break;
}
}
if (!$error) { // True is returned if value is not 0;
$newpath = 'photos/'.time();
foreach ($file_ary as $file) {
$res = #move_uploaded_file($file['tmp_name'],
$newpath.'-'.$file['name']);
unlink ($file['tmp_name']);
if (!$res) {
$error = 3;
break;
}
}
}
if (!$error) {
$res = mysql_query(' ... insert query ... ');
if (!$res) {
$error = 4;
}
}
if ($error) {
// If you wanted to be super thorough, you could loop through
// and make sure that if any files did get moved that they
// were deleted.
$msg = "";
switch ($error) {
case 1: $msg = 'File not found.'; break;
case 2: $msg = 'Incorrect file format.'; break;
case 3: $msg = 'Error moving uploaded file.'; break;
case 4: $msg = 'Database query failed. '.mysql_error(); break;
default: $msg = 'Error';
}
echo "<h2 class='error'>$msg</h2><a href='sell.php'>Try Again.</a>";
}
}
check out: http://www.php.net/manual/en/features.file-upload.multiple.php
One hard-coded way I've done it in the past is:
<input type="file" name="file_1" />
<input type="file" name="file_2" />
<input type="file" name="file_3" />
and then when submitted:
foreach($_FILES as $file) {
// file actions
}