php copy function from one folder to another - php

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";
}

Related

How do i set up path and folder pattern in PHP?

So I am trying to set up path for my pdf files that are stored in a folder structure. The file that has to be selected depends on the user input.
I want to set up first the absolute path and then a folder pattern.
The folder where I have stored my files is:
C:\Apache24\htdocs\archivedb\Tourenfahrer\2017\5
The last three folders changes as per user input.
I have setup my root directory in my config.php like this:
define( 'ROOT_DIR', dirname(__FILE__) );
Now in my php file I am recieving my variables, which will be my folder names to search for the files.
<?php
require_once 'conf/config.php';
if (!empty($_REQUEST['magName'] && $_REQUEST['year'] && $_REQUEST['issue']
)) {
$magazineName = $_REQUEST['magName'];
$year = $_REQUEST['year'] ;
$issue = $_REQUEST['issue'] ;
}
Now Please tell how to access the respective folder using these variables?
and how can i set up a pattern with this using glob(); ?
Please try this
define('ROOT_DIR', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
if (!empty($_REQUEST['magName'] && $_REQUEST['year'] && $_REQUEST['issue'])) {
$magazineName = $_REQUEST['magName'];
$year = $_REQUEST['year'];
$issue = $_REQUEST['issue'];
$dir = $magazineName . DS . $year . DS . $issue;
echo "<h3>Use scandir:</h3>";
$files = scandir(ROOT_DIR . DS . $dir);
foreach ($files as $file) {
echo basename($file) . "<br>";
}
echo "<h3>Use glob:</h3>";
foreach (glob($dir . DS . '*') as $filename) {
echo basename($filename) . "<br>";
}
}

Losing variable value when trying to copy file using mailReader.php

I'm using the mailReader script found here: https://github.com/stuporglue/mailreader
I am trying to copy the file(s) after upload to another folder.
The file(s) upload correctly to the folder where the script resides.
When I try to run a copy command, the filename variable is empty.
Here is the portion of the code I am working with: The last three lines are what I added.
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I receive confirmation by email that the file(s) are uploaded, then another email with the error message.
Warning: copy(/attachments/W7652222-546/1453406138_residential-print_from_td.pdf): failed to open stream: No such file or directory in /home/myhost/public_html/mailreader/mailReader.php on line 224
224 being the line number of my added code.
The source filename is missing from in front of /attachments...
Anyone have any thoughts?
$name is defined in the while loop and may not be accessible on the upper scopes my suggestion is to change your code to this:
private function saveFile($filename,$contents,$mimeType = 'unknown'){
$filename = preg_replace('/[^a-zA-Z0-9_-]/','_',$filename);
$unlocked_and_unique = FALSE;
$name = '';
while(!$unlocked_and_unique){
// Find unique
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4); // added 1-19-2016
while(file_exists($this->save_directory . $name)) {
$name = time() . "_" . $filename;
$name = substr_replace($name,".pdf",-4);
}
// Attempt to lock
$outfile = fopen($this->save_directory.$name,'w');
if(flock($outfile,LOCK_EX)){
$unlocked_and_unique = TRUE;
}else{
flock($outfile,LOCK_UN);
fclose($outfile);
}
}
fwrite($outfile,$contents);
fclose($outfile);
if (copy($this->save_directory.$name, "/attachments/" . TRANS_ID . "/". $name)) {
unlink( $this->save_directory.$name );
}
I hope this solves your problem
I ended up defining a constant of email_id in the private function saveToDb, then running a script after everything else is finished to query the table using the email_id and looping through the records moving the files.

How to use Unlink() function

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.

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