I'm having trouble getting file_put_contents() to work in uploading decoded email attachments as files onto my server. Here is the basic script:
$user = "user";
$pass = "pass";
$host = "ftp://mydomain.com";
$content = 'hello';
$file = 'public_html/mydomain.com/files/readme.txt';
$options = array('ftp' => array('overwrite' => true));
$stream = stream_context_create($options);
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file;
file_put_contents($hostname, $content, 0, $stream);
I've tried various formulations of this, including logging in as different ftp users, and no matter what I do I get a "no such file or directory" error. My server has the typical structure of "/public_html/mydomain.com/" file structure, but this doesn't seem to work.
However, when I try to us ftp_put(), it seems to make the connection and find the directory just fine -- but I can't use ftp_put() because I'm not uploading a local file but a string to a remote file.
Here's the code I used for that:
$user = "user";
$pass = "pass";
$host = "mydomain.com";
$ftp_path = '/public开发者_Go百科_html/files';
$content = 'localfile.txt'
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_pasv($conn_id, true);
ftp_login($conn_id, $user, $pass) or die("Cannot login");
// perform file upload
ftp_chdir($conn_id, '/public_html/mydomain.com/files/');
$upload = ftp_put($conn_id, $ftp_path, $content, FTP_BINARY);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
ftp_close($conn_id);
I realize that I'm probably missing something dead simple, any help?
You have this line in your code:
$file = 'public_html/mydomain.com/files/readme.txt';
Which makes me assume: either your working script is outside Web-root, OR the code is wrong... You sure file's location is right?
The only thing that comes to mind is this:
$user = "user";
$pass = "pass";
$host = "ftp://mydomain.com";
$content = 'hello';
$file = 'public_html/mydomain.com/files/readme.txt';
$options = array('ftp' => array('overwrite' => true));
$stream = stream_context_create($options);
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file;
file_put_contents($hostname, $content, 0, $stream);
Or more specifically, this line:
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file;
Will result in a URL like
User:Pass@ftp://host.com/file
While it should be
ftp://User:Pass@host.com/file
So I would change it to
$protocol = "ftp://";
$user = "user";
$pass = "pass";
$host = "mydomain.com";
$content = 'hello';
$file = 'public_html/mydomain.com/files/readme.txt';
$options = array('ftp' => array('overwrite' => true));
$stream = stream_context_create($options);
$hostname = $protocol . $user . ":" . $pass . "@" . $host . "/" . $file;
file_put_contents($hostname, $content, 0, $stream);
That will also give you leeway later on if you need to use a different protocol.
精彩评论