Hướng dẫn copy php not working

Trying to copy files from one directory to another in PHP, but it is not copying.

My Code:

Go Back";
?>

Hướng dẫn copy php not working

asked Nov 21, 2017 at 11:27

13

Error should be here :

1: Try to check FOLDER PERMISSION (How to play with Permission ? see http://php.net/manual/en/function.chmod.php )

2: Parent folder does not exist (you are using ../).

How Copy() works :

 bool copy ( string $source , string $dest [, resource $context ] )

Makes a copy of the file source to dest.

If the destination file already exists, it will be overwritten.

How to set Permission (Linux) ? :

Go to your Linux Terminal and use command sudo chmod 755 -R folder_name, if you are using VPS/Dedicated. if you are using Shared Hosting simply go to www folder and set permission by following given steps using UI

answered Nov 21, 2017 at 11:34

helpdochelpdoc

1,82013 silver badges35 bronze badges

8

1. Folder permission - so try to give that folder recursive permission.
2. Use 
bool copy ( string $source , string $dest [, resource $context ]) function
eg: $file = '/test1/example.txt'; 
$newfile = '/test2/example.txt';
if(!copy($file,$newfile)){
  echo "failed to copy $file";
}else{
  echo "copied $file into $newfile\n";
}

Refer this link as well - 
http://www.phpkida.com/php-tutorial/copy-multiple-files-from-one-folder-to-another-php/

answered Nov 21, 2017 at 11:58

SurabhiSurabhi

1691 silver badge6 bronze badges

1

There are still 2 possible ways which can used to copy your files from another server.

Nội dung chính

  • 1. Using PHP Copy to move files from server to server.
  • 2. Using PHP FTP to move files from server to server
  • ZIP and UNZIP Files using PHP
  • ZIP Files using PHP
  • UNZIP Files using PHP
  • Other Alternative to ZIP / UNZIP File
  • How can I transfer files from one server to another in PHP?
  • How do I copy a server from one server to another?
  • How do I copy a folder from one directory to another in PHP?
  • How do you copy a file from one folder to another?

-One is to remove your .htaccess file from example.com or allow access to all files(by modifying your .htaccess file). -Access/Read those files via their respective URLs, and save those files using 'file_get_contents()' and 'file_put_contents()' methods. But this approach will made all files accessible to other people too.

            $fileName       = 'filename.extension';
            $sourceFile     = 'http://example.com/path-to-source-folder/' . $fileName;
            $targetLocation = dirname( __FILE__ ) . 'relative-path-destination-folder/' + $fileName;

            saveFileByUrl($sourceFile, $targetLocation);

            function saveFileByUrl ( $source, $destination ) {
                if (function_exists('curl_version')) {
                    $curl   = curl_init($fileName);
                    $fp     = fopen($destination, 'wb');
                    curl_setopt($ch, CURLOPT_FILE, $fp);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_exec($ch);
                    curl_close($ch);
                    fclose($fp);
                } else {
                    file_put_contents($destination, file_get_contents($source));
                }
            }

Or you can create a proxy/service on example.com to read a specific file after validating a pass key or username/password combination(whatever as per your requirement).

            //In myproxy.php
            extract($_REQUEST);
            if (!empty($passkey) && paskey == 'my-secret-key') {
                if (!empty($file) && file_exists($file)) {
                    if (ob_get_length()) {
                        ob_end_clean();
                    }
                    header("Pragma: public");
                    header( "Expires: 0");
                    header( "Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    header( 'Content-Type: ' . mime_content_type($file) );
                    header( "Content-Description: File Transfer");
                    header( 'Content-Disposition: attachment; filename="' . basename( $file ) . '"' );
                    header( "Content-Transfer-Encoding: binary" );
                    header( 'Accept-Ranges: bytes' );
                    header( "Content-Length: " . filesize( $file ) );
                    readfile( $file );
                    exit;
                } else {
                    // File not found 
                }
            } else {
                //  You are not authorised to access this file.
            }

you can access that proxy/service by url 'http://example.com/myproxy.php?file=filename.extension&passkey=my-secret-key'.

Sometimes you need to move/migrate files to another server/hosting, and you/your client only have FTP access to the server. And to download these files and re-upload to another server can take a lot of time using FTP client such as Filezilla. FTP do not have zip – unzip functionality, so you need to upload it one by one. And server to server transfer is a lot faster than downloading and uploading the files.

You can use this simple PHP script to move files from one server to another server.

Note: It’s just a simple examples. you need to build your own auth/security method if needed.

1. Using PHP Copy to move files from server to server.

You can just create a php file in the destination server and load the file once in your browser. For example you add this code in http://destination-url/copy-files.php and in copy-files.php you add this php code:

/**
 * Transfer Files Server to Server using PHP Copy
 * @link https://shellcreeper.com/?p=1249
 */

/* Source File URL */
$remote_file_url = 'http://origin-server-url/files.zip';

/* New file name and path for this file */
$local_file = 'files.zip';

/* Copy the file from source url to server */
$copy = copy( $remote_file_url, $local_file );

/* Add notice for success/failure */
if( !$copy ) {
    echo "Doh! failed to copy $file...\n";
}
else{
    echo "WOOT! success to copy $file...\n";
}

2. Using PHP FTP to move files from server to server

Sometimes using PHP Copy didn’t work if the files is somehow protected by this method (hotlink protection maybe?). I did experience that if the source is from Hostgator it didn’t work.

But we can use another method. Using FTP (in PHP) to do the transfer using the code:

/**
 * Transfer (Import) Files Server to Server using PHP FTP
 * @link https://shellcreeper.com/?p=1249
 */

/* Source File Name and Path */
$remote_file = 'files.zip';

/* FTP Account */
$ftp_host = 'your-ftp-host.com'; /* host */
$ftp_user_name = ''; /* username */
$ftp_user_pass = 'ftppassword'; /* password */


/* New file name and path for this file */
$local_file = 'files.zip';

/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host );

/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

/* Download $remote_file and save to $local_file */
if ( ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY ) ) {
    echo "WOOT! Successfully written to $local_file\n";
}
else {
    echo "Doh! There was a problem\n";
}

/* Close the connection */
ftp_close( $connect_it );

using FTP you have more flexibility, the code above is using ftp_get to import the files from source server to destination server. But we can also use ftp_put to export the files (send the files) from source server to destination, using this code:

/**
 * Transfer (Export) Files Server to Server using PHP FTP
 * @link https://shellcreeper.com/?p=1249
 */

/* Remote File Name and Path */
$remote_file = 'files.zip';

/* FTP Account (Remote Server) */
$ftp_host = 'your-ftp-host.com'; /* host */
$ftp_user_name = ''; /* username */
$ftp_user_pass = 'ftppassword'; /* password */


/* File and path to send to remote FTP server */
$local_file = 'files.zip';

/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host );

/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

/* Send $local_file to FTP */
if ( ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
    echo "WOOT! Successfully transfer $local_file\n";
}
else {
    echo "Doh! There was a problem\n";
}

/* Close the connection */
ftp_close( $connect_it );

To make it easier to understand:

  • ftp_connect is to connect via FTP.
  • ftp_login is to login to FTP account after connection established.
  • ftp_close is to close the connection after transfer done (log out).
  • ftp_get is to import/download/pull file via FTP.
  • ftp_put is to export/send/push file via FTP.

After you import/export the file, always delete the PHP file you use to do this task to prevent other people using it.

ZIP and UNZIP Files using PHP

Of course to make the transfer easier we need to zip the files before moving, and unzip it after we move to destination.

ZIP Files using PHP

You can zip all files in the folder using this code:

/**
 * ZIP All content of current folder
 * @link https://shellcreeper.com/?p=1249
 */

/* ZIP File name and path */
$zip_file = 'files.zip';

/* Exclude Files */
$exclude_files = array();
$exclude_files[] = realpath( $zip_file );
$exclude_files[] = realpath( 'zip.php' );

/* Path of current folder, need empty or null param for current folder */
$root_path = realpath( '' );

/* Initialize archive object */
$zip = new ZipArchive;
$zip_open = $zip->open( $zip_file, ZipArchive::CREATE );

/* Create recursive files list */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator( $root_path ),
    RecursiveIteratorIterator::LEAVES_ONLY
);

/* For each files, get each path and add it in zip */
if( !empty( $files ) ){

    foreach( $files as $name => $file ) {

        /* get path of the file */
        $file_path = $file->getRealPath();

        /* only if it's a file and not directory, and not excluded. */
        if( !is_dir( $file_path ) && !in_array( $file_path, $exclude_files ) ){

            /* get relative path */
            $file_relative_path = str_replace( $root_path, '', $file_path );

            /* Add file to zip archive */
            $zip_addfile = $zip->addFile( $file_path, $file_relative_path );
        }
    }
}

/* Create ZIP after closing the object. */
$zip_close = $zip->close();

UNZIP Files using PHP

You can unzip file to the same folder using this code:

/**
 * Unzip File in the same directory.
 * @link http://stackoverflow.com/questions/8889025/unzip-a-file-with-php
 */
$file = 'file.zip';

$path = pathinfo( realpath( $file ), PATHINFO_DIRNAME );

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
    $zip->extractTo( $path );
    $zip->close();
    echo "WOOT! $file extracted to $path";
}
else {
    echo "Doh! I couldn't open $file";
}

Other Alternative to ZIP / UNZIP File

Actually, if using cPanel you can easily create zip and unzip files using cPanel File Manager.

I hope this tutorial is useful for you who need a simple way to move files from server to server.

How can I transfer files from one server to another in PHP?

$file, "wb"); $source = file_get_contents($file); fwrite($destination, $source, strlen($source)); fclose($destination); The image needs to be transferred to an FTP server..

Initialize a session first..

The desired transfer options can be set..

The transfer can be performed..

The session can be closed..

How do I copy a server from one server to another?

The approach is as follows:.

Step 1: Login to server A using WinSCP..

Step 2: Download the files from server A to your local system (Windows).

Step 3: Login to server B using WinSCP..

Step 4: Upload the local files to server B..

How do I copy a folder from one directory to another in PHP?

Used Functions:.

copy() Function: The copy() function is used to make a copy of a specified file. ... .

opendir() Function: The opendir() function is used to open a directory handle. ... .

is_dir() Function: The is_dir() function is used to check whether the specified file is a directory or not..

How do you copy a file from one folder to another?

Moving and Copying Files & Folders.

Right-click the file or folder you want, and from the menu that displays click Move or Copy. The Move or Copy window opens..

Scroll down if necessary to find the destination folder you want. ... .

Click anywhere in the row of the folder you want..