Can I create/write on a file on开发者_运维知识库 another host & domain with file_put_contents() OR fwrite()?
If I can, what permissions and other property should set on that host?
Thanks ..
check this out from http://www.php.net/manual/en/function.file-put-contents.php#101408
To upload file from your localhost to any FTP server. pease note 'ftp_chdir' has been used instead of putting direct remote file path....in ftp_put ...remoth file should be only file name
<?php
$host = '*****';
$usr = '*****';
$pwd = '**********';
$local_file = './orderXML/order200.xml';
$ftp_path = 'order200.xml';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_pasv($conn_id, true);
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// perform file upload
ftp_chdir($conn_id, '/public_html/abc/');
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
// close the FTP stream
ftp_close($conn_id);
?>
I wrote a function similar to PHP file_put_contents() which is writing to a FTP server:
function ftp_file_put_contents($remote_file, $file_string)
{
// FTP login
$ftp_server="my-ftp-server.com";
$ftp_user_name="my-ftp-username";
$ftp_user_pass="my-ftp-password";
// Create temporary file
$local_file=fopen('php://temp', 'r+');
fwrite($local_file, $file_string);
rewind($local_file);
// Create FTP connection
$ftp_conn=ftp_connect($ftp_server);
// FTP login
@$login_result=ftp_login($ftp_conn, $ftp_user_name, $ftp_user_pass);
// FTP upload
if($login_result) $upload_result=ftp_fput($ftp_conn, $remote_file, $local_file, FTP_ASCII);
// Error handling
if(!$login_result or !$upload_result)
{
echo('FTP error: The file could not be written on the remote server.');
}
// Close FTP connection
ftp_close($ftp_conn);
// Close file handle
fclose($local_file);
}
// Usage
ftp_file_put_contents('my-file.txt', 'This string will be written to the remote file.');
If you want to use file_put_contents
specifically, you have to use a stream context for a protocol the remote server accepts for uploading. For instance, if the server is configured to allow PUT requests, you could create an HTTP context and send the appropriate method and content to the server. Another option would be to setup an FTPs context.
There is an example in the comments for file_put_contents
on how to use it with a stream context for FTP. Note that the used ftp://user:pass@host URI scheme is transmitting the user credentials in cleartext.
Additional examples
精彩评论