i've code with which i want to check if there is some file located in folder. Every file has at start of filename 00'.$id'-time() so some example "00226-1413203222.pdf".
i have this code for checking if there is some file with that id :
$id = 226;
$searchpath = "files/00" . $id . "-*";
if (file_exists($searchpath)) {
...
...
...
but this code don't want to work, so probably i need some other method to do this?
Can u give me some good advices how to do this best way?
Thank you
Why not use scandir() like so
$id = "26";
$dir_path = "files";
$fileSearchRegex = "/^00".$id."-[0-9]*\.pdf$/";
$foundFile = array_map(function($file){
if(preg_match($fileSearch, $file))
return $file;
}, scandir($dir_path));
Related
In my images folder have file
1_cover.???
2_cover.???
3_cover.???
4_cover.???
5_cover.???
I wanna get file extension 4_cover.???
How to write PHP code
==========
UPDATE
Thanks for all help me,
I can use this code
$images = glob("./images/4_cover.*");
print_r($images);
Is that what you are looking for ?
$info = new SplFileInfo('photo.jpg');
$path = $info->getExtension();
var_dump($path);
PHP Documentation
If you want to look in a directory for files, this might not be the best suited way to do your method but since you don't know what the file-type is, you can do something like this: (all code should be in order from top-bottom)
The directory housing all of your files
$directory = "public/images/headers/*";
The files gathered from the glob function, use print_r($files) to see all of the files gathered for debugging if there's an error going on
$files = glob( $directory );
The file you said you were looking for, if this is from a database you'll replace this data with data from the database
$filename_to_lookfor = '4_cover.';
If statements to check the file types and see if they're existant
$file_types_to_check_for = ['gif', 'jpg', 'png'];
foreach ($file_types_to_check_for as $filetype)
if (in_array( $filename_to_lookfor.$filetype, $files)
echo "This is a {$filetype} file!";
After reading more into glob - I'm not too experienced with it.
You can simply write this line:
if (count($files = glob( 'public/images/4_cover.*' )) != 0) $file = $files[0]; else echo 'No file with extension!';
or
$file = (count($files = glob('public/images/4_cover.*') != 0)) ? $files[0] : 'NO_FILE' ;
I apologize for the quite bad quality code, but that's what OP wants and that's the easiest way I could think to do that for him.
You can use the pathinfo function
$file = "file.php";
$path_parts = pathinfo($file);
$path_parts['extension']; // return => 'php'
I am trying to copy a file that I download it. The file name is test1234.txt, but I want to access it using a wildcard like this: test*.txt and after that to move it to another folder (because I don't know how the file name looks like, but I know that the beginning is test and the rest is changing every time I download a new one). I tried some codes:
$myFile = 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNewFile = 'C:/Users/Carl/Downloads/'. date("y-m-d").'/text.xml';
if(preg_match("([0-9]+)", $myFile)) {
echo 'ok';
copy($myFile, $myNewFile);
}
I am getting an error because of * in $myFile. Any help is very appreciated.
$myFile= 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNyFile = 'C:/Users/Carl/Downloads/'.date("y-m-d").'/test.txt';
foreach (glob($myFile) as $fileName) {
copy($fileName, $myNyFile);
}
For complete response, if you want to only move *.txt in NewFolder.
$myFiles = 'C:/Users/Carl/Downloads/*.txt';
$myFolderDest = 'C:/Users/Carl/NewFolder/';
foreach (glob($myFiles) as $file) {
copy($file, $myFolderDest . basename($file));
}
i want to delete my pdf file from server. my controller function looks like
function delete_pdf()
{
$id = (isset($_GET['id']) && $_GET['id']!='')?$_GET['id']:'1';
$user_email = $this->session->userdata('user_email');
$file = site_url('pdf files/'.$user_email.'/pdf #'. $id.'.pdf');
unlink($file);
}
when i echo $file;, it gives url http://localhost/my_site/pdf files/developer_team#gmail.com/pdf #4.pdf but the function not working to delete the pdf file.
I would appreciate for any help where i can delete my pdf files from server. thank you.
we can't delete file using URL. we need absolute path. try this-:
$file = FCPATH.'pdf files/'.$user_email.'/pdf #'. $id.'.pdf';
try to remove space in pdf #4.pdf in your url
http://localhost/my_site/pdf files/developer_team#gmail.com/pdf #4.pdf
You need the absolute path to the file, I mean something like this
/Users/me/..../my_sites/pdf
The path depends of where is your controller. I don't know how codeigniter works.
EDIT
$file = dirname(__FILE__). DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'pdf files/'.$user_email.'/pdf #'. $id.'.pdf';
It will give you this :
C:\xampp\htdocs\my_site\application\controllers\..\..\pdf files\developer_team#gmail.com\pdf #4.pdf
I'm trying to create a folder tree from an array, taken from a string.
$folders = str_split(564);
564 can actually be any number. The goal is to create a folder structure like /5/6/4
I've managed to create all folders in a single location, using code inspired from another thread -
for ($i=0;$i<count($folders);$i++) {
for ($j=0;$j<count($folders[$i]);$j++) {
$path .= $folders[$i][$j] . "/";
mkdir("$path");
}
unset($path);
}
but this way I get all folders in the same containing path.
Furthermore, how can I create these folders in a specific location on disk? Not that familiar with advanced php, sorry :(
Thank you.
This is pretty simple.
Do a for each loop through the folder array and create a string which appends on each loop the next sub-folder:
<?php
$folders = str_split(564);
$pathToCreateFolder = '';
foreach($folders as $folder) {
$pathToCreateFolder .= DIRECTORY_SEPARATOR . $folder;
mkdir($folder);
}
You may also add the base path, where the folders should be created to initial $pathToCreateFolder.
Here you'll find a demo: http://codepad.org/aUerytTd
Or you do it as Michael mentioned in comments, with just one line:
mkdir(implode(DIRECTORY_SEPARATOR, $folders), 0777, TRUE);
The TRUE flag allows mkdir to create folders recursivley. And the implode put the directory parts together like 5/6/4. The DIRECTORY_SEPARATOR is a PHP constant for the slash (/) on unix machines or backslash (\) on windows.
Why not just do:
<?php
$directories = str_split(564);
$path = implode(DIRECTORY_SEPARATOR, $directories);
mkdir($path, 0777, true);
Don't know what you're really trying to do, but here are some hints.
There are recursive mkdir:
if(!file_exists($dir)) // check if directory is not created
{
#mkdir($dir, 0755, true); // create it recursively
}
Path you want can be made in two function calls and prefixed by some start path:
$path = 'some/path/to/cache';
$cache_node_id = 4515;
$path = $path.'/'.join('/', str_split($cache_node_id));
Resulting path can be used to create folder with the code above
So here we come to a pair of functions/methods
function getPath($node_id, $path = 'default_path')
{
return $path.'/'.join('/', str_split($node_id))
}
function createPath($node_id, $path = 'default_path');
{
$path = getPath($node_id, $path);
if(!file_exists($path)) // check if directory is not created
{
#mkdir($path, 0755, true); // create it recursively
}
}
With these you can easily create such folders everywhere you desire and get them by your number.
As mentioned earlier, the solution I got from a friend was
$folders = str_split(564);
mkdir(implode('/',$folders),0777,true);
Also, to add a location defined in a variable, I used
$folders = str_split($idimg);
mkdir($path_defined_earlier. implode('/',$folders),0777,true);
So thanks for all the answers, seems like this was the correct way to handle this.
Now the issue is that I need to the created path, so how can I store it in a variable? Sorry if this breaches any rules, if I need to create a new thread I'll do it...
The script I made is.
<?php
$source_file = 'http://www.domain.tld/directory/img.png';
$dest_file = '/home/user/public_html/directory/directory/img.png';
copy($source_file, $dest_file);
?>
I need that image to not be delete and reuploaded every time the script is running. I would either want it to be img1.png, img2.png, img3.png, etc. Or img(Date,Time).png, img(Date,Time).png, etc. Is this possible and if so, how do I do this?
If you're concerned with overwriting a file, you could just drop in a timestamp to ensure uniqueness:
$dest_file = '/home/user/public_html/directory/directory/img.png';
// /home/user/public_html/directory/directory/img1354386279.png
$dest_file = preg_replace("/\.[^\.]{3,4}$/i", time() . "$0", $dest_file);
Of if you wanted simpler numbers, you could take a slightly more tasking route and change the destination file name as long as a file with that name already exists:
$file = "http://i.imgur.com/Z92wU.png";
$dest = "nine-guy.png";
while (file_exists($dest)) {
$dest = preg_replace_callback("/(\d+)?(\.[^\.]+)$/", function ($m) {
return ($m[1] + 1) . $m[2];
}, $dest);
}
copy($file, $dest);
You may need to be using a later version of PHP for the anonymous function callback; I tested with 5.3.10 and everything worked just fine.
<?php
$source_file = 'http://www.domain.tld/directory/img.png';
$dest_file = '/home/user/public_html/directory/directory/img.png';
if(!is_file($dest_file)){
copy($source_file, $dest_file);
}
else{
$fname = end(explode('/',$dest_file));
$fname = time().'-'.$fname;
$dest_file = dirname($dest_file).'/'.$fname;
copy($source_file,$dest_file);
}
?>
use this code
This will add time before filename
$source_file = 'http://www.domain.tld/directory/img.png';
$dest_file = '/home/user/public_html/directory/directory/img'.uniqid().'.png';
copy($source_file, $dest_file);
uniquid gives you a unique Id which is rarely possible to overwrite...
also i would make folders for each month or related to the id of the image
like
mkdir(ceil($imgId / 1000), 0777);
You can use rename().
For Example:
rename ("/var/www/files/file.txt", "/var/www/sites/file1.txt");
Or
You can also use copy
$source_file = 'http://www.domain.tld/directory/img.png';
$dest_file = '/home/user/public_html/directory/directory/img.png';
if(!is_file($dest_file)){
copy($source_file, $dest_file);
}
Or if you want to add time it ,you can try like this.
$source="http://www.domain.tld/directory/";
$destn ="/home/user/public_html/directory/directory/";
$filename="image.png";
$ex_name = explode('.',$filename));
$newname = $ex_name[0].'-'.time().$ex_name[1]; //where $ex_name[0] is filename and $ex_name[1] is extension.
copy($source.filename,$destn.$newname );