Html upload file to ftp

Upload files directly to the FTP server by using «Jquery file upload plugin»

I am using the «Blueimp Jquery file upload plugin» on my website, and I give a permission to users to can uploading files on my sever. I hosted my website on HostGator. The problem is that users cannot upload files’ size more than 64MB/file, and after searching I found that HostGator has setting this limit of the uploading files to 64MB/file as a maximum in the «php.ini» file, and I cannot change this size limit. But actually I can upload any size of files without any limits directly via the FTP. So, am asking about if there is a workaround that I can use to avoid this HostGator Limits, or if there is way to allow users uploading the files directly to the server via FTP throw this jquery plugin «web application».

3 Answers 3

You definitely can change hostgator’s max file size settings, as I’ve done it before several times.

In the directory of your choosing, create a .htaccess file. In this file include php overwrite settings.

php_value upload_max_filesize 200M php_value post_max_size 200M 

Unless something has changed in the last few months, this workaround has always worked for me.

Thanks for your prompt reply, but this solution doesn’t work with me, I just added this code in a .htaccess file in the uploads folder directly»I don’t know if that right or not», also I want to ask how to include php overwrite settings «I cannot understand» ?? Kindly explain more 😀

Читайте также:  Код таймера обратного отсчета html код

jupload can upload via ftp

this is an ok solution imo. While not all users enable java, you can make your html page degrade gracefully to http upload, in which case the only users who lose are those who want to upload large files.

or switch webhosts- another easy and effective solution.

You CAN use FTP with the «Blueimp Jquery file upload plugin» but it requires some PHP coding. Don’t hack up the UploadHandler class (file-uploads/server/php/UploadHandler.php), instead you should extend it and override the functions as needed.

Replace the contents of file-uploads/server/php/index.php with the following:

require('UploadHandler.php'); /* * custom class for uploading files, simply extends the UploadHander class */ class CustomUploadHandler extends UploadHandler < /* * rewreite the handle_file_upload() function to use FTP to send the files to the FTP server */ protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null, $content_range = null) < $file = new stdClass(); $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error, $index, $content_range); $file->size = $this->fix_integer_overflow((int)$size); $file->type = $type; if ($this->validate($uploaded_file, $file, $error, $index)) < $this->handle_form_data($file, $index); $upload_dir = $this->get_upload_path(); if (!is_dir($upload_dir)) < mkdir($upload_dir, $this->options['mkdir_mode'], true); > $file_path = $this->get_upload_path($file->name); $append_file = $content_range && is_file($file_path) && $file->size > $this->get_file_size($file_path); if ($uploaded_file && is_uploaded_file($uploaded_file)) < // multipart/formdata uploads (POST method uploads) if ($append_file) < file_put_contents( $file_path, fopen($uploaded_file, 'r'), FILE_APPEND ); >else < move_uploaded_file($uploaded_file, $file_path); >> else < // Non-multipart uploads (PUT method support) file_put_contents( $file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0 ); >$file_size = $this->get_file_size($file_path, $append_file); if ($file_size === $file->size) < $file->url = $this->get_download_url($file->name); if ($this->is_valid_image_file($file_path)) < $this->handle_image_file($file_path, $file); > > else < $file->size = $file_size; if (!$content_range && $this->options['discard_aborted_uploads']) < unlink($file_path); $file->error = $this->get_error_message('abort'); > > $this->set_additional_file_properties($file); > /* * now send it to the FTPserver */ $source_file = $file_path; // the path of the file to upload $destination_file = '/your/path/' . $file->name; // the file path to upload to (must have trailing / in the path before the $file->name is appended) $ftp_error = $this->ftp_upload($source_file, $destination_file); if ($ftp_error != '') < $file->error = $ftp_error; > return $file; > /* * new function for uploading using FTP */ protected function ftp_upload($source_file, $destination_file) < $ftp_server = 'YOUR FTP HOST NAME'; $ftp_user_name = 'YOUR USER NAME'; $ftp_user_pass = 'YOUR PASSWORD'; $port_number = YOUR FTP PORT NUMBER; $error = ''; // set up basic connection $conn_id = ftp_connect($ftp_server, $port_number); if (!$conn_id) < $error = "FTP connection has failed! Connection attempt was blocked." ; return $error; >// login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // check connection if (!$login_result) < $error = "FTP connection has failed! "; $error .= "Could not log into fpt://$ftp_server for user $ftp_user_name"; return $error; >// upload the file $upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); // check upload status if (!$upload) < $error = "FTP upload has failed!"; >else < $error = "Uploaded $source_file to $ftp_server as $destination_file"; >// close the FTP stream ftp_close($conn_id); return $error; > > // options to pass to the upload handler object $options = [ // ANY OPTIONS, SUCH AS FILE UPLOAD LOCATION 'upload_url' => 'fpt://YOUR-FTP-SERVER-NAME/files/', ]; // finally, instantiate the new class $upload_handler = new CustomUploadHandler($options); 

Note that this merely copies the file, via ftp, to the ftp server after it has been uploaded to the upload server. This means you’ll have two copies of the same file. You could delete the originally uploaded file without too much extra work, but make sure that the ftp operation has completed first.

You’ll need this AND you’ll need the .htaccess apache setting as described by Ohgodwhy

Источник

Загрузка файлов на FTP-сервер с помощью PHP (для новичков)

Для того чтобы загрузить файл на FTP-сервер, вам нужна HTML форма, где можно разместить такие детали FTP-соединения, как те, что описаны ниже:

  • server – сервер, на который вы хотите загрузить файл;
  • username – имя пользователя, под которым происходит соединение с FTP сервером;
  • password – пароль пользователя для доступа к FTP-серверу;
  • path to server – путь к FTP-серверу, на который вы хотите загрузить свой файл;
  • user file – файл, который вы собираетесь загрузить на FTP-сервер.

Подсказка : если вы хотите предложить пользователям вашего веб-сайта форму, куда они смогут загружать свои файлы, вы должны взять информацию о FTP-сервере и путь к нему из файла конфигурации. В этой статье мы демонстрируем подробный пример того, как загружать файлы через FTP, со всеми деталями.

У нас будет POST форма и атрибут enctype со значением multipart/form-data , потому что на нашей форме есть файл. Пользовательская форма, в которую нужно будет заносить информацию, выглядит так:

  
Current server: Username: Password: Path on the Server: Select File to Upload:

Когда пользователь отправляет форму, мы должны собрать всю информацию, которую пользователь занес в форму, и затем загрузить файл на FTP-сервер:

//имя файла, который нужно загрузить $filep = $_FILES['userfile']['tmp_name']; $ftp_server = $_POST['server']; $ftp_user_name = $_POST['user']; $ftp_user_pass = $_POST['password']; $paths = $_POST['pathserver']; //имя файла на сервере после того, как вы его загрузите $name = $_FILES['userfile']['name'];

Чтобы загрузить файл, мы должны, прежде всего, установить подключение к FTP-серверу с помощью функции ftp_connect , задав в качестве параметра адрес FTP-сервера. Функция возвращает идентификатор соединения:

$conn_id = ftp_connect($ftp_server);

После соединения с сервером мы должны войти в учетную запись, используя функцию ftp_login , имеющую три входных параметра: идентификатор соединения, имя пользователя на FTP, пароль пользователя. Также нужно проверить, был ли вход осуществлен удачно:

// входим при помощи логина и пароля $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // проверяем подключение if ((!$conn_id) || (!$login_result)) < echo "FTP connection has failed!"; echo "Attempted to connect to $ftp_server for user: $ftp_user_name"; exit; >else

После авторизации мы можем загрузить файл на сервер, а затем проверить, был ли он загружен корректно:

// загружаем файл $upload = ftp_put($conn_id, ‘public_html/’.$paths.’/’.$name, $filep, FTP_BINARY); // проверяем статус загрузки if (!$upload) < echo "Error: FTP upload has failed!"; >else

Для закрытия FTP-соединения мы используем функцию ftp_close , принимающую в качестве параметра идентификатор соединения:

Для загрузки больших файлов необходимо установить для сервера ограничение по времени, чтобы не завершить скрипт, пока выполняется загрузка:

Источник

Saving page as .html and upload to ftp

I allow myself to ask the question here cause I looked for what to do regarding my problem but didn’t find anything helpful. Im having a webpage where users can modify information such as text, images etc, and I would like to add a button which would save the page as an .html in its current state (reloading the pas reset everything) and upload it on a ftp so they could have access to it online. At this point, I know how to get all the html content using js .innerHTML, and how to send a file to the ftp using php, but I don’t know what to look for to generate the .html file with the innerHTML content in it. So here I am, asking for your help to guide me toward the right direction. Thanks a lot! Following theCNG27’s suggestion, I think now the issue comes from my php script.. Sorry about that but Im really not used to php yet. here is the php script:

2 Answers 2

So you have Text (in your case the HTML code) in your javascript that you want to transfer to your php script and save it as a file!? Is that correct? If so, I would recommend this:

Since javascript is client-side and php is server-side you should send by POST. I would use a form like this:

Now in the js-script you have to update the value of your hidden input like this:

document.getElementById("htmlsubmit").value = htmlcode; 

htmlcode represents your HTML code you got through .innerHTML

Now in your PHP script you just have to receive the code and write it to a file:

$handle = fopen("filename.html", "w+"); fwrite($handle, $_POST['HTML']); 

Since you already know how to upload a file to ftp via php, just do that with your file «filename.html» 😉

EDIT: You edited your question and said you need help with the php script. This would be a possible complete script you could use:

Is that all you need in your script?

Источник

Upload image into FTP through HTML form

What is your real question exactly? You want a script that uploads your image? That’s not really what SO is for i guess.

I want it to upload into my FTP images folder. The code I have above «images/$filename» does not goes into the folder

1 Answer 1

Here is how you will check extension:

if(is_uploaded_file($_FILES['imgfile']['tmp_name'])) < $fileExtension = array('jpg','jpeg','gif','png'); $file_name = pathinfo($_FILES["imgfile"]["name"]); $extension = strtolower($file_name['extension']); if(!in_array($extension, $fileExtension)) < $error .= "invalid file format !
"; > >

And here is how you will upload if no errors are found:

$tmp_file = ''; if(is_uploaded_file($_FILES['imgfile']['tmp_name'])) < $file_name = pathinfo($_FILES["imgfile"]["name"]); $extension = strtolower($file_name['extension']); $tmp_file = substr($file_name['filename'], 0, 50).'_'.time().'.'.$extension; $uploaddir = 'user_image/'; $uploadfile = $uploaddir.$tmp_file; move_uploaded_file($_FILES['imgfile']['tmp_name'], $uploadfile); //list($width, $height) = getimagesize($uploadfile); $fileType = $_FILES['imgfile']['type']; $fileSize = $_FILES['imgfile']['size']; >

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Uploading an image to ftp from HTML input

I’m trying to store images on an FTP server to be used on other pages, but I’m getting multiple errors trying to get this work. Running everything on XAMPP. First I use input on an html page:

$image = $_POST["image"]; $ftpCon = ftp_connect("127.0.0.1", "21") or die("Could not connect to FTP"); ftp_fput($ftpCon, "image.png", $image, FTP_BINARY); ftp_close($ftpCon); 

2 Answers 2

$image = $_FILES['image']['tmp_name']; 

When you upload items (files) via a form it’s populated in the $_FILES superglobal.

An associative array of items uploaded to the current script via the HTTP POST method.

Make sure you also set the form with enctype=’multipart/form-data’

So the first line of the PHP has to be changed to:

$image = $_FILES['image']['tmp_name']; 

The $_FILES is associtaive and contains the following data:

(userfile = image, in your case)

$_FILES['userfile']['name'] The original name of the file on the client machine. $_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted. $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload. This element was added in PHP 4.2.0 

Источник

Оцените статью