I'm trying to create a script that will send across files from one server to another. My script successfully does that as well as checks if the file has something in it or not. My next step is to check whether the file already exists on the server; if the file already exists it does not send and if it does not exist, it does send.
I've tried a few different things and can't seem to get my head around it. How can I get it to check whether the file already exists or not? Any help would be appreciated!
(I had a look at some similar questions but couldn't find anything specific to my issue.)
require('constants.php');
$files = $sftp->nlist('out/');
foreach($files as $file) {
if(basename((string) $file)) {
if(strpos($file,".") > 1) { //Checks if file
$filesize = $sftp->size('out/'.$file); //gets filesize
if($filesize > 1){
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
else {
$sftp->get('out/'.$file, 'import/'.$file); //Sends file over
//$sftp->delete('out/'.$file); //Deletes file from out folder
}
else {
echo $file. ' is empty.</br>';
}
}
}
}
}
EDIT: To try and get this to work, I wrote the following if statement to see if it was finding the file test.php;
if (file_exists('test.txt')){
echo 'True';
} else {
echo 'False';
}
This returned true (a good start) but as soon as I put this into my code, I just get a 500 Internal Server Error (extremely unhelpful). I cannot turn on errors as it is on a server that multiple people use.
I also tried changing the file_exists line to;
if (file_exists('test.txt'))
in the hopes that would work but still didn't work.
Just to clarify, I'm sending the files from the remote server to my local server.
There is a closing curly brace missing right before the second else keyword.
Please try to use a code editor with proper syntax highlighting and code formatting to spot such mistakes on the fly while you are still editing the PHP file.
The corrected and formatted code:
require('constants.php');
$files = $sftp->nlist('out/');
foreach ($files as $file) {
if (basename((string)$file)) {
if (strpos($file, ".") > 1) { //Checks if file
$filesize = $sftp->size('out/' . $file); //gets filesize
if ($filesize > 1) {
if (file_exists('import/' . $file)) {
echo $file . ' already exists';
} else {
$sftp->get('out/' . $file, 'import/' . $file); //Sends file over
}
} else {
echo $file . ' is empty.</br>';
}
}
}
}
Your code checks the file exist in your local server not in remote server.
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
You need to check in remote server using sftp object like
if($sftp->file_exists('import/'.$file)){
echo $file.' already exists';
}
Edit:
Add clearstatcache() before checking file_exists() function as the results of the function get cached.
Refer: file_exists
Related
I inherited a piece of code that has suddenly stopped working. I've isolated the code down to it appears this function is no longer reading the directory and locating the xml file found in it for later processing. I've uploaded versions of the xml file with uppercase and lowercase .xml/.XML extension with the same result: NO XML FILE FOUND
I've verified that the print_r is in fact reading the correct directory where the xml file resides. There are other files in the directory but that has been the case for years. Did something change recently in PHP to stop this code from working?
function GetXMLFile($path) {
$path .= "/";
print_r($path);
$filename = "";
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (GetFileExtention($path . strtolower($file)) =="XML") {
$filename = $file;
}
}
}
closedir($handle);
}
return $filename;
}
Later in the code the function is called that is producing the NO XML error. I've confirmed the $config['xml_dir'] variable below matches the print_r directory location above as well.
$cur_xml_file = GetXMLFile($config['xml_dir']);
if ($cur_xml_file == "") {
echo "NO XML FILE FOUND";
exit(0);
}
No, nothing has changed in PHP recently that would cause the code you show to stop functioning. If it doesn't work anymore, the error is somewhere else.
Then again, that's a lot of code to find a file. Why don't you just do change it to
function GetXMLFile($path) {
$all_xml_files = glob("$path/*.{xml,XML}", GLOB_BRACE);
return !empty($all_xml_files) ? realpath($all_xml_files[0]) : "";
}
That will return the absolute path of the first file with an .XML or .xml extension in the given $path or an empty string if no files are found or an error occured.
See if the error goes away when you change it to that.
UPDATE: The embarrassing reason why it "didn't work" just was based on the fact that i was looking at the wrong directory.
I need to unlink/delete all files inside a folder. To achieve this, I have modified a method I've found here on SO:
public function deleteDirContent($dirPath)
{
if (!is_dir($dirPath))
{
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/')
{
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file)
{
if (is_dir($file))
{
$this->deleteDirContent($file);
}
else
{
print_r($file);
if(unlink($file))
{
echo " - SUCCESS";
}
else
{
echo " - ERROR !";
}
echo PHP_EOL;
}
}
}
The method works fine for all files, except for *.zip files, as it seems. And what's even more strange about it: unlink() still returns true without deleting the file.
Maybe the problem is related to my PHP version and/or the fact that it's running on a Windows Server.
Relevant specs:
PHP Version: 5.3.1
XAMPP Version: xampp-win32-1.7.3
OS: Windows 2008 Server
Any help would be appreciated.
Try changing the permissions with chmod:
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);
The embarrassing reason why it "didn't work" just was based on the fact that i was looking at the wrong directory.
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.
I have a .bat file that encodes an mp3 file on the server side, and I also have a php function that checks if the file exists, and then adds it as an HTML list item. The problem I'm running into - sometimes the mp3 file isn't done encoding on the server side. If somebody were to try downloading the file while it's in the process of encoding it will crash the browser.
Can I check to make sure the filesize is finished increasing before listing the item?
Here's the function that checks if the file exists:
function ListDir($dir_handle,$path) {
global $listing;
echo "<ul>";
while (false !== ($file = readdir($dir_handle))) {
$dir =$path . $file;
if(is_dir($dir) && $file != '.' && $file !='..' && filesize($file) {
$handle = #opendir($dir) or die("Unable to open file $file");
echo "<li>".$dir;
ListDir($handle, $dir);
echo "</li>";
} elseif($file != '.' && $file !='..' && $file !='.htaccess') {
$new_string = ereg_replace("[^A-Za-z.]", "", $file);
echo '<li>'.str_replace('wav', 'mp3', $new_string).'</li>';
}
}
echo "</ul>";
closedir($dir_handle);
}
Have the bat encode, then move to a final location for a "finished" state, if it doesn't exist there - it's not done. This is similar to drew010's answer except it utilizes the same file, from a working directory to a production directory.
This also prevents it being accessible by any resources until it's ready which could potentially cause problems.
You can't really know the final filesize, so have your bat file create a file like mp3filename.work or something and then have the bat file delete it when the encoding finishes, so if the .work file doesn't exist, then the encoding is done.
I wrote this code to create a ZIP file and to save it. But somehow it just doesn't show any error, but it doesn't create a ZIP file either. Here's the code:
$zip = new ZipArchive;
$time = microtime(true);
$res = $zip->open("maps/zips/test_" . $time . ".zip", ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
What am I doing wrong, and how can I fix it?
Probably apache or php has not got permissions to create zip archives in that directory. From one of the comments on ZipArchice::open:
If the directory you are writing or
saving into does not have the correct
permissions set, you won't get any
error messages and it will look like
everything worked fine... except it
won't have changed!
Instead make sure you collect the
return value of ZipArchive::close().
If it is false... it didn't work.
Add an else clause to your if statement and dump $res to see the results:
if($res === TRUE) {
...
} else {
var_dump($res);
}
There are 2 cases when zip doesn't generate the error.
Make sure every file you are adding to the zip is valid. Even if
one file is not available when zip->close is called then the archive
will fail and your zip file won't be created.
If your folder doesn't
have write permissions zip will not report the error. It will finish
but nothing will be created.
I had an exactly same issue, even when with full writing/reading permissions.
Solved by creating the ".zip" file manually before passing it to ZipArchive:
$zip = new ZipArchive;
$time = microtime(true);
$path = "maps/zips/test_" . $time . ".zip"
touch($path); //<--- this line creates the file
$res = $zip->open($path, ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
Check out that each of your file exists before calling $zip->addFile otherwise the zip won't be generated and no error message will be displayed.
if(file_exists($fichier->url))
{
if($zip->addFile($fichier->url,$fichier->nom))
{
$erreur_ouverture = false;
}
else
{
$erreur_ouverture = true;
echo 'Open error : '.$fichier->url;
}
}
else
{
echo 'File '.$fichier->url.' not found';
}
break it into steps.
if ($res === TRUE) {
check if file_exist
check if addFile give any error
}
if($zip->close())
{
$zip_created = true;
echo "FILE ADDED!"
}
Check the phpinfo for zip is enabled or not :)
One of the reasons for zip file is not created is due to missing check if you are adding file and not a directory.
if (!$file->isDir())
I found the solution here.