PHP unlink(); No such file or directory - php

I searched everywhere for this problem and can't find the solution. I have this:
<?php
$file_name = $_GET['name'];
$file_delete = '../u/' . $file_name;
unlink($file_delete);
//header("location: $file_delete");
?>
unlink returns the error: No such file or directory, but if I try header("location: $file_delete"); it opens the file (picture in this case).
Where may I be wrong?

Get Absolute path first for the file to be deleted and check file exist before delete:
$file_name = $_GET['name'];
$base_dir = realpath($_SERVER["DOCUMENT_ROOT"]);
$file_delete = "$base_dir/your_inner_directories_path/$file_name";
if (file_exists($file_delete)) {unlink($file_delete);}

After some research, unlink() doesn't seem to allow you to use relative paths (with "../").
Here's an alternative:
<?php
$file_name = $_GET['name'];
$file_delete = dirname(__FILE__, 2) . '\\u\\' . $file_name;
unlink($file_delete);
?>
$file_delete here is the absolute path to the file you want to delete.
Reminder: / is used for Unix systems, \ for Windows.
PHP doc:
- http://php.net/manual/en/function.unlink.php
- http://php.net/manual/en/function.dirname.php

I also had same issue with my code. What I did to solve the issue is:
First execute:
var_dump($image_variable) // var_dump($file_delete) in your case.
It outputs: string(23)(my-image-path )
When I started counting string I just found 22 characters. I wondered where is the 23rd?
I checked and count carefully, at the end I found that there is space at the end of my image path. So I used php trim() function to remove white spaces. Like,
$trimed_path = trim($image_variable) // trim($file_delete) in your case.
Second: Now execute,
unlink($trimed_path).
OR CHECK LIKE
if(unlink($trimed_path))
{
echo "File Deleted";
}
else
{
echo "Error Deleting File";
}

Took me a couple of hours to figure out. As mentioned above unlink() is picky when it comes to paths.
Solution is:
1st) Define the path (this is how Wordpress does it btw):
define( 'ROOTPATH', dirname(dirname(__FILE__)) . '/' );
2) Do:
unlink(ROOTPATH.'public_html/file.jpg');

Related

If file with name.jpg exists do A else do B

I need to develop a little PHP script that I can run from a cron job which in pseudo code does the following:
//THIS IS PSEUDO CODE
If(file exists with name 'day.jpg')
rename it to 'fixtures.jpg'
else
copy 'master.jpg' to 'fixtures.jpg'
Where day.jpg should be the current day of the month.
I started to replace the pseudo code with the stuff I'm pretty sure how to do:
<?php
if(FILE EXISTS WITH NAME DAY.JPG) {
rename ("DAY.JPG", "fixtures.jpg");
} else {
copy ("master.jpg", "fixtures.jpg");
}
?>
Clearly there are still a few things missing. Like I need to get the filename with the current day of the month and I need to check if the file exists or not.
I guess I need to do something like this $filename='date('j');'.jpg to get the filename, but it isn't really working so I kinda need a bit help there. Also I don't really know how to check if a file exists or not?
$path = __DIR__; // define path here
$fileName = sprintf("%s%d.jpg", $path, date("j"));
$fixtures = $path . DIRECTORY_SEPARATOR . "fixtures.jpg";
$master = $path . DIRECTORY_SEPARATOR . "master.jpg";
file_exists($fileName) ? rename($fileName, $fixtures) : copy($master, $fixtures);
Basicly you need script like above but you need to work on your path. Your code above had syntax problem.
You have a basic syntax problem, it should be:
$filename = date('j') . '.jpg';
You don't put function calls inside quotes, you need quotes around the literal string '.jpg', and you need to use . to concatenate them.
I recommend you read the chapter on Strings in a PHP tutorial.

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

Best way to move entire directory tree in PHP

I would like to move a file from one directory to another. However, the trick is, I want to move file with entire path to it.
Say I have file at
/my/current/directory/file.jpg
and I would like to move it to
/newfolder/my/current/directory/file.jpg
So as you can see I want to retain the relative path so in the future I can move it back to /my/current/directory/ if I so require. One more thing is that /newfolder is empty - I can copy anything in there so there is no pre-made structure (another file may be copied to /newfolder/my/another/folder/anotherfile.gif. Ideally I would like to be able to create a method that will do the magic when I pass original path to file to it. Destination is always the same - /newfolder/...
You may try something like this if you're in an unix/linux environment :
$original_file = '/my/current/directory/file.jpg';
$new_file = "/newfolder{$original_file}";
// create new diretory stricture (note the "-p" option of mkdir)
$new_dir = dirname($new_file);
if (!is_dir($new_dir)) {
$command = 'mkdir -p ' . escapeshellarg($new_dir);
exec($command);
}
echo rename($original_file, $new_file) ? 'success' : 'failed';
you can simply use the following
<?php
$output = `mv "/my/current/directory/file.jpg" "/newfolder/my/current/directory/file.jpg"`;
if ($output == 0) {
echo "success";
} else {
echo "fail";
}
?>
please note I'm using backtick ` to execute instead of using function like exec

php loop folder get the file names and size

I want make a loop of my fold, get all the files and make a judge, print all the files name witch size are less than 10kb. But I get nothing from this code (no php error hint, just 0 result, and I am sure there has 10 files at lest < 10kb), where is the problem? Thanks.
$folder = dirname('__FILE__')."/../images/*";
foreach(glob($folder) as files){
$size = filesize(files);
if($size<10240){
echo files.'<br />';
}
}
I think there's a typo, because
dirname('__FILE__')
should be (without quotes)
dirname(__FILE__)
and also, your variable files doesn't have a dollar sign
$size = filesize($files);
and also here echo $files
That's it, it should fix your problem
__FILE__ is a magic constant, therefore you cannot wrap it in quotes:
$folder = dirname(__FILE__)."/../images/*";
You missed a $ in files:
$size = filesize($files);
// and
echo $files.'<br />';
Are you sure
$folder = dirname('__FILE__')."/../images/*";
is valid? do you mean
dirname(__FILE__)

Get the current script file name

If I have PHP script, how can I get the filename of the currently executed file without its extension?
Given the name of a script of the form "jquery.js.php", how can I extract just the "jquery.js" part?
Just use the PHP magic constant __FILE__ to get the current filename.
But it seems you want the part without .php. So...
basename(__FILE__, '.php');
A more generic file extension remover would look like this...
function chopExtension($filename) {
return pathinfo($filename, PATHINFO_FILENAME);
}
var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // string(15) "bob.i.have.dots"
Using standard string library functions is much quicker, as you'd expect.
function chopExtension($filename) {
return substr($filename, 0, strrpos($filename, '.'));
}
When you want your include to know what file it is in (ie. what script name was actually requested), use:
basename($_SERVER["SCRIPT_FILENAME"], '.php')
Because when you are writing to a file you usually know its name.
Edit: As noted by Alec Teal, if you use symlinks it will show the symlink name instead.
See http://php.net/manual/en/function.pathinfo.php
pathinfo(__FILE__, PATHINFO_FILENAME);
Here is the difference between basename(__FILE__, ".php") and basename($_SERVER['REQUEST_URI'], ".php").
basename(__FILE__, ".php") shows the name of the file where this code is included - It means that if you include this code in header.php and current page is index.php, it will return header not index.
basename($_SERVER["REQUEST_URI"], ".php") - If you use include this code in header.php and current page is index.php, it will return index not header.
This might help:
basename($_SERVER['PHP_SELF'])
it will work even if you are using include.
Here is a list what I've found recently searching an answer:
//self name with file extension
echo basename(__FILE__) . '<br>';
//self name without file extension
echo basename(__FILE__, '.php') . '<br>';
//self full url with file extension
echo __FILE__ . '<br>';
//parent file parent folder name
echo basename($_SERVER["REQUEST_URI"]) . '<br>';
//parent file parent folder name with //s
echo $_SERVER["REQUEST_URI"] . '<br>';
// parent file name without file extension
echo basename($_SERVER['PHP_SELF'], ".php") . '<br>';
// parent file name with file extension
echo basename($_SERVER['PHP_SELF']) . '<br>';
// parent file relative url with file etension
echo $_SERVER['PHP_SELF'] . '<br>';
// parent file name without file extension
echo basename($_SERVER["SCRIPT_FILENAME"], '.php') . '<br>';
// parent file name with file extension
echo basename($_SERVER["SCRIPT_FILENAME"]) . '<br>';
// parent file full url with file extension
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
//self name without file extension
echo pathinfo(__FILE__, PATHINFO_FILENAME) . '<br>';
//self file extension
echo pathinfo(__FILE__, PATHINFO_EXTENSION) . '<br>';
// parent file name with file extension
echo basename($_SERVER['SCRIPT_NAME']);
Don't forget to remove :)
<br>
alex's answer is correct but you could also do this without regular expressions like so:
str_replace(".php", "", basename($_SERVER["SCRIPT_NAME"]));
you can also use this:
echo $pageName = basename($_SERVER['SCRIPT_NAME']);
A more general way would be using pathinfo(). Since Version 5.2 it supports PATHINFO_FILENAME.
So
pathinfo(__FILE__,PATHINFO_FILENAME)
will also do what you need.
$argv[0]
I've found it much simpler to use $argv[0]. The name of the executing script is always the first element in the $argv array. Unlike all other methods suggested in other answers, this method does not require the use of basename() to remove the directory tree. For example:
echo __FILE__; returns something like /my/directory/path/my_script.php
echo $argv[0]; returns my_script.php\
Update:
#Martin points out that the behavior of $argv[0] changes when running CLI. The information page about $argv on php.net states,
The first argument $argv[0] is always the name that was used to run the script.
However, a comment from (at the time of this edit) six years ago states,
Sometimes $argv can be null, such as when "register-argc-argv" is set to false. In some cases I've found the variable is populated correctly when running "php-cli" instead of just "php" from the command line (or cron).
Please note that based on the grammar of the text, I expect the comment author meant to say the variable is populated incorrectly when running "php-cli." I could be putting words in the commenter's mouth, but it seems funny to say that in some cases the function occasionally behaves correctly. 😁
This works for me, even when run inside an included PHP file, and you want the filename of the current php file running:
$currentPage= $_SERVER["SCRIPT_NAME"];
$currentPage = substr($currentPage, 1);
echo $currentPage;
Result:
index.php
Try This
$current_file_name = $_SERVER['PHP_SELF'];
echo $current_file_name;
Although __FILE__ and $_SERVER are the best approaches but this can be an alternative in some cases:
get_included_files();
It contains the file path where you are calling it from and all other includes.
Example:
included File: config.php
<?php
$file_name_one = basename($_SERVER['SCRIPT_FILENAME'], '.php');
$file_name_two = basename(__FILE__, '.php');
?>
executed File: index.php
<?php
require('config.php');
print $file_name_one."<br>\n"; // Result: index
print $file_name_two."<br>\n"; // Result: config
?>
Try this
$file = basename($_SERVER['PATH_INFO']);//Filename requested
$filename = "jquery.js.php";
$ext = pathinfo($filename, PATHINFO_EXTENSION);//will output: php
$file_basename = pathinfo($filename, PATHINFO_FILENAME);//will output: jquery.js
__FILE__ use examples based on localhost server results:
echo __FILE__;
// C:\LocalServer\www\templates\page.php
echo strrchr( __FILE__ , '\\' );
// \page.php
echo substr( strrchr( __FILE__ , '\\' ), 1);
// page.php
echo basename(__FILE__, '.php');
// page
As some said basename($_SERVER["SCRIPT_FILENAME"], '.php') and basename( __FILE__, '.php') are good ways to test this.
To me using the second was the solution for some validation instructions I was making

Categories