This is a script that Upload a file in all directory. But when i run it, its only upload One time and then fail to upload . whats wrong in this code ?
function read_directory($p_pathname)
{
$d = dir ($p_pathname);
$target = $p_pathname;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target.$_FILES['uploaded']['name']))
{
echo $target. "Done<br>";
}
else
{
echo $target."Sorry<br>";
}
while (($file = $d->read()) !== false)
{
if (($file != ".") and ($file != ".."))
{
$filetype = filetype ("{$d->path}/{$file}");
if ($filetype == "dir")
{
read_directory ("{$d->path}/{$file}");
}
else
{
// echo "\tFILE: {$d->path}/{$file}\n";
}
}
}
$d->close;
}
Use copy() instead of move_uploaded_file(). move_uploaded_file() deletes the source file when it's done, so you can't use it multiple times on the same file. copy() leaves the original file alone, so you can do it as many times as you want.
When the script exits, PHP automatically removes the temp file that was uploaded if it doesn't get moved by the script.
in the first time your moving the file... not copying ... so only next time that file not in the temp directory, so you can't move again..
Related
I am making a simple php script which just read a text file from server and delete it after showing on web.Script works well but it reads another file and delete another. It should delete the same file it reads. Any help please. Here is my code:
<?php
$mystr = '';
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$info = pathinfo($entry);
if ($info["extension"] == "txt") {
$mystr = $entry;
}
}
}
closedir($handle);
}
if (empty($mystr)) {
}else{
$contents = file_get_contents($mystr);
echo $contents;
unlink($mystr);
}
?>
Update
I dont know the file name, So in a loop I get the file name. I want to read any .txt file in the folder. This I read file one by one and at the same time delete it.
Your script is just this :
foreach(glob('/path/to/dir/*.txt') as $file)
{
readfile($file);
unlink($file);
}
See readfile() and glob() manual pages.
Have the following script.
<?php
if ($handle = opendir('files/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace("SKU#","",$fileName);
rename(fileName, $newName);
}
closedir($handle); } ?>
my script is in the root directory of iss.
inetpub/wwwroot
And I am trying to as a result access the folder files/, which is one level up to wwwroot. Where contains one image called:
"WV1716BNSKU#.zoom.1"
I am using a windows OS, any idea why this is not working, code looks file.
What error do you get? Make sure PHP is setup to display all errors.
Your script will also have to be in the same folder as your files you want to rename as all your paths are relative.
Try this:
if ($handle = opendir('./')){
while (false !== ($fileName = readdir($handle))){
$newName = str_replace("SKU#", "", $fileName);
rename($fileName, $newName);
}
closedir($handle);
}
Hey i have a system were in uploading a file. I have a script I've found online and it seems to work well.
Here is the PHP code:
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000))
{
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname))
{
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
echo "It's done! The file has been saved as: ".$newname;
}
else
{
echo "Error: A problem occurred during file upload!";
}
}
else
{
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
}
else
{
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
}
else
{
echo "Error: No file uploaded";
}
No this works fine if i want to upload a jpg file. But i want to be able to put the file into another directory. because at the moment the upload page is for admin users, they are on a subdomain called admin.mysite.com but the location i want the file to go to is in the members section which is mysite.com/members/video/
Now there are a few bits of code that im not 100% with like "dirname(FILE)" what does this do? I guessed it would get the current locations, but i've changed the whole line where so it looks like this:
$newname = '../mysite.com/members/video/'.$filename;
and
$newname = 'http://www.mysite.com/members/video/'.$filename;
But nothing. Anyone know how i can change this code so i can copy the file to a new directory?
Thanks for the help.
Change $newname to whatever location you want!
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'upload/'.$filename;
dirname(_ FILE _) returns the current directory of the file, in this case, file_upload.php
So, in this script, the $newname will save the uploaded file to /upload/name_of_new_file_uploaded.ext.
You should try to use realpath() instead dirname. Like this:
$newname = realpath("../../members/video/") . $filename;
depending on you file structure, add/remove the dots.
PS: Remember to change folder permissions, so the php can write on a folder.
For security, you should
Put the file in a location that is not accessible by the general web. /home/uploadedfiles/
Change the name of the file. Store the name of that file in a database and don't let the end users see that actual name.
I am trying to make sure that when the user uploads a profile picture, there can only be one image within the dir "profile_pic". I am openning and reading the dir with a while loop but the #unlink is not working. Below is the php code:
$directory = "uploads\\".$id."\images\profile_pic\\";
if (glob($directory . "*.jpg") != false) {
$filecount = count(glob($directory . "*.jpg"));
if ($filecount > 0) {
//delete exiting pics in folder profile_pic
$handle = opendir($directory);
while ($handle && ($file = readdir($handle)) !== false) {
if ( unlink($entry)) {
$msg .= "File Deleted";
}
}
closedir($directory);
}
}
Sorry, where did you define $entry - did you ever assign a value to it? And why do you make exactly the same call to glob() twice instead of catching the result of the first call in a variable? And why bother to opendir() to list files when you have already glob()ed and obtained that list of files? Especially when you don't apply the same *.jpg filter to the files you are deleting...
Just do this:
// Forward slashes work on Windows too (in PHP, at least)
$directory = "uploads/".$id."/images/profile_pic";
if (($existing = glob($directory . "/*.jpg")) !== false) { // Get a list of files...
foreach ($existing as $file) { // ...loop them...
$msg .= (unlink($directory."/".$file)) ? "File $file deleted\n" : "Could not delete $file\n"; // ...and delete them
}
} else $msg .= "Listing directory failed\n";
I am trying to read a file name current.conf and then use the name of a folder saved in it to opendir(); when I open:
$file = fopen("current.conf","r");
$lines = fread($file,"10");
fclose($file);
$lines = "/".$lines."/";
echo $lines;
$dir=opendir($lines);
$files=array();
while (($file=readdir($dir)) !== false)
{
if ($file != "." and $file != ".." and $file != "index.php")
{
array_push($files, $file);
}
}
closedir($dir);
The current.conf has only one line in it:
2.1-2328
I am not able to open the folder that is named in the conf files. I have a feeling it has to do with the formatting of the conf file but not sure.
I suspect the directory doesn't exist (or you don't have the rights to read it), but without a specific error (opendir is most likely throwing an E_WARNING - check your logs, etc.)
Incidentally, you could re-write your code to reduce its complexity as follows:
<?php
// Grab the contents of the "current.conf" file, removing any linebreaks.
$dirPath = '/'.trim(file_get_contents('current.conf')).'/';
$fileList = scandir($dirPath);
if(is_array($fileList)) {
foreach($fileList as $file) {
// Skip the '.' and '..' in here as required.
echo $file."\n";
}
}
else echo $dirPath.' cound not be scanned.';
?>
In this instance the call to scandir will throw an E_WARNING.