getting directory of a file without knowing its extension - php

I want to be able to present the photo of a user. That user may be of the type Doctor, Nurse or Patient and each person belonging to each of those types has a distinct ID which identifies him. I have the photos of each type of users separated in three folders inside the directory /images/user_upload/ and a given user may or may not have a photo. If he has a photo, I want to present the photo with a name which is the same as his ID (Note that I don't know the extension of this file, only the name). If he doesn't I want to present a default image. I have a function called printUserPhoto for this end.
function printUserPhoto()
{
$path = '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id']. '.*';
$source = glob($path);
if(empty($source))
echo '<img src="images/default_profile_img.png" />';
else
echo '<img src="',$source[0],'" />';
}
Although, I always get an empty array in the variable $source, even though the image exists. What am I doing wrong?

This way with glob
function printUserPhoto()
{
$pathToDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
$path = $pathToDocumentRoot . '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id']. '.*';
$source = glob($path);
if(empty($source)){
echo '<img src="images/default_profile_img.png" />';
} else {
echo '<img src="',$source[0],'" />';
}
}
Maybe limit the filetypes user can upload. With that you could do something like this:
function printUserPhoto()
{
$pathToDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
$path = $pathToDocumentRoot . '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id'];
$file = "images/default_profile_img.png";
if(file_exists($path . '.jpg')){
$file = $path . '.jpg';
}else if(file_exists($path . '.png')){
$file = $path . '.png';
}else if(file_exists($path . '.gif')){
$file = $path . '.gif';
}
echo '<img src="' . $file . '" />';
}
Also as being said by #Phil you are now referring to the file system root / being absolute path not relative to your document root.

Related

Am trying to create a folder with random digits, and put a file inside of it

Here is my code
$file = 'post.php';
$root = '/' . $dir_auth1 . '/'. $file;
$folder = mkdir(rand(10,10000));
$folder5 = $folder . '/' . $file;
echo $folder5;
if($folder) {
if (!copy($root, $folder5)) {
echo "failed to copy $file...\n";
} else {
echo "<p style='font-size:35px;font-family:verdana;text-align:center;'>status was successfuly created.</p>";
}
}
Basically what I am trying to do is upon a form submit create a directory with random digits and place the $file variable inside of the randomized directory
mkdir - return bool. Please read about mkdir
And rewrite you code something like this:
$file = 'post.php';
$root = '/' . $dir_auth1 . '/'. $file;
$folder = rand(10,10000);
mkdir($folder);
$folder5 = $folder . '/' . $file;
And check you if. You always true. (not empty string = true)

How to check Image name in folder and rename it?

I have a csv file with image name and Prefix for image and I want to add prefix in that image name and rename it and move it to another directory.
<?php
$fullpath = '/var/www/html/john/Source/01-00228.jpg';
$additional = '3D_Perception_';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/' . $additional
. $info['filename']
. '.' . $info['extension'];
echo $fullpath ;
}
?>
Here Image file is store in Source Directory I want to rename it with some prefix and move it other directory like Destination
Please help me out to find solution for this.
<?php
$source_directory = '/var/www/html/john/Source/';
$dest_directory = '/var/www/html/john/Source/'; // Assuming you'll change it
$filename = '01-00228.jpg';
$prefix = '3D_Perception_';
$file = $source_directory . $filename;
$dest_file = $dest_directory . $prefix . $filename;
if (file_exists($file)) {
if (copy($file, $dest_file)) {
unlink($file); // Deleting source file.
var_dump(pathinfo($dest_file)); // Dump dest file infos, replace it with wathever you want to do.
} else {
// if copy doesn't work, do something.
}
}
?>
Try this, and take care about my comments. ;)

PHP renaming/chaning featured picture

I'm trying to make a PHP script that changes the featured picture of some item.
The general principle is that it when $_POST['featured'] is set, it renames that picture to featured.jpg and renames all other pictures to their hash_file value. However, it works well the first time when there is no featured picture set, but when I try to change it from one featured picture to another, the previous featured picture gets removed and the new one doesn't get renamed to featured.jpg. All pictures are in the same folder.
Here is the relevant code:
if (isset($_POST['featured'])) {
$id = $_POST['id'];
$slike = glob('../img/uploads/'.$id.'/*.{jpg,png}', GLOB_BRACE);
if ($slike != null) {
foreach ($slike as $slika) {
$path = realpath($slika);
$name = basename($path);
if($name == basename($_POST['featured'])){
if(!file_exists(dirname($path) . '/featured.jpg')){
rename($path, dirname($path) . '/featured.jpg');
}else{
rename(dirname($path) . '/featured.jpg', dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
rename($path, dirname($path) . '/featured.jpg');
}
}else{
rename ($path, dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
}
}
}
}

PHP no image display from directory

When I run the PHP file, the image is not show, instead just the altattribute value shown which is 14.JPG . The page source is also accurate and the image is also exist in that folder.
Note - there are also some echo statements before this code. they are for other purposes.
Do I need to use headers also when displaying image this way?
$dir = "C:/xampp/htdocs/PHP";
$file = "14.JPG";
if ( file_exists($dir) == false ){
echo 'Directory \''. $dir. '\' not found!';
}
else{
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. '"/>';
}
The problem is you're getting the file path mixed up with the URL. The file path is C:/xampp/htdocs/PHP and the URL is http://localhost/PHP. You need to use the URL when setting links to file and images. Your image source should be http://localhost/PHP/14.JPG but you've set it to C:/xampp/htdocs/PHP/14.JPG. Change it and it'll work for you.
You apply wrong approach please use relative url make uploads folder in your PHP folder
$dir = "uploads/";
$file = "14.JPG";
if ( file_exists($dir) == false ){
echo $dir .'not found!';
}
else{
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. '"/>';
}
Change This
$dir = "C:/xampp/htdocs/PHP";
To This
$dir = "PHP/";

Getting the actual document root in PHP?

I'm not sure exactly where this script will be running, so it must be able to access this directory from anywhere.
I'm trying to create a list of images by getting the image file names from a directory, filtering them until I only have the image formats I want, then displaying them using an <img> tag.
The first bit went really well. Outputting the HTML is proving to be a problem.
While I can use $_SERVER["DOCUMENT_ROOT"] to work with the directories in PHP, it's problematic to output that value as part of the path in thetag'ssrc` attribute.
Here is my current code:
$unkwown_files = scandir($_SERVER['DOCUMENT_ROOT'] . "/path/images");
foreach($unkwown_files as $file) {
$exploded_filename = explode(".", $file);
$file_type = array_pop($exploded_filename);
$accepted_filetypes = [
"png",
"jpg",
"gif",
"jpeg"
];
$picture_names = [];
if (in_array($file_type, $accepted_filetypes)) {
$picture_names[] = $file;
}
}
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
A slightly different approach for you that filters files by extension from the outset.
$dir = $_SERVER['DOCUMENT_ROOT'] . "/path/images/";
/*
glob() searches for files/paths that match the pattern in braces and returns the results
as an array.
The '*' is a wildcard character as you would expect.
The flag 'GLOB_BRACE' expands the string so that it tries to match each
( From the manual: GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' )
*/
$col = glob( $dir . "*.{jpg,png,gif,jpeg}", GLOB_BRACE );
/*
Iterate through the results, with each one being the filepath to the file found.
As the glob() function searched for the required types we don't need to check
if they are in the allowed types array.
Because you do not wish to display the fullpath to the image, a relative path is
preferred - thus we remove, from the path, the document root.
*/
foreach( $col as $index => $file ){
$path_to_image = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $file );
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Try this out
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images/" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}

Categories