I have an html file and i have done the code for printing the names of images from a folder in PHP , but it is not printing the values to screen. if i echo any other thing it is printed on screen.
i have the set the server using xampp.
how to correct this, i make the names of images from that folder printed on screen?
do i need to do anything extra
im a newbie in php. how can i achieve this?
<?php
function findImagesInFolder()
{
$folder = $_GET['C:\xampp\htdocs\firstsite'];
$images = glob($folder . '/*.{png,jpg,jpeg,gif}', GLOB_BRACE);
echo json_encode($images);
exit();
}
?>
It seems you have misused the $_GET variable.
I thing you want to just use the string value, ie.:
$folder = 'C:\xampp\htdocs\firstsite';
And note, the exit() terminates whole script after printing the json_encoded string.
So, to make the function reusable change it to get the path as a parameter $folder:
<?php
function findImagesInFolder($folder, $filter = '*.*')
{
// note, here we expect the path does not trail with backslash
$images = glob($folder . '\\' . $filter, GLOB_BRACE);
return json_encode($images);
}
// call the function with actual path to scan:
$path = 'C:\xampp\htdocs\firstsite';
$filter = '{*.png,*.jpg,*.jpeg,*.gif}';
echo findImagesInFolder($path, $filter);
?>
Note: output as [] means empty array encoded to JSON.
Related
I have the following
$basename = !empty($_POST['basename']) ? $_POST['basename'] : null;
$upload_files = array(
'/usr/path/to/dir/' . $basename,
'/usr/path/to/dir/thumbs/' . $basename
Later on, I reassigned the variable $basename, like so
$basename = 'test.jpg';
When echo like so
echo $upload_files[0];
I want to output this
'/usr/path/to/dir/test.jpg'
But obviously, it doesn't.
Is there a trick with php where this is possible, like adding & before the variable or something?
Once you include $basename into a string, PHP loses all track of it as a variable, so subsequent changes have no effect. You could make the values in $upload_files into arrays, imploding them into strings when required, and making the second element a reference to $basename:
$basename = 'file1.gif';
$upload_files = array(
array('/usr/path/to/dir/', &$basename),
array('/usr/path/to/dir/thumbs/', &$basename)
);
echo implode('', $upload_files[0]) . PHP_EOL;
$basename = 'test.jpg';
echo implode('', $upload_files[0]). PHP_EOL;
Output:
/usr/path/to/dir/file1.gif
/usr/path/to/dir/test.jpg
Demo on 3v4l.org
What is your intended use case? If you need to access each pic string, you can store them in an array, and just use the last entry for the 'current' item. Then you'd have access to search or process each if you needed it. You can concat as needed. I'd probably write a function for processing it.
$basenames = [];
// However you're retrieving the filename
array_push($basenames, "file.gif");
// Current file
concatPic(count($basenames)-1);
// To find what key you wants position
$fileIndex = array_search("what_you're_looking_for", $basenames);
concatPic($fileIndex); // To process a specific index
function concatPic($indexValue)
{
return / echo (whatever) "usr/path/..." . $basenames[$indexValue]
};
You can also write a foreach to do all of them at once as well, or even concatenate them before pushing to the array if you want.
I have an array, which contains amongst other things a file path to a video file. There are various file formats .avi, .mp4 etc etc.
Now I only want to display the rows where the file path's file extension is .mp4.
Currently I'm using a function to extract the file extension, but I'm having trouble doing this on the fly while displaying the rows.
An example of the file path: c:\TempVideoDir\Office-P-cam01-20140826-083016.avi
The function im using to get the file ext:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
echo $just_fileext;
}
Which works fine.
Now I'm querying the database to get the filepath along with other details about the file, and I only want to display the rows where the file path contains a .mp4 file.
I've tried everything I could thing of/find on Google etc but this is what I currently have:
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
if (in_array((get_fileext($row["Filename"])== "mp4"), $result)) {
echo " blah blah
I dont have the option of adding the file extension into the database table as this is backed up automatically by a piece of equipment.
So, whadoyareckon? is it possible to do it on the fly like this?
Any help is much appreciated!
Thanks
I dont think you can use in_array() like that. Its searching the entire index of the array, so when it looks ate $result[] its never going to find $row['filename'] with only an ext.
try this:
//looping through $result array
foreach($result as $row) {
//check if $row['filename'] has a string with a mp4 extension.
if (get_fileext($row["Filename"])== "mp4") {
echo "Row has a filename with the mp4 extension';
also as someone else pointed out fix your get_fileext() method to return something.
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
return $just_fileext;
}
Your function isn't returning a value. It's emitting the value to the output:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
echo $just_fileext;
}
So there's no way for anything invoking that function to see that result. Instead, return the value:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
return $just_fileext;
}
That way the invocation of the function itself evaluates to the returned value, allowing you to use the function in your logic.
You could consider adjusting your database query to only return rows with ".mp4" files.
Change your query to have something like:
filepath = "%.mp4"
In MySQL the % operator is a wildcard, so this will match any strings ending in ".mp4"
so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.
As the title said i need a way to set the variable name depending of what the name of the picture is (i got over 100 different pictures)
Since i got custom classes in another php file for each picture (like tags) like for example:
$picture1 = "hillside sunset";
$picture2 = "beach cyprus";
and so on, so i need to fetch each variable for each picture
Heres the current loop where the div class is going to be each pictures name ($PICTURENAME is just to define where this code goes and is irelevant codewise):
<?php
foreach (glob("img/*.jpg") as $filename)
{
$path = $filename;
$file = basename($path);
$file = basename($path, ".jpg");
echo '<div class="'.$PICTURENAME.'" id="'.$file.'"><img src="'.$filename.'"> '.$file.' </div>';
}
?>
Don't use 100+ variables. Using a database would make far more sense, but if you don't want to get into learning that (you should, though), using a data structure would still make far more sense.
You could create one array (and use it as a map), and have the filename as the key, and the value would be the tags.
In PHP, you can address a variable using another variable:
$name = "foo";
${$name} = "bar";
echo $foo; // prints "bar"
echo ${$name}; // the same as above
However, as Kitsune already recommended, you are better off using something else, e.g., an array.
I am looking for some help with my code, I have looked elsewhere but am having difficulty to really understand what is going on with the code given elsewhere and I am hoping someone can help me.
I have one gallery page that uses $_POST to change the folder the gallery gets it images form based on the link clicked.
What I want now is to code a search function that looks through them all for a string (a jpg) when it finds it, it returns its img tags and displays the image.
I am having trouble making scandir work and display currently using this code
<?php
$dir = "/galleries/images/adult-cakes/images/";
$scan = scandir($dir);
echo $dir;
print_r($scan);
foreach ($scan as $output) {
echo "$output" . "<br />";
}
?>
that returns the echo dir but nothing else ( please note print was something I tried it was echo before and neither is working.
Then I need to get the output of all the gallery types, adult, anniversary etc and put them into a loop like so
search criteria = cake 1(.jpg)
put scandir info into $folderarray
search this folder until found -
galleries/images/$folderarray/images/
loop
if found then echo img tags with link to pic
if not display not found
This will get an array of all the files in directory $dir
<?php
$dir = "/galleries/images/adult-cakes/images/";
$images = glob($dir . '*');
?>
Do this to get all subdirectories of $Dir into array $DirArray:
$Dir = '/galleries/images/'; //
foreach ( $DirArray = array_filter(glob($Dir . '*'), 'is_dir') as $DirName ) {
$DirName = str_replace($Dir, '', $DirName); // Optionally, remove path from name to display
echo "Dir Name: $DirName <br />\n"; // Test
}
echo var_dump($DirArray); // Test
Modify accordingly