How to use Unlink() function - php

I'm trying to use PHP unlink() function to delete away the specific document in the folder. That particular folder has already been assigned to full rights to the IIS user.
Code:
$Path = './doc/stuffs/sample.docx';
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
It keep return fail. The sample.docx does reside on that particular path. Kindly advise.

I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual
error to unlink file. To delete file you must to change the file's owner.
An example:
chown($tempDirectory . '/' . $fileName, 666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($tempDirectory . '/' . $fileName);
So try something like this:
$path = './doc/stuffs/sample.docx';
chown($path, 666);
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
EDIT 1
Try to use this in the path:
$path = '.'
. DIRECTORY_SEPARATOR . 'doc'
. DIRECTORY_SEPARATOR . 'stuffs'
. DIRECTORY_SEPARATOR . 'sample.docx';

Try this:
$Path = './doc/stuffs/sample.docx';
if (file_exists($Path)){
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
} else {
echo "file does not exist";
}
If you get file does not exist, you have the wrong path. If not, it may be a permissions issue.

This should work once you are done with the permission issue. Also try
ini_set('display_errors', 'On');
That will tell you whats wrong

define("BASE_URL", DIRECTORY_SEPARATOR . "book" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$path = "doc/stuffs/sample.docx";
if (unlink(ROOT_PATH . $Path)) {
echo "success";
} else {
echo "fail";
}
// http://localhost/book/doc/stuffs/sample.docx
// C:/xampp/htdocs\book\doc/stuffs/sample.docx

You need the full file path to the file of interest. For example: C:\doc\stuff\sample.docx. Try using __DIR__ or __FILE__ to get your relative file position so you can navigate to the file of interest.

Related

php copy function from one folder to another

Here is my code, what I am trying to do is take the file post.php or $file from the root of the directory that it is originally from, then put it inside this uniqueID directory, or it should finally arrive in the $newFolder5 variable to complete. The $root in the !copy function is a path pointing to the file inside the current directory, then it should go it the $newFolder5 directory when the copy function is executed on the page load. Can $root or the source of the copy be a string with a directory to the file?
<?php
$unique = uniqid();
$root = '/gallry/' . $dir_auth1 . '/'. 'post.php';
$folder = mkdir($unique, 0755);
$uniqueFolder = '/' . $unique . '/' . 'post.php';
$destination2 = $dir_auth1 . '/' . $unique . '/' . 'post.php';
$newFolder = '/' . $dir_auth1 . $uniqueFolder;
if (!copy($root, $newFolder)) {
echo " status not created.";
} else {
echo "Success!";
}
?>
I changed $dir_auth1 to 'aidan', since that is the root directory that the post.php is in.
In short, what Im trying to do is create a folder/directory with a uniqid() and put post.php inside of it. Or copy it.
You're not creating the same directory that you're trying to copy into.
$unique = uniqid();
$root = "/gallry/$dir_auth1/post.php";
$uniqueFolder = "/$dir_auth1/$unique";
$destFile = "$uniqueFolder/post.php";
if (mkdir($uniqueFolder)) {
if (copy($root, $destFile)) {
echo "Success!";
} else {
echo " status not created";
}
} else {
echo "Unable to create folder $uniqueFolder";
}

Having an issue with the fopen() php function

I have a users directory and a child directory for the login/register system. I have a file, testing.php, to try to figure out how to create a directory in the users directory AND create a PHP file within that same directory. Here's my code:
<?php
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = "../" . "ActivationFile";
fopen("$file", "w");
?>
I'm able to get mdkir($directory) to work, but not the fopen("$file", "w").
Try this, this should normally solve your problem.
PHP delivers some functions to manipulate folder & path, it's recommended to use them.
For example to get the current parent folder, you can use dirname function.
$directoryname = dirname(dirname(__FILE__)) . "/SomeDirectory";
if (!is_dir($directoryname)) {
mkdir($directoryname);
}
$file = "ActivationFile";
$handle = fopen($directoryname . '/' . $file, "w");
fputs($handle, 'Your data');
fclose($handle);
This line is equivalent to "../SomeDirectory"
dirname(dirname(__FILE__)) . "/SomeDirectory";
So when you open the file, you open "../SomeDirectory/ActivationFile"
fopen($directoryname . '/' . $file, "w");
You can use the function touch() in order to create a file:
If the file does not exist, it will be created.
You also forgot to re-use $directory when specifying the filepath, so the file was not created in the new directory.
As reported by Fred -ii- in a comment, error reporting should also be enabled. Here is the code with these changes:
<?php
// Enable error output, source: http://php.net/manual/en/function.error-reporting.php#85096
error_reporting(E_ALL);
ini_set("display_errors", 1);
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = $directory . "/ActivationFile";
touch($file);
try this:
$dirname = $_POST["DirectoryName"];
$filename = "/folder/{$dirname}/";
if (file_exists($filename)) {
echo "The directory {$dirname} exists";
} else {
mkdir("folder/{$dirname}", 0777);
echo "The directory {$dirname} was successfully created.";
}

File exists issues

I'm attempting to try and debug the following code with the file_exists function. I've ran a var_dump on the avatar directory and it always returns as bool(false). I'm not sure why. I tested the code below and it gets to the file exists but it proves the if statement false everytime. Any thoughts? I have looked and the image is in the directory correctly.
$default_avatar = 'default.jpg';
$avatar_directory = base_url() . 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists($avatar))
{
$user_data->avatar = $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
$default_avatar = 'default.jpg';
$avatar_directory = 'assets/globals/images/avatars/';
if (!is_null($user_data->avatar))
{
$avatar = $avatar_directory . $user_data->avatar;
if (file_exists(FCPATH . $avatar))
{
$user_data->avatar = base_url() . $avatar_directory . $user_data->avatar;
}
else
{
$user_data->avatar = base_url() . $avatar_directory . $default_avatar;
}
}
else
{
$user_data->avatar = $default_avatar;
}
from the name base_url seems like a function that will get a url like http://www.mysite.com, which will not work for doing local directory functions.
you need something like getcwd, or a full path
getcwd will get the current working directory (the directory where the initial script was executed from):
//If say script.php was exectued from /home/mysite/www
$avatar_directory = getcwd() . '/assets/globals/images/avatars/';
//$avatar_directory would be
/home/mysite/www/assets/globals/images/avatars/
Well this works both CLI and via Apache etc...:
$avatar_directory = substr(str_replace(pathinfo(__FILE__, PATHINFO_BASENAME), '', __FILE__), 0, -1) . '/assets/globals/images/avatars/'
The did returned is the one that the php file itself is in, not the root.
assuming you meant base_url() to point to the root of your project -
$file = __DIR__ . "/path/to/file.ext";
if (file_exists($file)) {
//...
}
Or some variation thereof. This also works:
__DIR__ . "/.."
it resolves to the parent directory of __DIR__.
see PHP's magic constants:
http://php.net/manual/en/language.constants.predefined.php
If you are looking for a remote resource - a file not located on your local filesystem - you have to change your php.ini to permit that. And it's probably not a good idea, this is not usually considered safe or secure. At all.
http://php.net/manual/en/features.remote-files.php
And note:
"This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir."
-- from http://php.net/manual/en/function.file-exists.php
-- edited to add relevant information based on a comment from OP.

How do I set relative paths in PHP?

I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>

PHP Delete File script

I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)

Categories