Link to home
Start Free TrialLog in
Avatar of wjdashwood
wjdashwood

asked on

ftp account on the remote server to copy file

I need the content of a file to be available for use on a different domain. I have been told this can be done by setting up a ftp account on the remote server. I could do with some help with the steps on how I should go about setting this up.

Thanks,
H
Avatar of CosminB
CosminB

try this script:

<?php
function getFile($serverFile, $localFile)
{
      global $ftpAccount, $ftpPasswd;
      $conn = ftp_connect($ftp_server) or die ('Could not connect to the ftp server');
      ftp_login($conn, $ftpAccount, $ftpPasswd) or die('Could not login to the ftp server');
      ftp_get($conn, $localFile, $serverFile, FTP_ASCII) or die('Could not download the file from the ftp server');
      ftp_close($conn);
}

function saveFile($serverFile, $localFile)
{
      global $ftpAccount, $ftpPasswd;
      $conn = ftp_connect($ftp_server) or die ('Could not connect to the ftp server');
      ftp_login($conn, $ftpAccount, $ftpPasswd) or die('Could not login to the ftp server');
      ftp_put($conn, $serverFile, $localFile, FTP_ASCII) or die('Could not upload the file to the ftp server');
      ftp_close($conn);
}

function getBlock($text, $startString, $endString)
{
      if (strpos($text, $startString) !== false && strpos($text, $endString) !== false)
            return trim(substr($text, strpos($text, $startString) + strlen($startString), strpos($text, $endString)-strpos($text, $startString)-strlen($startString)));
      else
      {
            if (strpos($text, $startString) === false)
                  echo '<h1>Missing "',$startString,'" in input file</h1>';
            if (strpos($text, $endString) === false)
                  echo '<h1>Missing "',$endString,'" in input file</h1>';
      }
}

$ftpServer = 'your.server.com';
$ftpAccount = 'yourAccount';
$ftpPasswd = 'yourPassword';
$serverFile = '/path/on/the/remote/server/filename.php';
$tempFile = '/path/to/tempFile.php';
getFile($serverFile, $tempfile);
$contents = implode('',file($tempFile));

if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
      $cssContent = getBlock($contents, '//start css', '//end css');
      $topContent = getBlock($contents, '//start top', '//end top');
      $pageContent = getBlock($contents, '//start page', '//end page');
      $bottomContent = getBlock($contents, '//start bottom', '//end bottom');
      
      echo '<form action="" method="post">';
      echo 'CSS: <textarea name="css">', $cssContent, '</textarea>';
      echo 'TOP: <textarea name="top">', $topContent, '</textarea>';
      echo 'PAGE: <textarea name="page">', $pageContent, '</textarea>';
      echo 'BOTTOM: <textarea name="bottom">', $bottomContent, '</textarea>';
      echo '<input type="submit" value="Save"></form>';
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
      if (is_writable($fileName))
      {
            $cssContent = "\n//start css\n". $_POST['css']."\n//end css\n";
            $topContent = "\n//start top\n". $_POST['top']."\n//end top\n";
            $pageContent = "\n//start page\n". $_POST['page']."\n//end page\n";
            $bottomContent = "\n//start bottom\n". $_POST['bottom']."\n//end bottom\n";
            $fp = fopen($tempFile, 'w');
            fwrite($fp, $cssContent);
            fwrite($fp, $topContent);
            fwrite($fp, $pageContent);
            fwrite($fp, $bottomContent);
            fclose($fp);
            saveFile($serverFile, $tempfile);
      }
      else
            echo $fileName, ' is not writeable';
}
?>

remember to give write permission to the dir where your temp file will be.
Avatar of wjdashwood

ASKER

It says:

Call to undefined function: ftp_connect() ...

Any ideas?
from php.net

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP 4 or --with-ftp when using PHP 3.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


you can check your compilied option with phpinfo()

hope this helps.

Lk
it's saying that your php hasn't been copiled with ftp support
I have emailled my hosting company to get them to enable it. I'll get back to the question when they have done this. It will probably tomorrow.
Thanks,
H
If you just need the file accessed from a PHP page, why don't you just use...

<?
include("http://www.somedomain.com/myfile.html");
?>

Then you can do what ever you wish with the contents.
and if u dont want to display on webpage

you can send headers so it ask user to save file

Lk
apparently I have CURL functions available to me that should be sufficient to do what I need. Can anyone explain what these are and how I can use them rather than the ftp_connect() php command?

Thanks,
H
CURL is like using a browser to retrieve a page. INCLUDE is more like FTP. What sort of page are you trying to get (text, html, etc.) and what are you needing to do with it?
I would like to get the source of a php file with html content and copy it over to my domain to edit before saving the edited file back to the first domain. I own both domains.
Oh. Try this:

$handle = fopen("http://www.example.com/xyz.php", "w+");

Then do what you need to with the file handle.

See also: http://www.php.net/fopen
this won't work: "$handle = fopen("http://www.example.com/xyz.php", "w+");"
will that not even work to just make a copy of the file to the domain where the code is called from? Because then I can use the code you already gave me to extract the content and edit it.

- H
It's the same thing(copying it or reading it directly). You'll have to acces the file directly, using ftp or putting your script on the same server
so it the only way to do it using the ftp_connect command?
there are other ways to transfer files between two servers but php only implements ftp
I'm transferring my domain to a server which is currently setup to enable the use of the ftp_connect function. It may be some time so please check back, probably in a couple of days and I'll let you know if the code worked.

Thanks again for all the help.
Finally I have everything setup on a server which apparently has the ftp_connect function available. My new error is:

Warning: file_get_contents(ftp://w......demo.php): failed to open stream: FTP server reports 530 Login incorrect. in /home/..../public_html/..../editpage.php on line 45

Does this mean it is trying to get it from the wrong place?
have you tried my script exactly the way I wrote it? I don't have a file_ge_contents in my code ... if you changed the code post it here so i could see what exactly are your doing
I think my main problem is the servers. I realised that I had notchecked the correct code, but I now have the right code and the errors are to do with the variables.

$ftpServer = 'your.server.com';    
                    -   Is this the host name of the domain holding the original file to edit?
$ftpAccount = 'yourAccount';
                    -   Is this the userID of the domain holding the original file to edit?
$ftpPasswd = 'yourPassword';
                    -   Is this the password of the domain holding the original file to edit?
$serverFile = '/path/on/the/remote/server/filename.php';
                    -   Is this address of the original file? do I start this with ftp? or www?
$tempFile = '/path/to/tempFile.php';
                    -   Is this the path from the loaded file to where the temp file will be held?

Thanks for getting back so quick,
H
$ftpServer = 'remote.server.com'; //this has to be the server where the file that you want to edit is
$ftpAccount = 'ftpAccount'; //this has to be the username for the ftp account
$ftpPassword = 'ftpPassword'; //this has to be the password for the ftp account
$serverFile = '/userdir/public_html/dir/file.php'; //this has to be the real path to the file on the remote server. so if the remote server is a windows server $serverFile should be ''c:\some\path\to\file.php', and if it's a linux/unix server it should be '/some/path/to/file.php'

$tempFile = '/path/to/tempFile.php'; //this has to be the path where your temp file will be stored.(on the same that runs the script)
ok i think i have all of those right. I get this error:

Warning: ftp_connect(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/.../public_html/..../files.php on line 13
Could not connect to the ftp server

i am using the code exactly how you put earlier on the page, but with the (hopefully) correct paths in
that means that the script could not connect to the ftp server
are sure you have ftp access on your remote server? If yes make sure the name of the server is spelled corectly and if that doen't work try with the server ip instead of the server name
ps: you server name has to be either 'www.server.com' or '192.123.321.123' NOT 'http://www.server.com/path' or anythuing like that
the server name is correct. Is it the place where the original file is stored that needs to have the ftp_connect() available? Or is it the one that has the script using the command. The one that has the script using the command does have it available. The other I will find out.
no, I am informed that it is enabled on both accounts. Could anything else be causing the problem?
try this(I assume you are on windows):
- open your command prompt
- type ftp and hit enter
- type "open <nameofremoteserver>"
- type your username & password

tell me if it works
it says unknown host after the open command. Does that mean the ftp isn't actually available?
no it means it cand find your host ... try with the ip
does it find your host if you type in the browser "http://yourhost/" ?
ah, i was typing in the < and >. Sorry
It has let me in now. it says:
230-User la***e has group access to:  la***e
230 OK. Current restricted directory is /
"ah, i was typing in the < and >" ???

try the same host on the script ($ftpServer) ... make sure you don't "type in the < and >"
that is the host I was using on the script for the $ftpServer variable
are you saying that it gives you the same error?
yeah, I didn't have to change the code in the script. I had already put the correct ftpserver name
i had a few bugs in my script ... sorry, my fault for not testing it

try this:
<?php
function getFile($serverFile, $localFile)
{
      global $ftpAccount, $ftpPasswd, $ftpServer;
      $conn = ftp_connect($ftpServer) or die ('Could not connect to the ftp server');
      ftp_login($conn, $ftpAccount, $ftpPasswd) or die('Could not login to the ftp server');
      echo $localFile," - ", $serverFile;
      ftp_get($conn, $localFile, $serverFile, FTP_ASCII) or die('Could not download the file from the ftp server');
      ftp_close($conn);
}

function saveFile($serverFile, $localFile)
{
      global $ftpAccount, $ftpPasswd;
      $conn = ftp_connect($ftp_server) or die ('Could not connect to the ftp server');
      ftp_login($conn, $ftpAccount, $ftpPasswd) or die('Could not login to the ftp server');
      ftp_put($conn, $serverFile, $localFile, FTP_ASCII) or die('Could not upload the file to the ftp server');
      ftp_close($conn);
}

function getBlock($text, $startString, $endString)
{
      if (strpos($text, $startString) !== false && strpos($text, $endString) !== false)
            return trim(substr($text, strpos($text, $startString) + strlen($startString), strpos($text, $endString)-strpos($text, $startString)-strlen($startString)));
      else
      {
            if (strpos($text, $startString) === false)
                  echo '<h1>Missing "',$startString,'" in input file</h1>';
            if (strpos($text, $endString) === false)
                  echo '<h1>Missing "',$endString,'" in input file</h1>';
      }
}

$ftpServer = 'remoteserver';
$ftpAccount = 'ftpAccount';
$ftpPasswd = 'ftpPassword';
$serverFile = '/path/to/remote/file.php';
$tempFile = '/path/to/temp/file.php';
getFile($serverFile, $tempFile);
$contents = implode('',file($tempFile));

if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
      $cssContent = getBlock($contents, '//start css', '//end css');
      $topContent = getBlock($contents, '//start top', '//end top');
      $pageContent = getBlock($contents, '//start page', '//end page');
      $bottomContent = getBlock($contents, '//start bottom', '//end bottom');
      
      echo '<form action="" method="post">';
      echo 'CSS: <textarea name="css">', $cssContent, '</textarea>';
      echo 'TOP: <textarea name="top">', $topContent, '</textarea>';
      echo 'PAGE: <textarea name="page">', $pageContent, '</textarea>';
      echo 'BOTTOM: <textarea name="bottom">', $bottomContent, '</textarea>';
      echo '<input type="submit" value="Save"></form>';
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
      if (is_writable($fileName))
      {
            $cssContent = "\n//start css\n". $_POST['css']."\n//end css\n";
            $topContent = "\n//start top\n". $_POST['top']."\n//end top\n";
            $pageContent = "\n//start page\n". $_POST['page']."\n//end page\n";
            $bottomContent = "\n//start bottom\n". $_POST['bottom']."\n//end bottom\n";
            $fp = fopen($tempFile, 'w');
            fwrite($fp, $cssContent);
            fwrite($fp, $topContent);
            fwrite($fp, $pageContent);
            fwrite($fp, $bottomContent);
            fclose($fp);
            saveFile($serverFile, $tempfile);
      }
      else
            echo $fileName, ' is not writeable';
}
?>

there is a chatch:
  $tempFile has to exist before you can start the ftp process and has be writeable by the web server(you can copy a file to your temp file directory and do a chmod 777 on that file)
  or the directory holding the temp file has to be writeable by the webserver(you cand do a chmod 777 to the dir containing the temp file or set $tempFile to  '/tmp/somefilename.someextension' (by default de /tmp directory is writeable by the web server))

i found some more bugs ... please wait about 15 mins
ok thanks. I really appreciate your help :)
ASKER CERTIFIED SOLUTION
Avatar of CosminB
CosminB

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i get:

Remote file: /sitefiles1/demo.php

Warning: ftp_get(): Error opening in /home/****/public_html/***/files.php on line 16
Could not download the file from the ftp server

what did I do wrong?
that means that the file path is incorect
if you remote web directory is /home/your_username/public_html and you want to edit the file located at http://remoteserver/sitefiles/demmo.php you should use
$serverFile = '/home/your_username/public_html/sitefiles/demmo.php'; //remeber you have to use the absolute path of that file

if you don't know the absolute file path of the remote file open a ftp connection(see earlier post) and do a 'pwd' command . This will return the absoulte path to the curent directory. Type 'ls' or 'dir' to view the directory contents. Type 'cd "directoryname"' to enter a directory or 'cd ..' to leave a directory. Once you have entered the remote directory where your file is type 'pwd' to find the absolute path. Put this path in $serverFile (remember to add the filename)
i have changed the file path to the one it gave me when doing the pwd thing and it came up with the same error so I tried a few other combinations and tried changing the path to the temp file incase that was the one which was wrong, all of which gave me the same error. In the pwd it gave me the file path as /public_html/sitefiles/demo.php the home and username were not there, but i did try with the home and username too which didn't work.
try with '~/public_html/sitefiles/demo.php'
or './public_html/sitefiles/demo.php'
no luck.  Is it definately that path? could the problem be caused by anything else?
it's the filename for sure
try with 'public_html/sitefiles/demo.php'

if this doesn't work open a ftp connection (again) and type "get public_html/sitefiles/demmo.php c:\demmo.php" (if you are on windows) or "get public_html/sitefiles/demmo.php ~/demmo.php" and tell me what the error is, or if it creates a file in c:\ (or in your home directory) if you are on linux
actually i might be wrong
change the temp file path to a file that already exists(absoulte path)
It works in the command prompt, but still not in the script!

200 PORT command successful
150 Connecting to port 33514
226-File successfully transferred
226 0.008 seconds (measured here), 487.32 Kbytes per seco
ftp: 3903 bytes received in 0.09Seconds 41.52Kbytes/sec.
it must be the temp file

change your getFile function with this and tell me what it says

function getFile($serverFile, $localFile)
{
      global $ftpAccount, $ftpPasswd, $ftpServer;
      echo 'Remote file: ',$serverFile,"<br>";
      $conn = ftp_connect($ftpServer) or die ('Could not connect to the ftp server');
      ftp_login($conn, $ftpAccount, $ftpPasswd) or die('Could not login to the ftp server');
      if (!is_file($localFile) || !is_writeable(dirname($localFile)))
            die('Local file error'.$localFile);
      ftp_get($conn, $localFile, $serverFile, FTP_ASCII) or die('Could not download the file from the ftp server');
      ftp_close($conn);
}
Remote file: public_html/sitefiles1/demo.php
Local file error

thats what it says
replace your function again with this and tell me what is says
function getFile($serverFile, $localFile)
{
      global $ftpAccount, $ftpPasswd, $ftpServer;
      echo 'Remote file: ',$serverFile,"<br>";
      $conn = ftp_connect($ftpServer) or die ('Could not connect to the ftp server');
      ftp_login($conn, $ftpAccount, $ftpPasswd) or die('Could not login to the ftp server');
      if (is_file($localFile))
      {
            if (!is_writable($localFile))
                  die('A file with the name '.$localFile.' exists but it\'s not writeable');
      }
      elseif (!is_writable(dirname($localFile)))
      {
            die('The file with the name '.$localFile.' doesn\'t exists and the parent directory '.dirname($localFile).' is not writeable');
      }
      ftp_get($conn, $localFile, $serverFile, FTP_ASCII) or die('Could not download the file from the ftp server');
      ftp_close($conn);
}
The file with the name doesn't exists and the parent directory is not writeable
the getFile($serverFile, $tempFile); didn't have a capital F for file. now it says:
The file with the name /tempfiles/alter.php doesn't exists and the parent directory /tempfiles is not writeable
it should certainly be writeable, but perhaps the path is wrong, i'll have another go with the path
i did the pwd thing and got the exact path, but it still comes up with the same error. I did change the permissions so that the directory is 0777
remember that this paths have to be absolute paths. so if you have in your home dir(on your local server) a directory called "tempfiles" the absolute path to that directory is "/home/userdir/tempfiles" or smth. like that.
if you have ssh or telnet access to your server type pwd to see the curent absolute path
if you have ssh or telenet acces do this:
cd / [ENTER]
stat tempfiles [ENTER]
//you should see some output. tell me what it says
ftp> cd /
250 OK. Current directory is /
ftp> stat tempfiles
Connected to u***e.com.
Type: ascii; Verbose: On ; Bell: Off ; Promp
Debugging: Off ; Hash mark printing: Off .

is that what you meant?
or add this at the begining of your script and tell me what it says
echo $_SERVER['SCRIPT_FILENAME'],"<br><br>";
not ftp!
only for SSH or TELNET
i think we have a winner. I got the path wrong i had been trying it without the / at the start, as that was how i had the serverfile path
now it seems to work, but still not finding the code. Give me a bit of time to try and figure this out. Thanks so much for taking me through it step by step. I would have been so lost witout you!
i have to go now ... if you have any more problems post them here and I'll read them tomorow morning.

happy debuging
It now works fine. I've even managed to get it working within an existing file that doesn't output it in a textbox.

I may still need help at some point at the part to get it to save, but you never know I might figure out how to do it myself.

Thanks for all the help the points are well deserved!