PHP- Delete images with the name "example" - php

How can I delete images in a folder that for example all have the name "john" in them. I am making a temporary image folder and I want to erase all of the users data on the temp folder after they're done.
Thanks.

Make use of PHP's built in DirectoryIterator to iterate across all the files in the images/ directory you want to modify.
$name = 'John';
$dir = new DirectoryIterator('images'); //In this case the images directory
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
//Is a valid file name
$filename = $fileinfo->getFilename();
//Now you have access to the filename make appropriate modifications. Below is a quick naive demonstration.
if (strpos($filename, $name)) {
//We have fulfilled the 'John' condition, delete the file
unlink('images/' . $filename);
}
}
}
You may need to modify the variables and directory names accordingly based on absolute or relative pathing to your situation. Make sure you have the appropriate permissions to (if relevant).

Something like this:
<?php
$NameToDelete = $_GET['name']; //ex: file.php?name=john
$Folder = "/images/"; //The folder you want to delete from
$FileType = array( //All the filetypes (in this case some image types
'jpg',
'png',
'bmp',
'jpeg'
);
foreach($FileType as $Type){//For EACH filetype as type
$Link = $_SERVER['DOCUMENT_ROOT']."$Folder".$NameToDelete."."."$Type"; //path
#unlink($Link); //DELETE - using # to not get any errors
echo "Deleted: $Link<br/>"; //Print
}

Related

How to copy an image from one folder to other in php

I have a image named xyz. Besides this file named xyz has unknown extension viz jpg,jpeg, png, gif etc. I want to copy this file from one folder named advertisers/images to other folder publishers/images in my website cpanl. How to do this with php. Thanks in advance.
You can use copy function:
$srcfile = 'source_path/xyz.jpg';
$dstfile = 'destination_path/xyz.jpg';
copy($srcfile, $dstfile);
You should write your code same as below:
<?php
$imagePath = "../Images/somepic.jpg";
$newPath = "../Uploads/";
$ext = '.jpg';
$newName = $newPath."a".$ext;
$copied = copy($imagePath , $newName);
if ((!$copied))
{
echo "Error : Not Copied";
}
else
{
echo "Copied Successful";
}
?>
Use copy() function
copy('advertisers/images/xyz.png','publishers/
images/xyz.png');
Change the file extension, whatever it is.
If you don't know the extension, go with the wildcard. It will give you the array of all the files matching with the wildcard.
$files = glob('advertisers/images/xyz.*');
foreach ($files as $file) {
copy($file,'publishers/images/'.$file);
}

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__

rename all the files in a folder

i have been trying to rename all the files (images) in a folder on my website but it does not work. the files are not renamed.
i have an input field for 'name' i want to use that name, add a uniqid and rename all the files.
here's the code that i am using:
<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {
$newName = uniqid().$name;
rename($directory.$file, $directory.$newName);
}}}
?>
besides, do i really need to _Post the $name variable?
P.S. i want to rename all the files and then copy them to another folder.
You don't need to POST name
glob is return you every files in folder with path // example /basic_images/test.jpg
then you just do foreach to loop over files, and update its name.
$path = "../basic_images/";
$directory = glob($path,"*.*");
foreach($directory as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$newName = uniqid().$ext;
rename($file, $path.$newName);
}
read more about glob : http://php.net/manual/en/function.glob.php
so, i finally solved the problem. now, instead of renaming the original files and then copying them to another folder, i just create new copies of the files with new names.
This is the code final code that works for me:
if(isset($_POST['submit'])){
$path = "../posts_images/";
$files = glob("../basic_images/*.*");
foreach($files as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$name = $_POST['new_name'];
$pic = uniqid().$name;
$newName = $pic.'.'.$ext;
copy($file, $path.$newName);
}}
it is important to use $pic.'.'.$ext because without it the new files don't have any extension.

php is_file not detecting image with period in name

I have a function which checks if image files exist. It works for all images, except when a period is inside the filename. The filenames are user uploaded, and many already exist that are not sanitized. Here is an example:
$img = 'nice_name.jpg'; // detects
$img = 'bad_name.7.jpg'; // doesn't detect
if (is_file($path . $img)) {
return $path . $prefix . $img;
}
I'm not sure how to escape this or make it work. I have doubled checked and the file does exist at that path. The function works for other image names in the same folder.
edit: This was marked a duplicate and linked to a question about uploading files. I am using is_file() to check if a file already exists. There is no uploading occurring, and the file already has the extra "." in its name on the server, so this is a different issue.
You can use basename() to get the file name, and then do something with it, like rename it if it contains a period.
$testfile = "test.7.img";
$extension = ".img";
$filename = basename($testfile, $extension);
if(strpos($filename,".") > 0) {
$newname = str_replace(".","",$filename) . $extension ;
rename($testfile,$newname);
}
//... then continue on with your code

Get Image File Extension with PHP

The file name is known but the file extension is unknown. The images in thier folders do have an extension but in the database their names do not.
Example:
$ImagePath = "../images/2015/03/06/"; (Folders are based on date)
$ImageName = "lake-sunset_3";
Does not work - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath))->getExtension();
echo $Ext;
Does not work either - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath.$ImageName))->getExtension();
echo $Ext;
Does not work either - $Ext is still empty:
$Ext = (new SplFileInfo($ImagePath,$ImageName))->getExtension();
echo $Ext;
$Ext should produce ".jpg" or ".jpeg" or ".png" etc.
So my question is simple: What am I doing wrong?
Now, this is a bit of an ugly solution but it should work. Make sure that all your files have unique names else you'll have several of the same file, which could lead to your program obtaining the wrong one.
<?php
$dir = scandir($imagePath);
$length = strlen($ImageName);
$true_filename = '';
foreach ($dir as $k => $filename) {
$path = pathinfo($filename);
if ($ImageName === $path['filename']) {
break;
}
}
$Ext = $path['extension'];
?>
Maybe this might help you (another brute and ugly solution)-
$dir = '/path/to/your/dir';
$found = array();
$filename = 'your_desired_file';
$files = scandir($dir);
if( !empty( $files ) ){
foreach( $files as $file ){
if( $file == '.' || $file == '..' || $file == '' ){
continue;
}
$info = pathinfo( $file );
if( $info['filename'] == $filename ){
$found = $info;
break;
}
}
}
// if file name is matched, $found variable will contain the path, basename, filename and the extension of the file you are looking for
EDIT
If you just want the uri of your image then you need to take care of 2 things. First directory path and directory uri are not the same thing. If you need to work with file then you must use directory path. And to serve static files such as images then you must use directory uri. That means if you need to check files exists or what then you must use /absolute/path/to/your/image and in case of image [site_uri]/path/to/your/image/filename. See the differences? The $found variable form the example above is an array-
$found = array(
'dirname' => 'path/to/your/file',
'basename' => 'yourfilename.extension',
'filename' => 'yourfilename',
'extension' => 'fileextension'
);
// to retrieve the uri from the path.. if you use a CMS then you don't need to worry about that, just get the uri of that directory.
function path2url( $file, $Protocol='http://' ) {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
$image_url = path2url( $found['dirname'] . $found['basename'] ); // you should get the correct image url at this moment.
You are calling a file named lake-sunset_3. It has no extension.
SplFileInfo::getExtension() is not designed to do what you are requesting it to do.
From the php site:
Returns a string containing the file extension, or an empty string if the file has no extension.
http://php.net/manual/en/splfileinfo.getextension.php
Instead you can do something like this:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
getExtension() only returns the extension from the given path, which in your case of course doesn't have one.
In general, this is not possible. What if there is a file lake-sunset_3.jpg and a file lake-sunset_3.png?
The only thing you can do is scan the directory and look for a file with that name but any extension.
You're trying to call an incomplete path. You could try Digit's hack of looking through the directory for for a file that matches the name, or you could try looking for the file by adding the extensions to it, ie:
$basePath = $ImagePath . $ImageName;
if(file_exists($basePath . '.jpg'))
$Ext = '.jpg';
else if(file_exists($basePath . '.gif'))
$Ext = '.gif';
else if(file_exists($basePath . 'png'))
$Ext = '.png';
else
$Ext = false;
Ugly hacks aside, the question begging to be asked is why are you storing them without the extensions? It would be easier to strip off the extension if you need to than it is try and find the file without the extension

Categories