I searched the internet for days and i cant figure this out.
i have this code
foreach($_FILES['image']['name'] as $key => $value)
{
$name = $_FILES['image']['name'][$key];
}
I have a table in phpmyadmin with the name of img and two rows in it (url1) and (url2.
For example i submit 'pic1,jpg' and 'pic2.jpg' and i want to place 'pic1.jpg' in the row url1
and 'pic2.jpg' in the row url2
How would i do this, because i cant access the name of the images via the foreach loop.
For instance the variable $name has those two pictures in it, how would i echo the second picture?
without showing me the two pictures.
please help me i have been struggling for days now and grew a beard.
If you're only uploading 2 images:
$images = $_FILES['images'];
foreach($images['name'] as $key => $value) {
$file_name[$key] = $value;
$file_tmp = $images['tmp_name'][$key];
$file_ext = explode('.', $file_name); // images.jpg becomes images jpg
$file_ext = strtolower(end($file_ext)); // We make the extension (jpg, gif etc.)
// lowercase and separate it with "end" from images, which leaves us the extension
$file_trim_name = rtrim($file_name, ".".$file_ext); // We remove the extension (.jpg)
// from the image name
$file_name_new = uniqid($file_trim_name . "-", true) . '.' . $file_ext; // Create a
// "uniqid" (if you do not want to overwrite other images). We take the image name
// and separate name and id by "-" and add the extension afterwards: $file_name_new = images-20302.jpg
$file_destination = 'image/folder/location' . $file_name_new; // Choose file location
move_uploaded_file($file_tmp, $file_destination); // Here we move images to their
// location with the function "move_uploaded_file"
}
$url1 = $file_destination[0]; // Selecting first image
$url2 = $file_destination[1]; // Selecting second image
$query_images = "INSERT INTO images (url1, url2)
VALUES
('{$url1}', '{$url2}'";
Related
I am trying to upload an image with a random name, also when I update the image, I want the previous image to be deleted.
Code below:
$banner=$_FILES ['banner']['name'];
$upload="../image/banner/";
$target_file = $upload.basename($_FILES["banner"]["name"]);
$imagefiletype= pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["banner"]["tmp_name"], $target_file );
Any help will be appreciated.
When update your new images at that time first store old image name in variable. after update true then delete old image in your directory using "unlink" function.
$old_image = "xyz" // store old image name
after update query success
unlink('../image/banner/'.$old_image); // delete old image in your directory
You can do it like this.
$path = 'image/folder/'; $unique_name=time().uniqid(rand());
$File_with_location = $path . $unique_name . '.' . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
$filename = $_FILES["img"]["tmp_name"];
move_uploaded_file($filename, $File_with_location);
for deleting old image you can use this
$path = './root/home/folder/file.jpg';
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
I have a form that uploads data to the DB and this includes the path to the directory where images are uploaded. Everything works, except for the fact that the image won't display.
Viewing the source in my browser tells me that the image is found but I keep getting the broken image icon.
Here's my code:
$dir = "../uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
if (count($fileArray) > 0) {
$image = $fileArray[0];
echo "<img src='$image' width='300px'>";
}
In the form you can upload multiple files. In the DB, the files get a random prefix then file name, like 3456456745654_imageName.jpg.
If multiple files are uploaded, they are split with an asterisk (*), which is why I'm exploding.
Then, to print only one image, I'm checking for the number of images relevant to a specific record then displaying only the first one.
PS. This code works for displaying all the images relevant to a selected image:
$dir = "uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
foreach ($fileArray as $file) {
if (file_exists($dir . $file)) {
echo "<img class='images' src='$dir/$file' width='300px;'>";
}
}
But that's for a different page that displays a selected vehicle's information, including all images.
I need to show only one image per vehicle on the landing page that lists all vehicles.
Had to use the directory:
$dir = "../uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
if (count($fileArray) > 0) {
$image = $fileArray[0];
if (file_exists($dir . $image)) {
echo "<img class='images' src='$dir/$image' width='300px;'>";
}
}
I'm dealing with a few issues regarding multiple file uploads. My project deals with a form the user inputs multiple images that save to a database, but first temporarily stores the images in a directory to show a preview of sorts. In my class that deals with the uploading of the image I am trying to rename the images as seen below.
If I upload one image at a time, the previews work and each image is unique with a unique name. However if when I click the upload button and hold control while selecting images ie select multiple images a a time, they all save as the same name and the images that preview show duplicate images of whatever first image I selected.
How do I go about adding like a number corresponding to that sessions amount of pics uploaded like'name-of-image-1.jpg' , 'name-of-image-2.jpg', etc etc?
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,$index = null, $content_range = null)
{
$file = new \stdClass();
$file->name = $this->generate_unique_filename($name);
... //more code
}
protected function generate_unique_filename($filename = "")
{
$extension = "";
if ( $filename != "" )
{
$extension = pathinfo($filename , PATHINFO_EXTENSION);
if ( $extension != "" )
{
$extension = "." . $extension;
}
}
$filename = getmypid() . '_'.time();
return $filename;
}
In your case when you upload files,a single process id is handling all requests ,So every image gets the same name i.e. same (process id + time).
$filename = getmypid() . '_'.time(); (better use microtime())
You can do something like this to rename the file with hyphen added( the numbers added would be 0,1,2 etc).
//html
<input name="upload[]" type="file" multiple="multiple" />
//php
for($i=0; $i<count($_FILES['upload']['name']); $i++)
{
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$oldFile= $_FILES['upload']['name'][$i];
$old_name=pathinfo($oldFile);
$add_new_name = 'new-image-'.$i.'.'.$old_name['extension'];
/* or use $add_new_name = microtime().'-'.$i.'.'.$old_name['extension'];*/
if(move_uploaded_file($tmpFilePath, "./youruploadfolder/".$add_new_name))
{
//rest of the code here
}
}
}
set the second parameter of move_uploaded_file what you like (your upload folder name).
I know just image name I don't know image extension (jpg, gif, etc) (code auto select). Directory Name "Upload"
I have many images in upload folder like (Image1, Image2, Image3), but I want to select only one image (image1 . (jpg)(gif)(png)). Please give me PHP code for select image from directory with any extension.
$img_detail = '11_detail'; // i wanna select this image
$dir = 'upload/advertisement/';
$files = scandir($dir);
foreach($files as $file){
echo $file.'<br>';
}
// Code showing result like thi
// 11.swf
// 13.gif
// 14.gif
// 15.gif
// 16.jpg
// 16_detail.gif // i wanna select this image
// index.php
All image extension not same
Enjoy!
$ad_id = '11';
$addata = ad_data($conn, $ad_id, 'ad_img'); // Function
$addetail = $ad_id.'_detail'; // this is my file name
$dir = 'upload/advertisement/';
$files = scandir($dir);
foreach($files as $file){
$file = explode('.', $file);
$currentname = current($file); // i have select current name
$ext = end($file); // for final result
// echo $firstname. '-'.$ext.'<br>'; // test
if($currentname == $addetail){ // matching image name with required name
$real_file = $currentname.'.'.$ext; // after matching use real extension
}
}
if(empty($real_file)){ // if file not found
echo $ad_id.'.'.$addata['ad_img'];
}else{ // enjoy
echo $real_file;
}
Below I have included my code that uploads multiple images to a folder and the path to mysql. I am brand new so please excuse me for such a silly question but I can not figure where to start with sending this timestamp or $fileName value to mysql.
<?php
require_once('storescripts/connect.php');
mysql_select_db($database_phpimage,$phpimage);
$uploadDir = 'upload/';
if(isset($_POST['upload']))
{
foreach ($_FILES as $file)
{
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($fileName != ""){
$filePath = $uploadDir;
$fileName = str_replace(" ", "_", $fileName);
//Split the name into the base name and extension
$pathInfo = pathinfo($fileName);
$fileName_base = $pathInfo['fileName'];
$fileName_ext = $pathInfo['extension'];
//now we re-assemble the file name, sticking the output of uniqid into it
//and keep doing this in a loop until we generate a name that
//does not already exist (most likely we will get that first try)
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$result = move_uploaded_file($tmpName, $filePath.$fileName);
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$fileinsert[]=$filePath;
}
$cat=$_POST['cat'];//this is the category the product is stored in
$about=$_POST['about'];//this is some general information about the item
$price=$_POST['price'];//the price of the item
$item=$_POST['item'];//the name of the item
$name1=basename($_FILES['image01'][$fileName]);//the file name of the first actual jpg
$name2=basename($_FILES['image02'][$fileName]);//the file name of the sencond actual jpg
$name3=basename($_FILES['image03'][$fileName]);//the file name of the third actual jpg
$name4=basename($_FILES['image04'][$fileName]);//the file name of the fourth actual jpg
$query = "INSERT INTO image (mid, cid, about, price, item, name1, name2, name3, name4) ".
"VALUES ('','$cat','$about','$price','$item','$name1','$name2','$name3','$name4')";
mysql_query($query) or die('Error, query failed : ' . mysql_error()); }
?>
If I understand your question correctly, you need to change:
$fileinsert[]=$filePath;
to:
$fileinsert = array(); // initialize the variable before the loop
...
$fileinsert[]=$filePath.$fileName; // or just $fileName if you don't need the path in the DB
and then you need to change:
$name1=basename($_FILES['image01'][$fileName]);//the file name of the first actual jpg
$name2=basename($_FILES['image02'][$fileName]);//the file name of the sencond actual jpg
$name3=basename($_FILES['image03'][$fileName]);//the file name of the third actual jpg
$name4=basename($_FILES['image04'][$fileName]);//the file name of the fourth actual jpg
to:
$name1=$fileinsert[0];
$name2=$fileinsert[1];
$name3=$fileinsert[2];
$name4=$fileinsert[3];
Something like that should do it.