File Directory and delete file php? - php

I'm trying to create php script to scan directory and delete file in this directory. I have problem with my scanning file extension is not working right
<?php
if ($handle = opendir(''))
{
echo " Directory handle: $handle \n";
echo "Entries: \n";
while (false !== ($entry = readdir($handle)))
{
echo" $entry :\n";
$file_parts = pathinfo($entry);
switch ($file_parts['extension'])
{
case 'dmg':
echo "dmg";
break;
default:
echo "no file";
break;
}
}
closedir($handle);
}
?>
Notice: Undefined index: extension in /Applications/MAMP/htdocs/dir.php on line 13

This error would be caused if for example the path doesn't have an extension or some error occured.
If you want to retreive the filetype of the files it seems like a roundabout way of doing so when you can just do
switch(filetype($dir.$file)){
case 'dmg' ://And so on
}
Here $dir would be /Users/username/Downloads

Undefined Index means it doesn't exists in the array.
From docs:
If the options parameter is not passed, an associative array containing the
following elements is returned: dirname, basename, extension (if any), and filename.
Your files do have extension?
Also, put '.' (dot) in your dir instead of blank space.
You can use var_dump( $file_parts ); to see what it is.

Related

Copy() function can't detect destination path php [duplicate]

Anyone know why this:
<?PHP
$title = trim($_POST['title']);
$description = trim($_POST['description']);
// Array of allowed image file formats
$allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp');
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
echo '<div class="error">Invalid file type.</div>';
}
}
}
if (strlen($title) < 3)
echo '<div class="error">Too short title</div>';
else if (strlen($description) > 70)
echo '<div class="error">Too long desccription.</div>';
else {
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
}
Gives:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41
It's because you're moving a file and it thinks you're trying to rename that file to the second parameter (in this case a directory).
it should be:
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:/wamp/www/uploads/images/'.$file['name']);
You are specifying to move a file to a directory; neither PHP's move_uploaded_file nor its copy is as smart as a shell's copy -- you have to specify a filename, not a directory, for the destination.
So, one simple solution would be to take the basename of the source file and append that to the destination directory.
It sounds like the second argument to move_uploaded_file should be a full file name instead of just the directory name. Also, probably only a style issue, but you should use consistent slashes in 'c:\wamp\www\uploads\images/'
Because PHP is not a shell. You're trying to copy the file into the c:\wamp\www\uploads\images directory, but PHP doesn't know you mean that when you execute (within the move_uploaded_file function):
copy($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
This command tells it to rename the file to c:\wamp\www\uploads\images/, which it can't do because that's the name of an existing directory.
Instead, do this:
move_uploaded_file($_FILES['userfile']['tmp_name'],
'c:\wamp\www\uploads\images/' . basename($_FILES['userfile']['tmp_name']));
if you want just copy the file in two Dir different, try this :
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target.$pic1))
{
copy("C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/".$pic1, "C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/thumbs/".$pic1)
}
You should write the complete path "C:/..."
Try adding the extension to the name file.
$filename = $_FILES['userfile']['tmp_name'].".jpg";
It will be like below in phalcon 3.42
if ($this->request->hasFiles() == true) {
// Print the real file names and sizes
foreach ($this->request->getUploadedFiles() as $file) {
//Print file details
echo $file->getName(), " ", $file->getSize(), "\n";
//Move the file into the application
$file->moveTo($this->config->application->uploadsDir.$file->getName());
}
}
FIRSTLY FIND YOUR CURRENT DIRECTORY echo getcwd(); IF YOU FIND THE CURRENT DIRECTORY SO MOVE THEM ANOTHER DIRECTORY
FOR EXAMPLE = echo getcwd(); these output is "your live directory name" like that -> /opt/lampp/htdocs/product and create new directory anywhere but your current directory help to go another directory ***
plz read carefully very thinking answer

PHP readdir to find xml

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.

files not copying to a different folder

I am trying to move all the .vtk files and .raw files to a different folder. But it is not being copied. How do I fix this?
<?php
define ('DOC_ROOT', $_SERVER['DOCUMENT_ROOT'].'/');
$src = '/var/www/html/php/';
$dest ='/var/www/html/php/emd/';
$dh = opendir ($src); //Get a directory handle
$validExt = array('vtk','raw'); //Define a list of allowed file types
$filesMoved = 0;
// Loop through all the files in the directory checking them and moving them
while (($file = readdir ($dh)) !== false) {
// Get the file type and convert to lower case so the array search always matches
$fileType = strtolower(pathinfo ($file, PATHINFO_EXTENSION));
if(in_array ($fileType, $validExt)) {
// Move the file - if this is for the web really you should create a web safe file name
if (!$rename($src.$file, $dest.) {
echo "Failed to move {$file} to {$newPath}";
} else {
echo "Moved {$file} to {$newPath}";
$filesMoved++;
}
}
}
echo "{$filesMoved} files were moved";
closedir($dh);
?>
You forgot to add the filename for the destination, change this line:
if (!$rename($src.$file, $dest.) {
into:
if (!$rename($src.$file, $dest.$file) {
If this is not working make sure that the destination directory really exists and that you have write permission to it. If you had enabled error reporting you would have seen an error message like this:
Parse error: parse error in
/path/to/script/rename.php on
line 18

php code to grab set of characters from .php file giving error message

Thanks in advance.
Getting this warning when using below code:
Warning: file_get_contents(test.php) [function.file-get-contents]: failed to open stream: No such file or directory in /path/index.php on line so-n-so.
Here's the code I am using,
<?php
// Scan directory for files
$dir = "path/";
$files = scandir($dir);
// Iterate through the list of files
foreach($files as $file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] === "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrence of opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrence of ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}
?>
The error message says that the file isn't found.
This is because scandir() returns only the basename of the files from your directory. It doesn't include the directory name. You could use glob() instead:
$files = glob("$dir/*.php");
This returns the path in the result list, and would also make your extension check redundant.
I would suggest that you need to exclude . and .. from the list of files picked up by scandir() DOCs.
// Iterate through the list of files
foreach($files as $file) {
if('.' == $file or '..' == $file) {
continue;
}
...
Also you need to put the path before your file name:
$contents = file_get_contents($path . $file);

The second argument to copy() function cannot be a directory

Anyone know why this:
<?PHP
$title = trim($_POST['title']);
$description = trim($_POST['description']);
// Array of allowed image file formats
$allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp');
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
echo '<div class="error">Invalid file type.</div>';
}
}
}
if (strlen($title) < 3)
echo '<div class="error">Too short title</div>';
else if (strlen($description) > 70)
echo '<div class="error">Too long desccription.</div>';
else {
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
}
Gives:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41
It's because you're moving a file and it thinks you're trying to rename that file to the second parameter (in this case a directory).
it should be:
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:/wamp/www/uploads/images/'.$file['name']);
You are specifying to move a file to a directory; neither PHP's move_uploaded_file nor its copy is as smart as a shell's copy -- you have to specify a filename, not a directory, for the destination.
So, one simple solution would be to take the basename of the source file and append that to the destination directory.
It sounds like the second argument to move_uploaded_file should be a full file name instead of just the directory name. Also, probably only a style issue, but you should use consistent slashes in 'c:\wamp\www\uploads\images/'
Because PHP is not a shell. You're trying to copy the file into the c:\wamp\www\uploads\images directory, but PHP doesn't know you mean that when you execute (within the move_uploaded_file function):
copy($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
This command tells it to rename the file to c:\wamp\www\uploads\images/, which it can't do because that's the name of an existing directory.
Instead, do this:
move_uploaded_file($_FILES['userfile']['tmp_name'],
'c:\wamp\www\uploads\images/' . basename($_FILES['userfile']['tmp_name']));
if you want just copy the file in two Dir different, try this :
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target.$pic1))
{
copy("C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/".$pic1, "C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/thumbs/".$pic1)
}
You should write the complete path "C:/..."
Try adding the extension to the name file.
$filename = $_FILES['userfile']['tmp_name'].".jpg";
It will be like below in phalcon 3.42
if ($this->request->hasFiles() == true) {
// Print the real file names and sizes
foreach ($this->request->getUploadedFiles() as $file) {
//Print file details
echo $file->getName(), " ", $file->getSize(), "\n";
//Move the file into the application
$file->moveTo($this->config->application->uploadsDir.$file->getName());
}
}
FIRSTLY FIND YOUR CURRENT DIRECTORY echo getcwd(); IF YOU FIND THE CURRENT DIRECTORY SO MOVE THEM ANOTHER DIRECTORY
FOR EXAMPLE = echo getcwd(); these output is "your live directory name" like that -> /opt/lampp/htdocs/product and create new directory anywhere but your current directory help to go another directory ***
plz read carefully very thinking answer

Categories