How to pass url to read png files in php - php

If I do
$dir = './';
$files = glob( $dir . '*.png');
foreach( $files as $file) {
echo $file;
}
?>
And store the php file in the same folder as images I would get correct png files.
If I change location of php file How can I read png files located in other folder?
If I do
$dir = 'www.site.com/content/images';
$files = glob( $dir . '*.png');
foreach( $files as $file) {
echo $file;
}
it does not display anything, is it necessary to the php file with code to be in the same folder of images?

You shouldn't add "www.site.com" to path. You should use absolute path from the root of your server (beginning with "/": /content/images) or relative path from current location of php script (content/images).

If you are in fact trying to retrieve files on a remote server, look at this:
http://www.php.net/manual/en/features.remote-files.php

Related

php script to delete file names not matching a dynamic text file

I have created a text file (images.txt) located in /home/users/images.txt, the File contain names of jpeg files. for example:
1.jpeg
12.jpeg
33.jpeg
This file is updated regularly and new image filenames are added
I am looking for a php script that can help in reading the filenames from the .txt and deleting any files from /home/user/images/ directory that does not match the filenames in the .txt file
I have tried the below code and cant get it to work
$array = explode("\n", file_get_contents('/home/user/images.txt'));
$directory = "/home/user/images/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array($file, $array)) {
unlink($directory . $file);
}
}
The names returned by glob() include the directory prefix, but the names in $array don't have them. You need to remove the prefix before searching, and you don't need to add it when calling unlink().
$array = file('/home/user/images.txt', FILE_IGNORE_NEW_LINES);
$directory = "/home/user/images/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array(basename($file), $array)) {
unlink($file);
}
}

How to get filename from image pulled in through glob directory [duplicate]

How can I just return the file name. $image is printing absolute path name?
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
foreach($images as $image)
echo $image
?>
All I want is the file name in the specific directory not the absolute name.
Use php's basename
Returns trailing name component of path
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
foreach($images as $image)
echo basename($image);
?>
Instead of basename, you could chdir before you glob, so the results do not contain the path, e.g.:
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
chdir($directory); // probably add some error handling around this
$images = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
foreach($images as $image)
echo $image;
?>
This is probably a little faster, but won't make any significant difference unless you have tons of files
One-liner:
$images = array_map('basename', glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE));
Use basename()
echo basename($image);
You can also remove the extension like this:
echo basename($image, '.php');
Take a look at pathinfo
http://php.net/manual/en/function.pathinfo.php
Pretty helpful function
Example extracting only file names and converting in new array of filenames width extension.
$dir = get_stylesheet_directory();//some dir - example of getting full path dir in wordpress
$filesPath = array_filter(glob($dir . '/images/*.*'), 'is_file');
$files = array();
foreach ($filesPath as $file)
{
array_push($files, basename($file));
}
If you're nervous about the unintended consequences of changing the working directory, you can store the current dir with getcwd() before changing, then simply use that value to switch back after you've done everything you need to do in that dir.
<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$working_dir = getcwd();
chdir($directory);
$files = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
chdir($working_dir);
?>

How to delete a file which have such type of extensions in php?

What I'm trying to do is, to delete files which includes only such type of extensions.
Let's say a folder Images/ contains following files,
a.jpg
b.jpeg
c.php
d.php2
c.png
So now I want to delete only those c.php,d.php2. Is there any way to do this in a single step or any ideas ?
Note: In this case, I do not know exact name of the file or extension.
Thank you in advance.
To delete specific extension files from sub directories, you can use the following function. Example:
<?php
function delete_recursively_($path,$match){
static $deleted = 0,
$dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if(is_file($file)){
$deleted_size += filesize($file);
unlink($file);
$deleted++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
delete_recursively_($path.$dir,$match);
}
}
return "$deleted files deleted with a total size of $deleted_size bytes";
}
?>
e.g. To remove all text files you can use it as follows:
<?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>

How to store uploaded files in a directory of the main domain from a subdomain upload form

please how can store uploaded file in my main domain directory should it be like this:
move_uploaded_file(https://example.com/uploads)
First step is to start here with handling uploaded files:
http://php.net/manual/en/function.move-uploaded-file.php
The first example is almost exactly what you want:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:
$uploads_dir = __DIR__ . '/../public_html/uploads';
__DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.
The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.
This would be a quick and dirty way to do it( assuming you're in the root directory of your subdomain and your main domain is its own folder( if your main directory does not have its own folder remove the 2nd chdir)
Im assuming youre uploading an image. if not make the changes as necessary
chdir(dirname("../"));// this takes you up one level
chdir("main_directory");// use this only if main directory is inside a folder
$filepath = getcwd() . DIRECTORY_SEPARATOR . 'images' .DIRECTORY_SEPARATOR;
if (!file_exists($filepath)) {
mkdir($filepath, 0755);// this is only to create a new images folder if it doesnt exist
}
chdir($filepath);
$filename = 'file_name_you_want';
$info = pathinfo($_FILES['img']['name']);
$ext = $info['extension'];
$newname = $filename . "." . $ext;
$types = array('image/jpeg', 'image/jpg', 'image/png');
if (in_array($_FILES['img']['type'], $types)) {
if (move_uploaded_file($_FILES["img"]["tmp_name"], $newname)) {
$img_path = 'images' . DIRECTORY_SEPARATOR . $newname;
} else {
// do what needs to be done
}
If youre using php 7 you might want to take a look at string
dirname ( string $path [, int $levels = 1 ] );// the 2nd param would be how many levels up you want to go and $path can be your current directory using __DIR__

PHP copy all images folder from one folder to another

I am working on some code that will take all the images in one folder and copy them into another folder and then delete the original folder and it content.
I have:
copy('images/old-folder/*', 'images/new-folder/');
unlink('images/old-folder/');
but this does not work :( but it doesn't work I mean the files dont copy over and the old-folder is not deleted :(
I even tried:
system('cp images/old-folder/* images/new-folder/');
and that didn't work either :( Please help.
I have even tried to change the permissions of the two folders:
chmod('images/old-folder/', 0777);
chmod('images/new-folder/', 0777);
foreach(glob('images/old-folder/*') as $image) {
copy($image, 'images/new-folder/' . basename($image)); unlink($image);
}
rmdir('images/old-folder');
check the docs: glob, rmdir, also you might find user comments on rmdir useful.
EDIT:
added basepath to the second parameter to the copy function which has to be an actual path and not a directory.
<?php
$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
}
?>
Found here: PHP copy all files in a directory to another?
Here is a modified version from #Prasanth that should work (not tested)
<?php
$oldfolder = 'images/new-folder';
$newfolder = 'images/old-folder';
$files = glob($oldfolder . '/*');
foreach($files as $file){
$filename = basename($file);
copy($file, $oldfolder . '/' . $filename);
unlink($file);
}
rmdir($oldfolder);
?>

Categories