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;
}
Related
I have some code running on my site which works well to upload single files from file input form elements - but I now need a multiple file input form element to accept more than 1 file and upload them all to the server and store the details of the filenames uploaded in a comma separated string... Any ideas on how to make this work with the code I am using below:
form field:
<input name="logoexamples[]" id="blogoexamples" type="file" class="textInput" value="notrelevant" multiple>
PHP code (that works to accept 1 file uploaded, but not more than 1....?):
<?php
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// JWD - save uploaded filenames as a session var to get it on the redirect hook
$_SESSION['briefing_submittedfiles_' . $sf] = 'http://www.example.com/assets/uploads/'.$parentpageid.'/'.$filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
I had something similar coded for my website, this code is super old so don't judge or use it directly. Just an example.
if(isset($_POST['upload'])){
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "../FOLDER NAME/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
copy($newFilePath, $newFilePath1);
$filename = basename($_FILES['upload']['name'][$i]);
// add $filename to list or database here
$result = "The files were uploaded succesfully.";
}else{
$result = "There was an error adding the files, please try again!";
}
}
}
I have a form which has 2 file input fields. I have a PHP script which nicely handles the upload of the files - but what I am missing is the ability to get back the filename values from the form after the upload is complete. The code is below.
I am thinking maybe it might be easier to adapt this code to make it specific to upload the files of each specified file input - then I can get the file name back from easily?
e.g. so have 2 blocks of code to upload and store the file name value of inputs - input1 and input2 for example...?
Any ideas?
// initialize output;
$output = true;
// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');
// create unique path for this form submission
//$uploadpath = 'assets/uploads/';
// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.
// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE
// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';
// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
// loop through files
foreach ($submittedfiles as $sf) {
// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );
// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive
// is the file name empty (no file uploaded)
if($filename != '') {
// is this the right type of file?
if(in_array($ext, $ext_array)) {
// clean up file name and make unique
$filename = mb_strtolower($filename); // to lowercase
$filename = str_replace(' ', '_', $filename); // spaces to underscores
$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
// full path to new file
$myTarget = $target_path . $filename;
// create directory to move file into if it doesn't exist
mkdir($target_path, 0755, true);
// is the file moved to the proper folder successfully?
if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
// set a new placeholder with the new full path (if you need it in subsequent hooks)
$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
// set the permissions on the file
if (!chmod($myTarget, 0644)) { /*some debug function*/ }
} else {
// File not uploaded
$errorMsg = 'There was a problem uploading the file.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
} else {
// File type not allowed
$errorMsg = 'Type of file not allowed.';
$hook->addError($sf, $errorMsg);
$output = false; // generate submission error
}
// if no file, don't error, but return blank
} else {
$hook->setValue($sf, '');
}
}
return $output;
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 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}'";
I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path