Find full file name using wildcards using glob - php

I would like to search for the full name of the .jpg image using only the numbers.
I have a folder called "Pictures" and inside all of the pictures are named something like this:
100-Lisa_Person1.jpg
150-BillJohnson.jpg
160-BlakeSmith(1).jpg
and so on....
THE CODE:
$contact_lastname = 150;
$files = glob("C:\Pictures\\" . $contact_lastname . "*.jpg"); // Will find my .jpg
// Process through each file in the list
// and output its extension
if (count($files) > 0)
foreach ($files as $file)
{
$info = pathinfo($file);
echo "File found: extension ".$info["extension"]."<br>";
}
else
echo "No file name exists called $compartment. Regardless of extension."
So this is what I tired but it's saying: File found: extension jpg but I need to know the full file name of the image it found.

Well the full name of the file would be
$info["basename"]
This is because the pathinfo() function returns an array with these indexes:
dirname - the path of the files parent folder.
basename - the full name of the file, including extension.
extension - the extension of the file (this is what you used and is why you only got the extension).
filename - the name of the file without the extension.

Related

PHP: connect X.pdf to X.png in a chosen directory

I am looking for a PHP script that connects *.PDF to *.PNG files in a directory. Due to lack of PHP knowledge, I only know how to do this manually in HTML. Could PHP do this for me automatically by connecting A.pdf with A.png, B.pdf with B.png, C.pdf with C.png and so on? Then all I need to be able doing is to change the folder name in PHP.
<div><img src="FOLDER/A.png"></div>
<div><img src="FOLDER/B.png"></div>
<div><img src="FOLDER/C.png"></div>
etcetera...
I'm not sure if I understood this correctly, but the code below will get all .pdf files from a directory and return the HTML for each .pdf file. This will also check to see if the .png exists, but will not echo anything if it does not exist.
// get all .pdf files from directory
$directory = "directory/";
$files = glob($directory."*.{[pP][dD][fF]}", GLOB_BRACE);
foreach ($files as $item) {
// get pathinfo to get the filename
$fileInfo = pathinfo($item);
$fileName = $fileInfo['filename'];
// check if the .png exists
if (file_exists($directory.$fileName.".png")) {
// echo
echo "<div><a href='".$directory.$fileName.".pdf'><img src='".$directory.$fileName.".png'></a></div>";
}
}

Getting error when renaming file in PHP

I am uploading a file using PHP to a folder in my directory and am unable to rename it using the following code
$da = date("dmY");
$ja = $uid.$da;
$mukesh = $app.$ja;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['userfile'][$mukesh], $uploadpath));
Here's PHP's official document about how to handle uploads: http://www.php.net/manual/en/features.file-upload.post-method.php
The method move_uploaded_file() requires two parameters, a filename of the temp file, and a new location.
$tmp = $_FILES['userfile']['tmp_name']; // temp path
move_uploaded_file($tmp, $uploadpath . '/' . $mukesh);
You will need to name your input element userfile.
<input type="file" name="userfile" />
Based on code snippet provided, you can do following
move_uploaded_file ($_FILES["userfile"]["tmp_name"], $uploadpath);
When you upload a file, files will be store in upload location specified in php.ini using a temporary name. This file location with name can be accessed by $_FILES["userfile"]["tmp_name"]
Lets say you upload an image.if no error then
$uploads_dir = 'as per you defined';
$tmp_name = $_FILES["userfile"]["tmp_name"];
$name = 'custom_file_name.png';//$_FILES["userfile"]["name"];
move_uploaded_file($tmp_name, $uploads_dir."/".$name);
You are renaming the temp name of file ...
When you want to rename the change the name with which you want to store the file
$filename = time().$_FILES['userfile']['name'];
$upload_path = 'path_to_ur_upload_folder'.$filename;
move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path );
first param in move_upload_file is temporary name that will be used by stream while copying an d uploading .. the second parameter is path where your file will be saved (along with file name).. it is the second parameter which will help you in renaming of file which is being uploaded

Zipping up a folder without extra folders in the zipped file

So, I understand it's pretty easy to zip a folder and its contents given that php.net and stackoverflow are full of sample codes. I am trying to zip up a folder as well. This is my code:
$zip = new ZipArchive;
$zip->open('myzip.zip', ZipArchive::CREATE);
foreach (glob("/Volumes/Data/Users/username/Desktop/Archive/some/thisFolder/*") as $file) {
$zip->addFile($file);
}
$zip->close();
My script is running in a folder, say on Desktop, and I want to zip thisFolder and its contents. The above code WORKS. But, the problem is that when I unzip the myzip.zip created, I get a structure like
Volumes>Data>Users>username>Desktop>Archive>some>thisFolder
and then I find the contents inside the 8th folder (thisFolder) in this case. How can I change this code so that when I unzip myzip.zip,I would straightaway see the folder thisFolder with the contents inside it instead of having to navigate through folders 7 times before getting my content?
I tried to change the path and silly things like that. But, it doesn't work.
Thanks
If you want everything in the file to be a name relative to your starting folder, use chdir() to start from there:
chdir("/Volumes/Data/Users/username/Desktop/Archive/some/thisFolder");
foreach (glob("*") as $file) {
$zip->addFile($file);
}
Actually, I don't think this will work when $file is a subdirectory -- addFile doesn't recurse automatically. There's a comment in the documentation that shows how to write a recursive zip function:
http://www.php.net/manual/en/ziparchive.addemptydir.php
bool ZipArchive::addFile ( string $filename [, string $localname ] )
filename
The path to the file to add.
localname
local name inside ZIP archive.
You can use the pathinfo function to each $file in your loop, in order to retrieve the filename without the path, and then, use it as second parameter to the addFile method.
pathinfo doc here
Here is an example that could solve your problem:
// Create your zip archive
$zip = new ZipArchive;
// open it in creation mode
$zip->open('myzip.zip', ZipArchive::CREATE);
// Loop on all your file
$mask = "/Volumes/Data/Users/username/Desktop/Archive/some/thisFolder";
$allAvailableFiles = glob($mask . "/*")
foreach ($allAvailableFiles as $file)
{
// Retrieve pathinfo
$info = pathinfo($file);
// Generate the internal directory
$internalDir = str_replace($mask, "", $info['dirname']);
// Add the file with internal directory
$zip->addFile($file, $internalDir . "/" . $info['basename']);
}
$zip->close();

Check for file with same filename, but different extension

I have a directory contain jpeg and raw image files. Some jpeg files have a raw file version of them, some don't. Luckily, if a jpeg has a raw file they are named the same (excluding the extension). So, I need a way to check this directory for a matching raw file of the same filename, exclusing file extesion. the raw file, file extension could be pretty much anything.
Any ideas how I can do this? I have the filename (excluding extesion) stored of $filename at the moment.
To explain further. I have a directory with the following files in it:
cat.jpg
dog.jpg
bird.jpg
cat.raf
dog.foo
I need to match cat.jpg to cat.rag and dog.jpg to dog.foo. These have just been extracted from a uploaded zip file.
Try searching for files starting with the same name:
$fileWithoutExtension = basename($filename, '.jpg');
$allFilesWithThisName = glob($fileWithoutExtension . '.*');
if (count($allFilesWithThisName)) {
echo 'There is another file with this name';
}
As you already have the filename w/o the extension, you can just check if the raw file exists (file_exists()):
if (file_exists($filename.'.raw')) {
echo 'RAW file exists:', $filename , "\n";
}
But this seems so trivial to me, that I might did not understood your question completely.

How we can read zip file and get information of files or folders contains without unzipping in PHP?

What I actually wanted to do is read zip file and then if it does contain folder then refuse it with some message.
I want user should upload zip file with files only without any directory structure.
So I want to read zip file contains and check file structure.
I am trying with following code snippet.
$zip = zip_open('/path/to/zipfile');
while($zip_entry = zip_read($zip)){
$filename = zip_entry_name($zip_entry);
//#todo check whether file or folder.
}
I have sorted out.
I am now checking filename as strings wherever I am getting string ending with "/" that am treating as directory else as file.
can't you parse path of $filename? something like $dirName = pathinfo($filename, PATHINFO_DIRNAME)

Categories