I have files that are automatically uploaded onto a server from mobile phones, and I need to automatically transfer these files from the server to another server using PHP.
Could someone please explain how I would do this?
Thanks for any help
PHP has FTP functionality built in with FTP wrappers:
Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.
This means you can use FTP like any other file - an extremely simple example:
<?php
$data = file_get_contents('some/other/file.txt');
$fname = "ftp://name:yourpassword#127.55.41.10:21/some/path/filename.txt";
file_put_contents($fname,$data);
?>
Related
I need to upload same file to 2 different place in same FTP. Is there a way to copy the file on the FTP to the other place instead of upload it again? Thanks.
There's no standard way to duplicate a remote file over the FTP protocol. Some FTP servers support proprietary or non-standard extensions for this though.
Some FTP clients do support the remote file duplication. Either using the extensions or via a temporary local copy of the remote file.
For example WinSCP FTP client does support the duplication using both drag&drop and menu/keyboard command:
It supports the SITE CPFR/CPTO FTP extension (supported for example by the ProFTPD mod_copy module)
It falls back to an automatic duplication via a local temporary copy, if the above extension is not available.
(I'm the author of WinSCP)
Another workaround is to open a second connection to the FTP server and make the server upload the file to itself by piping a passive mode data connection to an active mode data connection. This solution is shown in the answer by #SaadAchemlal. This is basically use of FXP protocol, but for one server. Though many FTP servers will reject this, as they wont allow data connection to/from an address different to the client's.
Side note: people often confuse move with copy. In case you actually want to move, then that's a completely different question. Moving file on FTP is widely supported.
I don't think there's a way to copy files without downloading and re-uploading, at least I found nothing like this in the List of FTP commands and no client I have seen so far supported something like this.
Yes, the FTP protocol itself can support this in theory. The FTP RFC 959 discusses this in section 5.2 (see the paragraph starting with "When data is to be transferred between two servers, A and B..."). However, I don't know of any client that offers this sort of dual server control operation.
Note that this method could transfer the file from the FTP server to itself using its own network, which won't be as fast as a local file copy but would almost certainly be faster than downloading and then reuploading the file.
I can copy files between remote folders in Linux based systems.
In my particular case, I'm using very common file manager PCManFM:
Menu "Go" --> "Connect to server"
FTP Login info, etc
Open new tab in PCManFM
Connect to same server
Copy from tab to tab...
It's a bit slow, so I guess that it could be downloading and uploading back the files, but it's done automatically and very user-friendly.
The code below makes the FTP server to upload the file to itself (using loopback connection). It needs the FTP server to allow both passive and active connection mode.
If you want to understand the ftp commands here is a list of them : List of ftp commands
function copyFile($filePath, $newFilePath)
{
$ftp1 = ftp_connect('192.168.1.1');
$ftp2 = ftp_connect('192.168.1.1');
ftp_raw($ftp1, "USER ftpUsername");
ftp_raw($ftp1, "PASS mypassword");
ftp_raw($ftp2, "USER ftpUsername");
ftp_raw($ftp2, "PASS mypassword");
$res = ftp_raw($ftp2, "PASV");
$addressAndPort = substr($res[0], strpos($res[0], '(') + 1);
$addressAndPort = substr($addressAndPort, 0, strpos($addressAndPort, ')'));
ftp_raw($ftp1, "CWD ." . dirname($newFilePath));
ftp_raw($ftp2, "CWD ." . dirname($filePath));
ftp_raw($ftp1, "PORT ".$addressAndPort);
ftp_raw($ftp1, "STOR " . basename($newFilePath));
ftp_raw($ftp2, "RETR " . basename($filePath));
ftp_raw($ftp1, "QUIT");
ftp_raw($ftp2, "QUIT");
}
I managed to do this by using WebDrive to mount the ftp as a local folder, then "download" the files using filezilla directly to the folder. It was a bit slower than download normally is, but you dont need to have the space on your hdd.
Here's another workaround using PHP cUrl to execute a copy request on the server by feeding parameters from the local machine and reporting the outcome:
Local code:
In this simple test routine, I want to copy the leaning tower photo to the correct folder, Pisa:
$ch = curl_init();
$data = array ('pic' => 'leaningtower', 'folder' => 'Pisa');
curl_setopt($ch, CURLOPT_URL,"http://travelphotos.com/copypic.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Server code (copypic.php):
On the remote server, I have simple error checking. On this server I had to mess with the path designation, i.e., I had to use "./" for an acceptable path reference, so you may have to tinker with it a bit.
$pic = $_POST["pic"];
$folder = $_POST["folder"];
if (!$pic || !$folder) exit();
$sourcePath = "./unsortedpics/".$pic.".jpg";
$destPath = "./sortedpics/".$folder."/".$pic.".jpg";
if (!file_exists($sourcePath )) exit("Source file not found");
if (!is_dir("./sortedpics/".$folder)) exit("Invalid destination folder");
if (!copy($sourcePath , $destPath)) exit("Copy not successful");
echo "File copied";
You can do this from C-Panel.
Log into your C-Panel.
Go into file manager.
Find the file or folder you want to duplicate.
Right-click and chose Copy.
Type in the new director you want to copy to.
Done!
You can rename the file to be copied into the full path of your wanted result.
For example:
If you want to move the file "file.txt" into the folder "NewFolder" you can write it as
ftp> rename file.txt NewFolder/file.txt
This worked for me.
I've an IP-associated ftp access to an host, say ftp.host.com and I need to show in php pages (hosted somewhere else) some images hosted on the ftp site
The website php pages are the only ones allowed to access ftp.host.com because of the IP policies.
Of course, if I call images with " the call is done by the client, not the server, so it fails because of IP policies.
How can I call the images from server side? I can't use CURL nor FTP_GET because of the well known ftp over NAT php bug described here:
http://www.elitehosts.com/blog/php-ftp-passive-ftp-server-behind-nat-nightmare/
And I can't patch php because it's on an hosted server so I'm out of ideas
Any idea would be greatly appreciated!
These might work for you getimagesize() and readfile()
$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: $imginfo['mime']");
readfile($remoteImage);
I am working on a php web app .
I need to upload a file to the web server, with customer info - customers.csv.
but this process needs to be automated ,
The file will be generated in a Point of Sale app , and the app can open a browser window with the url ...
first i taught i would do something like this www.a.com/upload/&file=customers.csv
but read on here that is not possible,
then i taught i would set a value for the file upload field and submit form automatically after x seconds. Discovered thats not possible .
Anybody with a solution , will be appreciated .
EDIT
I have tried this and it works ,file is uploaded to remote server
is it working only because the php script is running on the same pc where csv is sitting ???
$file = 'c:\downloads\customers.csv';
$remote_file = 'customers.csv';
// set up basic connection
$conn_id = ftp_connect('host.com');
// login with username and password
$login_result = ftp_login($conn_id,'user','password');
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
This is of course not possible, imagine how this could be abused to upload on linux as example the /etc/passwd. The only way it might be possible is to use a Java Applet, but this is for sure not the best way.
You could try to let your PoS Application make a web request with the customers.csv file and let a WebAPI handle the upload, this may be possible, but I have no expierence with Point of Sale Applications.
Best might be, if the solution above cannot be considered, to just prompt the user to provide the file above and check over name + content if it is the correct one.
This is a bit tricky, but if your CSV is not too long, you could encode it in base64, send to the webserver as a GET parameter and then, in the server side, decode and store it as a CSV file.
If the file is too big to do that, you have to use other method, like the java applet pointed by #D.Schalla or even install and configure a FTP server, and make the Point of Sale app uploads the file there.
Other alternative, specially good if you cannot modify the sale app, is to install a web server in the client side and write a small php script to handle the upload process. In this way, the sale app could call a local url (something like: http:// localhost/upload.php) and it's this script the one in charge to upload the file which can be achieve with a classical HTTP POST, a FTP connection or any other way you can think about.
MY Solution , which will work with out setting up web server on client side.
This is for windows but can be adapted to linux
On client side
Local Application opens cmd and runs this command ftp -n -s:C:\test.scr
WHICH opens test.scr - a file with ftp commands e.g.
open host.com
user1
passwOrd
put C:\downloads\customers.csv public_html/customers.csv
more info here :
http://support.microsoft.com/kb/96269
more commands :
http://www.nsftools.com/tips/MSFTP.htm#put
Slightly weird concept here... A client of ours wants data pushed to them over FTP/S
The idea is that we download one of our reports by downloading from a URL (a CSV File), then push this to the client over FTP/S. I know I can do this in bash scripts using wget & ftp - but need to add to this over a web interface so PHP is the best way forward.
As this is a background task I can extend time-outs etc.
I know also I can use fopen to download and save a file, then find it and upload it using the PHP FTP library. Just looking for a way to download using fopen, hold the data in memory to upload straight away.
Any help appreciated in advance!
To retrieve the data from the URL you have a few options. You say you want the data in memory only to push directly to the FTP host.
One approach (that I find the simplest to use, but lacking in terms of reliability and error handling) is file_get_contents()
Example:
$url = 'http://www.domain.com/csvfile';
$data = file_get_contents($url);
Now you have your csv data in $data, over to how to push this to an ftp server.
Again the simplest way to do this is to use the builtin stream wrappers as used in the get example above. (Note however that this requires PHP 4.3.0)
Simply build up the connection string like this.
$protocol = 'ftps';
$hostname = 'ftp.domain.com';
$username = 'user';
$password = 'password';
$directory = '/pub';
$filename = 'filename.csv';
$connectionString = sprintf("%s://%s:%s#%s%s/%s",
$protocol,$username,$hostname,
$password,$directory,
$filename);
file_put_contents($connectionString,$data);
Have a look at the ftp wrappers manual
If this does not work there are other options.
You could use curl to get the data and the FTP Extension to push it.
To avoid saving the file to disk and "to upload straight away" i.e. to start pushing to FTP as soon as the first chunk of Data is downloaded?
Try this:
http://www.php.net/manual/en/function.stream-copy-to-stream.php
You'll need an FTP server and client library which support resuming uploads
If i have a local file, for example, c:/test.txt, what path do i need to type in the ftp_put function to make it work (string $local_file)? When i try with "c:/test.txt" i get an error.
Thanks
Its on a remote server. Am i using wrong php function? I want to upload a local file to a remote ftp ...
Yes, you're using the wrong function.. Remember - PHP executes on the SERVER, not in your browser and not on your local machine. Any FTP connection you establish in the PHP script will be relative to the server.
e.g. If you've got something like this:
(your machine) ----> (your website) ----> (other machine you ftp to)
The FTP connection will be between "your website" and "other machine you ftp to". Any "local" path you specify for a file will be local to "your website", not "your machine".
You'd first have to upload the file via regular HTTP file sending mechanisms via a form on your site, which gets the file from "your machine" to "your server". The PHP script which handles the upload can then use the FTP functions to transfer the file from "your website" to "other machine you ftp to".
I think that if you have to use ftp to pull a file off your machine (as opposed to using a html form) your best bet would be to set your local machine up as an ftp server. You would probably need an static ip address for this to be consistent. You could then have your script connect to your local machine and use ftp_get to grab test.txt.