How to Copy a file to another directory after submit - php

I am trying to create a directory after a form submit, then after the form is submitted I want that directory to have a file stuffed inside of it. I have tried the php copy function and used an if statement to see if it was copying successfully but it is not. Please take a look at my code and see what is going on. And when it was working, it would just give a "1" output once submitted. No actual file was moved inside of the folder.
if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$root = "/serves/registered.php";
$err = array();
$folder = mkdir($_POST['username']);
$reg = "registered.php";
mkdir($_POST['username']);
copy($root,$folder);
if (!copy($root, $folder)) {
echo "failed to copy $root...\n";
} else {
echo "Account was successfuly created.";
}
Thank you

This can do it:
$root = "serves/registered.php";
$folder = mkdir($_POST['username']);
if($folder) {
$reg = "registered.php";
if (!copy($root, $_POST['username']."/".$reg)) {
echo "failed to copy $root...\n";
} else {
echo "Account was successfuly created.";
}
}
else {
echo "Could not create folder";
}

if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$root = "contact.php";
$folder = $_POST['username'] . '/' . $root;
mkdir($_POST['username']);
if (!copy($root, $folder)) {
echo "failed to copy $root...\n";
} else {
echo "Account was successfuly created.";
}
}

Related

How to copy a file inside a newly created folder and rename the file?

Good day experts!
I want to copy a file inside a newly created folder and rename the file but it seems there's something wrong with codes and I cant figure it out. Here's my code:
<?php
$name = $_POST["newFileName"];
$folder = mkdir($name);
session_start();
$name = $_POST["newFileName2"];
$file = 'data.php';
$newfile = $_POST["newFileName"].'/'$_POST["newFileName2"].'.php';
file_exists($newfile) && die(" <center><br><br><br><br>The Exam name already exists.! Change it! <br><br> <a href='quiz.php'><button>GO BACK</button></a>");
if (!copy($file, $newfile)) {
echo "Failed to create Quiz";
}else {
echo "Created Successfully";
}
?>
session_start();
if ( !isset($_POST["newFileName"], $_POST["newFileName2"]) ) {
echo "An meaningful error message";
exit;
}
$existingFile = 'data.php';
// $_POST["newFileName"] is the new folder name
// may have been better named $_POST["newFolder"] :)
$folder = '';
$folder = $_POST["newFileName"];
if ( ! mkdir($folder) ) {
echo 'Cannot create a folder with that name';
exit;
}
$newFilename = $_POST["newFileName2"];
$newfile = "$folder/$_POST[newFileName2].php";
if ( file_exists($newfile) ) {
echo " <center><br><br><br><br>The Exam name already exists.! Change it! <br><br> <a href='quiz.php'><button>GO BACK</button></a>";
exit;
}
if (!copy($existingFile, $newfile)) {
echo "Failed to create Quiz";
}else {
echo "Created Successfully";
}

Move a file from directory to another using PHP

I have a file on one application folder of codiginitor and I want to copy that file to another application folder of codignitor in another directory.
I have tried below code but it doesn't seem to be working:
$file = 'http://xxxxxx/jakson_solar/ftp.php';
$newfile = './mobile_image/transfer/';
if ( copy($file, $newfile) ) {
echo "Copy success!"; die;
}else{
echo "Copy failed."; die;
}
is there another way to copy file from one directory to another directory?
copy requires as first parameter an input file and as second parameter an output file
So do it this way
$file = 'path_to/ftp.php';
$newfile = './mobile_image/transfer/ftp.php';
if ( copy($file, $newfile) ) {
echo "Copy success!"; die;
} else {
echo "Copy failed."; die;
}
#dev please find the code below for your needs
// 1 check if your input from the form is not empty
if ((isset($_FILES['file']))){
// 2. files inside the session
$_SESSION['FILES'] = $_FILES;
// 3. your path
$PATH = $_SERVER["DOCUMENT_ROOT"]."/mobile_image/transfer/";
// 4. temporary name -> optional step but recommended
$TEMP_NAME = explode(".",$_FILES["file"]);
// 5. new name of the file
$NAME_NEW = substr(number_format(time() * rand(),0,'',''),0,20) . '.' .end($TEMP_NAME);
$UPLOAD_FILE = $PATH . basename($NAME_NEW);
// 6. check before moving the file that is not empty
if (isset($UPLOAD_FILE)) {
move_uploaded_file($_FILES['file'], $PATH); }
// 7. custom errors
$json = array();
$json['status'] = "OK";
$json['message'] = 'File moved successfully';
echo json_encode($json);
}else{
// 7. custom errors
$json = array();
$json['status'] = "NO FILE";
$json['message'] = 'No files found';
echo json_encode($json);
}

How to copy the set of files from one folder to another folder using php

I want to copy set of uploaded files from one folder to another folder.From the below code, all the files in one folder is copied.It takes much time. I want to copy only the currently uploaded file to another folder.I have some idea to specify the uploaded files and copy using for loop.But I don't know to implement.I am very new to developing.Please help me.Below is the code.
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
To copy only the uploaded files, there is only a slight change in the coding which I have made. That is instead of using "." from one folder, I passed the array value. So that only the files which are uploaded will be copied to the new folder instead of copying everything which takes long time.Below is the only change made to do:
$files = glob("test_uploads/$name_arrray[$i]");

making a new folder using php code

I just wanna ask, what is the code needed in my code in order this warning will not show
Warning: mkdir() [function.mkdir]: File exists in
C:\xampp\htdocs\php-robert\dir\dir.php
also did my program is correct? what i want in my program is, if the folder is not exist, make a folder, if its existing just do nothing.. nothing to show, just nothing
dir.php
<?php
$var = "MyFolder";
$structure = "../../file/rep/$var";
if (!mkdir($structure, 0700)) {
}
else
{
echo"folder created";
}
?>
Try the following:
$folder = "folder_name";
// if folder does not exist or the name is used, just not for a folder
if (!file_exists($folder) || !is_dir($folder)) {
if (mkdir($folder, 0755)) {
echo 'Folder created';
} else {
echo 'Unable to create folder';
}
}
if (!is_dir($structure)) {
mkdir($structure);
}
else
{
echo "folder already exists";
}
if (is_dir($structure) == false and mkdir($structure, 0700) == false)
{
echo "error creating folder";
}
else
{
echo "folder exists or was created";
}
You could also test if a file exists, but it isn't a folder

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories