I made a code for multiple image uploader, but just first image is stored to mysql table and both into path, some help?
This is my code:
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(in_array($ext, $allowed) === true && move_uploaded_file($temp, "product_images/{$file}") === true){
$path = 'product_images';
mysql_query("INSERT INTO `products` (img_path, img_name) VALUES ('$path', '$file')");
}else{
$errors[] = 'Format slike mora biti .jpg ili .png';
}
}
}
}
Related
I found this code and it all works file uploads to the correct folder that is fine.
image - is main image that works it inserts one image name into the database field.
but when i try to insert all the names of the files uploaded in images field it only inserts the last file name.
$imageDirectory = "img/cars/" . $resultget->id . "";
$newDirName = generateRandomString(10);
$targetDir = $imageDirectory."/";
if (!file_exists($targetDir)) {
mkdir($targetDir, 0777, true);
} else {
$targetDir = $imageDirectory."/";
}
// Count total files
$fileCount = count($_FILES['the_file']['name']);
// Iterate through the files
for($i = 0; $i < $fileCount; $i++){
$target_dir = $imageDirectory."/";
$target_file = $target_dir . basename($_FILES["the_file"]["name"][$i]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["the_file"]["tmp_name"][$i]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$errorTxt = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["new_young"]["size"] > 500000) {
// $errorTxt = "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$errorTxt = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
$temp = explode(".", $_FILES["the_file"]["name"][$i]);
$newfilename = str_replace( '.', '', strval( microtime( true ) ) ) . '.' . end( $temp );
$target_file = $target_dir . $newfilename;
if (file_exists($target_file)) {
$errorTxt = "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
// if everything is ok, try to upload file
echo $errorTxt;
} else {
if (move_uploaded_file($_FILES["the_file"]["tmp_name"][$i], $target_file )) {
$checking = $resultget->images;
$checkimage = $resultget->image;
if(empty($checkimage)) {
$sqlimage = "UPDATE individual_cars SET image = '$newfilename' WHERE id = '$image_id'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
}
foreach (array($newfilename) as $filename) {
if(empty($checking)) {
echo implode(',', $filename);
$sqlimage = "UPDATE individual_cars SET images = '" . implode(',', $filename) . "' WHERE id = '" . $resultget->id . "'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
} else {
echo implode(',', $filename);
$sqlimage = "UPDATE individual_cars SET images = '," . implode(',', $filename) . "' WHERE id = '" . $resultget->id . "'";
mysqli_query($mysqli, $sqlimage) or die(mysqli_error($mysqli));
}
}
} else {
$errorTxt = "Sorry, there was an error uploading your file.";
}
}
}
Im checking images if empty because if a file name is already in that field i want it to continue so like this
example: 12345.png is already in there so if its not empty i want 12345.png, 54321.png and so on.
but its only inserting the last image name
sorry this is my first time posting.
I am trying to upload 3 separate images to upload on the server using. the code doesn't throw any error but only 1st image gets uploaded. The other two images are not uploaded on the server but Its name gets inserted into the database.
here is my code to upload the images:
<?php
include("common_code.php");
include("database_connection.php");
$property_id = $_POST['id'];
if (!$_FILES['file1']['size'] == 0) {
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
$fileName1= mt_rand(). "_". time(). "." .$extension;
$image_tmp_name = $_FILES['file1']['tmp_name'];
$folder = "images/property_images/";
$folder = $folder . $fileName1;
move_uploaded_file($image_tmp_name, $folder);
$uploadQuery = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder','$property_id')";
$run = mysqli_query($connection, $uploadQuery);
}
if (!$_FILES['file2']['size'] == 0) {
$temp2 = explode(".", $_FILES["file2"]["name"]);
$extension2 = end($temp2);
$fileName2= mt_rand(). "_". time(). "." .$extension2;
$image_tmp_name = $_FILES['file2']['tmp_name'];
$folder2 = "images/property_images/";
$folder2 = $folder2 . $fileName2;
move_uploaded_file($image_tmp_name2, $folder2);
$uploadQuery2 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder2','$property_id')";
$run2 = mysqli_query($connection, $uploadQuery2);
}
if (!$_FILES['file3']['size'] == 0) {
$temp3 = explode(".", $_FILES["file3"]["name"]);
$extension3 = end($temp3);
$fileName3= mt_rand(). "_". time(). "." .$extension3;
$image_tmp_name = $_FILES['file3']['tmp_name'];
$folder3 = "images/property_images/";
$folder3 = $folder3 . $fileName3;
move_uploaded_file($image_tmp_name3, $folder3);
$uploadQuery3 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder3','$property_id')";
$run3 = mysqli_query($connection, $uploadQuery3);
}
header("Location:property_reg_successful.php?id=$property_id");
Only file1 gets uploaded into a server!
file2 and file3 not uploaded.
You've just got a simple variable-naming error:
$image_tmp_name = $_FILES['file2']['tmp_name'];
[...]
move_uploaded_file($image_tmp_name2, $folder2);
Note the different variable names "$image_tmp_name" and "$image_tmp_name2".
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...";
}
}
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>
i am strcuked in a unexpected problem..i am having many queries of creating and insert.
eg:
if (isset($_POST['install']))
{
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$allowedExtss = array("jpg", "jpeg", "png");
$extensions = end(explode(".", $_FILES["path2"]["name"]));
//echo $extension;
if (($extensions == "jpeg")|| ($extensions == "jpg")|| ($extensions == "png"))
{
if ($_FILES["path2"]["error"] > 0)
{
$msgs = $_FILES["path2"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["path2"]["tmp_name"],
"../images/" . $_FILES["path2"]["name"]);
}
$filename2 = "images/" . $_FILES["path2"]["name"]; }
$install_queries[] = "INSERT INTO TABLE(image) VALUES('$filename2')";
foreach ($install_queries as $q)
{
//running queries here
}
but on ruuning script it is inserting it with blank in image filed..but another fields are filled...............
Thanks
Is it uploading any images at all?
Perhaps only insert into the image table if the upload is successful.
if (isset($_POST['install']))
{
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$allowedExtss = array("jpg", "jpeg", "png");
$extensions = end(explode(".", $_FILES["path2"]["name"]));
//echo $extension;
if (($extensions == "jpeg")|| ($extensions == "jpg")|| ($extensions == "png"))
{
if ($_FILES["path2"]["error"] > 0)
{
$msgs = $_FILES["path2"]["error"] . "<br />";
}
else
{
if(move_uploaded_file($_FILES["path2"]["tmp_name"],
"../images/" . $_FILES["path2"]["name"])) {
$filename2 = "images/" . $_FILES["path2"]["name"];
$install_queries[] = "INSERT INTO `image` VALUES('$filename2')";
}
}
foreach ($install_queries as $q)
{
//running queries here
}