I have converted this code from a single image upload and have tried to allow it to upload multiple images but it only displays one image when the form is submitted.
foreach($_FILES["images"]["error"] as $key=>$tmp_name){
$temp = $_FILES["images"]["tmp_name"][$key];
//$fileName = $_FILES["images"]["fileName"][$img];
$fileName = $pdo->lastInsertId() . '.jpg';
if(empty($temp))
{
break;
}
move_uploaded_file($temp, '../images/cars/' . $fileName);
}
you just need to use the instruction continue in this case.
if (empty($temp)) {
continue;
}
http://php.net/manual/en/control-structures.continue.php
With break you're stopping the foreach.
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 contains an image upload and an input text box. The user will be able to upload an image and enter text without refreshing the page using Ajax. The image will be relayed to PHP and PHP will handle what to do with the image. My problem is that for the first time the user uploads an image, it'll be checked if the same image name is on the server or not. If it is, the image name will get a uniqid() and then will be uploaded. But what if the user changes the data in the text box field, but keeps the image? Then that image will be uploaded again with a uniqid() since it's already on the server. I've tried solving this using my current code for the image handling:
PHP
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
if (isset($_SESSION["size"]))
{
$prevSize = $_SESSION["size"];
if (filesize($prevSize) != filesize($size))
{
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
}
}
else
{
$_SESSION["size"] = $size;
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
}
move_uploaded_file($tempName, $target_file);
Unfortunately, this code isn't working like I want it to. If I upload the same image twice in a row, in the same session, it doesn't override my previous image. Instead, it puts it on the server with a uniqid name. What am I doing wrong? And if there's a better way in solving this, I'd love to know!
What you can do is whenever someone uploads an image, store a hash of the image, encrypt it and store it in the database on the image row.
From now on, whenever someone uploads an image run a query like this:
SELECT COUNT(*) FROM images WHERE hash = $hash then in an if statement check if the returned value is bigger than 0, if it is, do what you need to do without re-uploading the image, and if it is 0, then upload your image and proceed
I chose a user avatar upload for this example. I'm not sure what your image is, but the workflow should be similar. No duplicate avatars will be copied to the image path.
function get_avatar_filename($filename) {
// only generate an avatar filename if the mimetype matches
switch (mime_content_type($filename)) {
case 'image/jpeg':
return sprintf('%s.jpg', hash_file('md5', $filename));
case 'image/gif':
return sprintf('%s.gif', hash_file('md5', $filename));
case 'image/png':
return sprintf('%s.png', hash_file('md5', $filename));
// otherwise the user uploaded a non-supported image
// return the default image
default:
return 'default-avatar.jpg';
}
}
function upload_avatar($avatarPath, $filename) {
// get the avatar filename
$f = get_avatar_filename($filename);
// copy the file to $avarPath only if the file doesn't already exist
if (!file_exists("{$avatarPath}/{$f}")) {
move_uploaded_file($filename, "{$avatarPath}/{$f}");
}
// return the avatar filename
return $f;
}
Now you can use these functions when you process the user form submission
// process user form submission ...
// ...
$filename = upload_avatar(
$_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/",
$_FILES['user_avatar']['tmp_name']
);
// save the avatar location for the user ...
// or whatever
$user->setAvatar($filename);
$user->save();
If the user uploads a non-supported image type, they will just be assigned default-avatar.jpg which is a file that should exist in your images directory.
I'm trying to upload files in php using the following function :
public function fileUpload($FILES){
$num_of_uploads = 1;
$max_file_size = 1048576; //can't be larger than 1 MB
$T = array ();
foreach($_FILES["file"]["error"] as $key=>$value){
if($_FILES["file"]["name"][$key] != ""){
if($value == UPLOAD_ERR_OK){
$v = array ();
$origfilename = $_FILES["file"]["name"][$key];
$filename = explode(".", $_FILES["file"]["name"][$key]);
$filenameext = $filename[count($filename) - 1];
$v['name'] = $filename[0];
$v['extension'] = $filename[1];
$v['type'] = $_FILES["file"]["type"][$key];
unset($filename[count($filename) - 1]);
$filename = implode(".", $filename);
$filename = "file__" . time() . "." . $filenameext;
if($_FILES["file"]["size"][$key] < $max_file_size){
$v['content'] = file_get_contents($_FILES["file"]["tmp_name"][$key]);
$T[] = $v;
}else{
throw new Exception($origfilename . " file size inaccepted!<br />");
}
}else{
throw new Exception($origfilename . " Error of upload <br />");
}
}
}
return $T;
}
This function works great with txt types, but when I'm testing pdf, or gif or jpg, it returns a damaged file.
As far as I know, file_get_contents() works well on text/html types.
However, for other file types you should parse their text content first to use it in further processing. Try opening any .pdf in Notepad to see it's text content.
For uploading purposes, use move_uploaded_file() in your cycle, like this:
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $filename);
Of course, without trying to get text content from uploaded file.
For downloading the file, you need to set headers. So, at the starting of function try setting any of below header for png or jpeg files:
//For png file
header("Content-Type: image/png");
//For jpeg file
header("Content-Type: image/jpeg");
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 have a problem here im trying to upload a file
first time it is moving the filename from temp it its respective directory,
but again i try ot upload the aa different file with the same name it should rename the
first time uploaded file
with date_somefilename.csv and give the filename to its original state
for example a file test.csv ,im uploading it for first time it will upload to
corresponding directory as
test.csv,when i upload a different csv file with same name test.csv
I need to get the
test.csv (latest uploaded file)
06222012130209_test.csv(First time uploaded file)
The code is below
$place_file = "$path/$upload_to/$file_name";
if (!file_exists('uploads/'.$upload_to.'/'.$file_name))
{
move_uploaded_file($tmp, $place_file);
}else{
move_uploaded_file($tmp, $place_file);
$arr1 = explode('.csv',$file_name);
$todays_date = date("mdYHis");
$new_filename = $todays_date.'_'.$arr1[0].'.csv';
echo $str_cmd = "mv " . 'uploads/'.$upload_to.'/'.$file_name . " uploads/$upload_to/$new_filename";
system($str_cmd, $retval);
}
See comments in code.
$place_file = "$path/$upload_to/$file_name";
if (!file_exists($place_file)) {
move_uploaded_file($tmp, $place_file);
} else {
// first rename
$pathinfo = pathinfo($place_file);
$todays_date = date("mdYHis");
$new_filename = $pathinfo['dirname'].DIRECTORY_SEPARATOR.$todays_date.'_'.$pathinfo['basename'];
rename($place_file, $new_filename)
// and then move, not vice versa
move_uploaded_file($tmp, $place_file);
}
DIRECTORY_SEPARATOR is php constant. Value is '/' or '\', depending of operation system.
pathinfo() is php function, that return information about path: dirname, basename, extension, filename.
What about...
$place_file = "$path/$upload_to/$file_name";
if (file_exists($place_file)) {
$place_file = date("mdYHis")."_".$file_name;
}
if (!move_uploaded_file($tmp, $place_file)) {
echo "Could not move file";
exit;
}
I would not add a date to the file if it already exists. Instead I would just add a number to the end of it. Keep it simple.
$counter = 0;
do {
// destination path path
$destination = $path.'/'.$upload_to.'/';
// get extension
$file_ext = end(explode('.', $file_name));
// add file_name without extension
if (strlen($file_ext))
$destination .= substr($file_name, 0, strlen($file_name)-strlen($file_ext)-1);
// add counter
if ($counter)
$destination .= '_'.$counter;
// add extension
if (strlen($file_ext))
$destination .= $file_ext;
$counter++;
while (file_exists($destination));
// move file
move_uploaded_file($tmp, $destination);
$target = "uploads/$upload_to/$file_name";
if (file_exists($target)) {
$pathinfo = pathinfo($target);
$newName = "$pathinfo[dirname]/" . date('mdYHis') . "_$pathinfo[filename].$pathinfo[extension]";
rename($target, $newName);
}
move_uploaded_file($tmp, $target);
Beware though: Security threats with uploads.
how about something like this?
<?php
$tmp = '/tmp/foo'; // whatever you got out of $_FILES
$desitnation = '/tmp/bar.xyz'; // wherever you want that file to be saved
if (file_exists($desitnation)) {
$file = basename($destination)
$dot = strrpos($file, '.');
// rename existing file to contain its creation time
// "/temp/bar.xyz" -> "/temp/bar.2012-12-12-12-12-12.xyz"
$_destination = dirname($destination) . '/'
. substr($file, 0, $dot + 1)
. date('Y-m-d-H-i-s', filectime($destination))
. substr($file, $dot);
rename($destination, $_destination);
}
move_uploaded_file($tmp, $destination);