FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!


FTP and PHP





The Tank
First thing first, Hello every one. I'm new on this forum, my first language is French and I'm not perfectly bilingual. Be nice to me Wink

I need help creating a FTP client in PHP and host on my website. I've tried a couple of example i found on Google, but they were not very useful. If someone has done something like that before and would be kind enough to share it, that would be great.

Thanks in advance.
The Tank
Diablosblizz
If you are talking about just for your site then you can use Fopen to open the files. If you're talking about as a net2ftp type of thing, then I do not know what to do.

That would take some major coding.
The Tank
Diablosblizz wrote:
If you are talking about just for your site then you can use Fopen to open the files. If you're talking about as a net2ftp type of thing, then I do not know what to do.

That would take some major coding.


My goal is to have my clients being able to upload small files into their own folder on my server. Some of my client don't know much about ftp software. So I'm looking at something like, they login to their own section on my website, then browse for the file and hit upload.
Diablosblizz
Maybe you could try:

Code:


fopen("ftp://website.url(probablyinapostvariable):username:password");


And then go from there. That would probably work.
The Tank
Diablosblizz wrote:
Maybe you could try:

Code:


fopen("ftp://website.url(probablyinapostvariable):username:password");


And then go from there. That would probably work.


Thanks. That can be useful and simple. Will try that when back home tonight.
The Tank
OK, I manage to create what I wanted to do, and it was working fine on my computer with EasyPHP. But since I uploaded the site online, everything is working except for the upload part.

Here is my code:

Code:
<?php
session_start();

//variable
$ftp_server = $_SESSION['ftp_serv'];
$ftp_user_name = $_SESSION['ftp_user'];
$ftp_user_pass = $_SESSION['ftp_pass'];
$ftp_folder = "html/fichier_client/".$_SESSION['folder'];
$destination_file = basename($_POST['file']);
$source_file = $_POST['file'];

// Mise en place d'une connexion basique  : $ftp_server
$conn_id = ftp_connect($ftp_server);

// Identification avec un nom d'utilisateur et un mot de passe  : $conn_id, $ftp_user_name, $ftp_user_pass
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Vérification de la connexion
if ((!$conn_id) || (!$login_result)) {
        echo "La connexion FTP a échoué !\n\n";
        echo "Tentative de connexion au serveur $ftp_server pour l'utilisateur $ftp_user_name\n\n";
        exit;
    } else {
        echo "Connexion au serveur $ftp_server, pour l'utilisateur $ftp_user_name\n\n";
    }

// Tentative de modification du dossier en "somedir"
echo "Dossier courant : " . ftp_pwd($conn_id) . "\n\n";
if (ftp_chdir($conn_id, $ftp_folder)) {
    echo "Le dossier courant est maintenant : " . ftp_pwd($conn_id) . "\n\n";
} else {
    echo "Impossible de changer de dossier\n\n";
}

// Chargement d'un fichier
echo $conn_id."\n\n";
echo $destination_file."\n\n";
echo $source_file."\n\n";
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// Vérification du status du chargement
if (!$upload) {
        echo "Le chargement FTP a échoué!\n\n";
    } else {
        echo "Chargement de $source_file vers $ftp_server en tant que $destination_file\n\n";
    }

// Fermeture du flux FTP
ftp_close($conn_id);
?>


If I did forget something let me know.
Thank
mathiaus
The Tank wrote:
If I did forget something let me know.

Code:
[code][/code]

Code Tags Wink
MrBlueSky
The Tank wrote:


If I did forget something let me know.
Thank


Chances are it has something to do with the filepermissions. Is the directory you are uploading to writeable for apache?

Try changing this line

Code:

if (ftp_chdir($conn_id, $ftp_folder)) {


to

Code:

if (ftp_chdir($conn_id, '/tmp')) {


If this works, and your file uploads to /tmp, then it sure is a problem with filepermissions.
kv
Here is a project in sourceforge http://sourceforge.net/projects/browseftp/

It has a ftp helper php class which makes it very easy to use ftp functions in php. There is also a sample php file along, which gives a basic UI to demonstrate how to use the helper class.

You can just enhance the UI and tweak it to meet your requirements.
manum
i dont think tht the ftp lib of php is enabled on frih...please ask d support and if its there then goto pscode.com and search there...i hav seen a wonderfull example der....
wexaz
what a else? PHP and mySQL? its a two different things as night and day I think Wink PHP is a computer language and mySQL is database Wink
Fire Boar
You're using $_POST['file']. Shouldn't that be something like $_FILES['file']? I'll share an example of something I did for another website. The file has been included from another file so it will need editing to suit your purposes. But it does work.

Code:
<?php
if (!defined('MAINTENANCE')) die('You cannot access this file directly.');
// Is there an uploaded file?
if ($_FILES['uploadedfile']['name'])
{
   $target_path = ($_POST['type'] == "file") ?
      $GLOBALS['cmConfig']['cms_root']."uploads/".$_FILES['uploadedfile']['name']:
      $GLOBALS['cmConfig']['cms_root']."images/".$_FILES['uploadedfile']['name'];
   $tries = 0;
   $target_path_final = $target_path;
   while (file_exists($target_path_final))
   {
      $tries++;
      $processing_path = str_replace(substr($target_path, strpos($target_path, '.')), '', $target_path);
      $target_path_final = $processing_path.$tries.substr($target_path, strpos($target_path, '.'));
   }
   if (!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path_final))
   {
      $page_output = "There was an error uploading the file, please try again.<br /><br /><a href=\"?maintaining=tool_upload\">Go back.</a>";
   }
   else
   {
      $page_output = "File uploaded successfully.<br /><br />";
      $page_output .= "The file is located at ".substr($target_path_final, strlen($GLOBALS['cmConfig']['cms_root']));
   }
}
else
{
   $page_output = <<< OUTPUT
<form enctype="multipart/form-data" action="?maintaining=tool_upload" method="post">
   <input type="file" name="uploadedfile" /><br /><br />
   This is:<br />
   <input id="opt_file" type="radio" name="type" value="file" checked="checked" /><label for="opt_file">A file</label><br />
   <input id="opt_image" type="radio" name="type" value="image" /><label for="opt_image">An image</label><br /><br />
   <input type="submit" value="Upload" />
</form>
OUTPUT;
}
?>
jabapyth
if you use a cgi script (perl/python) you wont need to worry about file permissions (as much)
thinkingskull
script 2 check wether a directory exists


Code:
<?php

// This is the directory we want to create

    $dir = "newdir";

   
// This is the URL on the remote server of the
// script that is going to FTP back to us.

    $url = "http://ftpenabled.server.com/ftp.php?dir=$dir";

// This just checks if the directory already exists ....
// if it doesn't call our remote script to FTP back to
// us and create it.

// Also check  "allow_url_fopen" is enabled.
       
      if(!file_exists("/var/www/html/testdomain/public_html/$dir"))
    {
   
// Now open the URL. The remote script can pass data back to
// us in $var

        $fh = fopen($url,"r");
        while(!feof($fh))
        {

// Just to stop it timing out ... FTP isn't fast!
       
            set_time_limit(10);
            $var = fgets($fh, 1024);
            print($var);
        }
        fclose($fh);
    }
}
?>


[b]Uploading script......[/b]

<?php

// If the server where this file is located
// has the FTP portion of PHP enabled then
// you call just run this function locally.

// Dir is the directory to create

$dir       = $HTTP_GET_VARS["dir"];

// These 3 variable you could pass to the
// script within the URL if you wanted -
// bit insecure though

$ftp_ip          = "ftp.this.com";
$ftp_username = "username";
$ftp_password = "password";

if($ftp=ftp_connect($ftp_ip))
{
    if(ftp_login($ftp,$ftp_username,$ftp_password))
    {

// Set to PASV mode

        ftp_pasv( $ftp, 1);

// In this example set the current directory to
// public_html

        ftp_chdir($ftp,"/public_html/");

// If we cannot set our directory to the new one
// then we create it

        if(!ftp_chdir($ftp,$dir))
        {   
            ftp_mkdir($ftp,$dir);
            echo("Directory $dir created ok");
        }
    }
    ftp_close($ftp);
}


?>








mathiaus: Please use CODE tags!
manav
The File Transfer Protocol (FTP) is widely used to transfer files across networks. Utilising it in a PHP script allows you to increase the level of sophistication of your PHP scripts as well as learn more about how FTP works.
The FTP extension needs no additional libraries to make it work, but you must recompile PHP. To include FTP support, run the following in the PHP source directory:
./configure --enable-ftp [other options]
The --enable-ftp argument configures FTP support to be added.
When I began learning PHP I had written a small code for a simple ftp session.
It is given below
Code:

01     <?
02     $HOST=”ftp servers address”;
03     $UN=”username”;
04     $PW=”password”;
05     $DIR=”/remote/directory/”;
06     $FILE=”test.txt”;
07
08     $conn = ftp_connect($HOST);
09     if(!$conn) {
10        exit(“Could not connect to server: $HOST\n”);
11    }
12
13    if(!ftp_login($conn,$UN,$PW)) {
14        ftp_quit($conn);
15        exit(“Could not log in\n”);
16    }
17
18    ftp_chdir($conn,$DIR);
19
20    $files = ftp_nlist($conn,”.”);
21
22    for($i=0;$i<count($files);$i++) {
23        if(!ftp_get($conn,$files[$i],$files[$i],FTP_ASCII)) {
24            echo “Could not download {$files[$i]}\n”;
25        }
26    }
27
28    if(!ftp_put($conn,$DIR.$FILE,$FILE,FTP_ASCII)) {
29        echo “Could not upload $FILE\n”;
30    }
31
32    ftp_quit($conn);
33    ?>

Explanation
Lines 02 through 06 define some parameters that will be specific to your setup. Set $HOST to an FTP server to which you have access; set $UN and $PW to the username and password, respectively, for the server; set $DIR to a directory on the remote server to which you have read and write access; and set $FILE to a local file you want to upload to the remote server.

On line 08, the script attempts to connect to $HOST — if it cannot, it fails out. On line 13, the script sends the username and password information required to authenticate access with the server. If the username and/or password are incorrect — or if there is an error — we exit from the script, informing the user. The script also tidies up after itself, closing the FTP session using ftp_quit().

If all goes well, on line 18 the script changes to the remote directory $DIR. On line 20, we retrieve a list of files in $DIR using the ftp_nlist() function. This function returns an array of files names. On lines 22 through 26, the script loops through the files, retrieving each (line 23) using ftp_get(). The second argument to ftp_get() specifies the local filename to which the remote file will be downloaded. The third argument specifies the remote file in which we are interested.

Finally, the fourth argument is the mode in which to download the file. There are two modes: FTP_ASCII for ASCII or text files; and FTP_BINARY for files in binary format, such as images or executables. Generally speaking, the mode that is chosen only matters if the client, server or both are not UNIX systems. The script uses FTP_ASCII. If any error is encountered when trying to download a file, the script notifies the user. On line 28, the script attempts to upload $FILE to the remote server using ftp_put(). The second argument specifies the remote file name, while the third specifies the local filename. As with ftp_get(), the fourth argument is the mode in which to transfer the file. If an error is encountered, the script tells the user.

The FTP session is closed on line 32 using ftp_quit().
[/b]
Related topics
req: PHP to list files in directory, and link to them
Great php editor
My website, my PHP FTP client
Creating a FTP directory using PHP
Yararlý Siteler
how connect to ftp ?
Does frihost live up to your expectations?
[Help]Montar servidores
php script to set up ftp users on linux
FTP en PHP
PHP script to create email addresses/ftp accounts/etc...
PHP that creates subdomain, ftp account, and mysql database?
Send large files across host
Direct Download to server
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.