Php unlink file which is in use situation? - php

In my personal experience, you cannot delete something that's in use, I think unlink() will not work if the target file is in use, how do you handle that?
<?php unlink ("notes.txt"); // how to handle if file in use? ?>

unlink returns a boolean that you can use to detect if deletion was successful or not:
<?php
$file = fopen('notes.txt','w');
fwrite($file,'abc123');
$resul = unlink("notes.txt"); // ◄■■■ ATTEMPT TO DELETE OPEN FILE.
if ( $resul )
echo "File deleted";
else echo "File NOT deleted (file in use or protected)";
fclose($file);
?>
You might see a warning message on screen, so turn off warnings and let your code (the if($resul)) handle the problem.
Edit :
It's possible to detect whether the file is in use or it is protected by using the function is_writable, next code shows how :
<?php
$file = fopen("notes.txt","w"); // ◄■■■ OPEN FILE.
fwrite($file,"abc123");
$resul = unlink("notes.txt"); // ◄■■■ ATTEMPT TO DELETE FILE.
if ( $resul ) // ◄■■■ IF FILE WAS DELETED...
echo "File deleted";
elseif ( is_writable( "notes.txt" ) ) // ◄■■■ IF FILE IS WRITABLE...
echo "File NOT deleted (file in use)";
else echo "File NOT deleted (file protected)";
fclose($file);
?>
To test previous code, open the properties of the file and set it to readonly and hidden, then run the code.

Related

PHP create and write form

I have a form with two fields. The first textbox the users enter information into is what I would like to name the file that is being saved, and the second textarea is for what I would like written into the file. I am able to write to a file I have already created using php coding below which I did simply to test the function:
<?php
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST CodeDescription';
// Get current working directory
echo getcwd();
// This should output /home/revo/public_html/evo/users
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( is_file( $FILENAME ) ):
// Open the text file
$f = fopen($FILENAME, "w");
// Write text
file_put_contents($FILENAME, $_POST['Code']);
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen($FILENAME, "r");
else:
echo 'Filename already exists';
endif;
?>
However I am unsure how to check to see if a file with the name they enter into the first box exists, and then if not create it, then write the information from the second box into the file.
<?php
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// Get current working directoty
//echo getcwd(); // Debugging output
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)) mkdir($USER_DIRECTORY);
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
//echo $FILENAME; // Debugging output
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
// Use file_get_contents() to read the file.
// $read_contents = file_get_contents($FILENAME);
else:
echo 'Filename already exists';
endif;
?>
you can use $_POST to get the contents of the textarea and input field.
$file_name = $_POST['filename'];
$contents = $_POST['code'];
$file = '../evo/avsave/'.$file_name . '.txt';
//writing the file
if(!file_exists($file)){
file_put_contents($file,$contents);
}else{
echo 'File exists';
}

Store Image from PHP to MYSQL

I have a PHP file with code as below with the functionality to save an image in a file directory , after uploading from mobile.
<?PHP
$data = file_get_contents('php://input');
echo $data;
exit ($data);
if (!(file_put_contents($_GET['filename'],$data) === FALSE)) echo "File xfer completed."; // file could be empty, though
else echo "File xfer failed.";
?>
We dont have much control on the front end side to change , so the logic of storing an image in MY SQL db should be from PHP script.
the $data echo results as below for an image of JPG format http://goo.gl/4AsU52
$data Echo :
Now , how do i store the $data value/its relative file directory in php into MYSQL DB?

Unable to read file in directory with file_get_contents - PHP

I have a file present in a directory content that contains a file to read from. On my MAMP installation, content/ is present in the webroot folder (/Applications/MAMP/htdocs/testApp/content). I am unable to read the file (test.txt) from the folder. The function I am using is:
function getDataFromLibrary($tgt_url) {
//header('Content-Type: text/html; charset=UTF-8');
echo "inside get data from lib.";
if(file_exists($tgt_url)) {
echo "File does exist.";
if(is_readable($tgt_url)) {
echo "file is readable.";
} else {
echo "file is not readable.";
}
} else {
echo "File does not exist.";
}
echo "tgt url = ".$tgt_url."the end.";
$file_contents = file_get_contents(urlencode($tgt_url));
if($file_contents === false) {
echo "could not read file contents.";
} else {
echo "file contents read.";
}
echo "Target url=".var_dump($tgt_url)."again the end.";
echo "File contents = ".$file_contents;
//$file_contents_replaced = str_replace($file_contents, "\"", "\\\"");
//echo $file_contents_replaced;
//var_dump($file_contents);
//return $tgt_url;
}
and the output I get when $tgt_url = content/test.txt is:
inside get data from lib.File does exist.file is readable.tgt url = content/test.txtthe end.could not read file contents.string(33) "content/test.txt" Target url=again the end.File contents =
The file does exist and is also readable. Where am I going wrong?
Any help is most welcome.
Edit:
I turned on the following errors in php.ini:
display_errors = On
and in the script, I included the lines:
error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
The output is:
inside get data from lib.File does exist.file is readable.tgt url = content/test.txtthe end.
Warning: file_get_contents(content%2Ftest.txt): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/testApp/index.php on line 323
could not read file contents.string(33) "content/test.txt" Target url=again the end.File contents =
As you check at the beginning everything $tgt_url you shouldn't after all checks change what you checked. Now you checked if file exists etc for $tgt_url and finally you wanted to get file urlencode($tgt_url) what will be not the same.
After called urlencode(), the $tgt_url will become to "content%2Ftest.txt", not "content/test.txt" again.
You can called urlencode() at the front of the getDataFromLibrary(), it will show: File does not exist.
Don't use urlencode() inside file_get_contents() functions.

deleting image from a file in php

I am trying to delete a file from folder in php here is my model function
function deleteFiles()
{
$file = "http://localhost/copycopy/img/uploaded/long.jpeg";
if(is_file($file))
{
#unlink($file); // delete file
echo $file.'file deleted';
}
else
{
echo "no file";
}
}
but I always see "no file" and file is never deleted, file is in folder,because the url in $file actually displays the file in browser
help me
instead of using web url
$file = "http://localhost/copycopy/img/uploaded/long.jpeg";
use local path to file:
$file = $pathToYourWebSite . "/copycopy/img/uploaded/long.jpeg";
be sure to set $pathToYourWebSite to real location of your website;

php file is writable but cannot be deleted

I am using this function. is_file and is_writable return true, but when I true to unlink, it gives an error. This is on windows server.
if(is_file($fileToDelete)) {
if(is_writable($fileToDelete)) {
unlink($fileToDelete);
}
}
The file is a PDF document, which I have open. I thought is_writable would return false in this case, but it doesn't.
So how can I tell if a file can be deleted or not?
Thank you
What about doing it the other way around? Just try to delete the file and check whether it is really gone?
#unlink($fileToDelete);
if(is_file($fileToDelete)) {
// file was locked (or permissions error)
}
Not sure whether this is workable in your specific case though, but judging by the code in your question this should be what you want.
Are you using the file? I mean, did you open it by doing fopen($file)?
Do a fclose($file) before trying to delete the file.
For them who don't want to delete the file before the check, the solution is here :
$file = "test.pdf";
if (!is_file($file)) {
print "File doesn't exist.";
} else {
$fh = #fopen($file, "r+");
if ($fh) {
print "File is not opened and seems able to be deleted.";
fclose($fh);
} else {
print "File seems to be opened somewhere and can't be deleted.";
}
}
Simple, and efficient.

Categories