简体   繁体   English

在php中以编程方式将文件从一台服务器复制到另一台服务器

[英]copy file from one server to another programmatically in php

I've hosted my all code files on one server whose domain is like example.com and I'm at one of those html pages.我在一台服务器上托管了我的所有代码文件,该服务器的域类似于example.com并且我在这些 html 页面之一。 I want some files of example.com to move on another server whose domain is like example2.com .我希望 example.com 的一些文件移动到另一台服务器上,其域类似于example2.com I've searched through Internet but I couldn't find any good solution.我已经通过互联网搜索,但我找不到任何好的解决方案。 Please tell me is this possible without FTP client or without browser where we upload files manually.请告诉我这是否可能没有 FTP 客户端或没有我们手动上传文件的浏览器。 Or is there any way to submit file from HTML form from one server to another like if on action we'll write或者有什么方法可以将 HTML 表单中的文件从一台服务器提交到另一台服务器,就像我们将编写的操作一样

<form action="http://example2.com/action_page.php">

Any help would be much appreciated.任何帮助将非常感激。

If you set the contents of this file: example2.com/action_page.php to:如果将此文件的内容:example2.com/action_page.php 设置为:

<?php
$tobecopied = 'http://www.example.com/index.html';
$target = $_SERVER['DOCUMENT_ROOT'] . '/contentsofexample/index.html';

if (copy($tobecopied, $target)) {
    //File copied successfully
}else{
    //File could not be copied
}
?>

and run it, through command line or cron (as you have written a php related question, yet banned use of browsers!) it should copy the contents of example.com/index.html to a directory of your site (domain: example2.com) called contentsofexample.并通过命令行或 cron 运行它(因为您已经写了一个与 php 相关的问题,但禁止使用浏览器!)它应该将 example.com/index.html 的内容复制到您站点的目录(域:example2. com) 称为内容示例。

NB If you wanted this to copy the whole website you should place it in a for loop注意如果你想复制整个网站,你应该把它放在一个 for 循环中

There are still 2 possible ways which can used to copy your files from another server.还有两种可能的方法可以用来从另一台服务器复制文件。

-One is to remove your .htaccess file from example.com or allow access to all files(by modifying your .htaccess file). - 一个是从 example.com 删除您的 .htaccess 文件或允许访问所有文件(通过修改您的 .htaccess 文件)。 -Access/Read those files via their respective URLs, and save those files using 'file_get_contents()' and 'file_put_contents()' methods. - 通过它们各自的 URL 访问/读取这些文件,并使用“file_get_contents()”和“file_put_contents()”方法保存这些文件。 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).或者,您可以在 example.com 上创建代理/服务以在验证密码或用户名/密码组合(根据您的要求进行任何操作)后读取特定文件。

            //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 '.您可以通过 url ' http://example.com/myproxy.php?file=filename.extension&passkey=my-secret-key ' 访问该代理/服务。

You can exchange files between servers by also using zip method.您也可以使用 zip 方法在服务器之间交换文件。 You own both servers so you shouldn't have security issues.你拥有两台服务器,所以你不应该有安全问题。

On the server that hosts the file or folder you want, create a php script and create a cron job for it.在托管您想要的文件或文件夹的服务器上,创建一个 php 脚本并为其创建一个 cron 作业。 Sample code below:示例代码如下:

<?php
/**
 * ZIP All content of current folder

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

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

/* Path of current folder, need empty or null param for current folder */
$root_path = realpath( '' ); //or $root_path = realpath( 'folder_name' ); if the file(s) are in a particular folder residing in the root

/* 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();
?>

Create another php script and cron job on the server to receive the copy as below:在服务器上创建另一个 php 脚本和 cron 作业以接收如下副本:

/**
* Transfer Files Server to Server using PHP Copy
*
*/ /* Source File URL */
$remote_file_url = 'url_of_the_zipped';

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

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

/* Add notice for success/failure */ 
if( !$copy ) {
echo "Failed to copy $file...\n"; }
else{
echo "Copied $file successfully...\n"; }
$file = 'myfiles.zip';
$path = pathinfo( realpath( $file ), PATHINFO_DIRNAME );
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
$zip->extractTo( $path );
$zip->close();
echo "$file extracted to $path"; }
else {
echo "Couldn't open $file";
}
?>

Voila!瞧!

    <?php
/* Source File URL */
$remote_file_url = 'http://origin-server-url/files.zip';
  
/* New file name and path for this new 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! Thanks Munshi and OBOYOB! success to copy $file...\n";
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM