Php select file from server

Скачивание файла с сервера через PHP

У меня есть папка на сервере, в которую загружаются файлы с сайта. Мне нужно сделать так, чтобы когда пользователь нажимает на ссылку, файл скачивался в загрузки. Список файлов находится в базе данных, посему оттуда берется название файла. Нашла код, попробовала переделать его под себя. При обновлении страницы и удалении get-параметра скачивается файл с кодом, при простом открытии страницы скачивается файл. Просто файл. Файл без названия и расширения (:

Не мега хорошо разбираюсь в php, так что могут быть очень дурацкие ошибки. Этот код для меня как дремучий лес, в нем я слабо разобралась.

 $file_extension = strtolower(substr(strrchr($file,"."),1)); switch ($file_extension) < case "pdf": $ctype="application/pdf"; break; case "exe": $ctype="application/octet-stream"; break; case "zip": $ctype="application/zip"; break; case "rar": $ctype="application/rar"; break; case "7z": $ctype="application/7z"; break; case "doc": $ctype="application/msword"; break; case "xls": $ctype="application/vnd.ms-excel"; break; case "ppt": $ctype="application/vnd.ms-powerpoint"; break; case "gif": $ctype="image/gif"; break; case "png": $ctype="image/png"; break; case "jpe": case "jpeg": case "jpg": $ctype="image/jpg"; break; default: $ctype="application/force-download"; >// сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт если этого не сделать файл будет читаться в память полностью! if (ob_get_level()) < ob_end_clean(); >header('Content-Description: File Transfer'); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: $ctype"); header('Content-Disposition: attachment; filename=' . basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); set_time_limit(0); @readfile($file) or die("File not found."); exit; ?>    ?>
Прикрепленный
файл
">
function file_force_download($file) < if (file_exists($file)) < // сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт // если этого не сделать файл будет читаться в память полностью! if (ob_get_level()) < ob_end_clean(); >// заставляем браузер показать окно сохранения файла header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); // читаем файл и отправляем его пользователю if ($fd = fopen($file, 'rb')) < while (!feof($fd)) < print fread($fd, 1024); >fclose($fd); > exit; > >

Источник

Читайте также:  Html footer example code

Php choose file from server with ajax

Solution 1: populate the select option values with folder dirs: jQuery: Php: I did not tested it there could be some spelling mistakes but this should do the trick Solution 2: get directory-paths using methods discussed here —> Using scandir() to find folders in a directory (PHP) Collect strin(paths) of child dir/files and construct next level of Solution 3: Make your AJAX request via JQuery on change of the first select with a container appended in the selector, like this: Setup your receiving AJAX page like this: Your AJAX call can now return your dynamic select box. Solution: you can’t upload a file using this javascript syntax use the jquery ajax form to submit forms with file elements in it.

Populate select from server directory PHP jQuery AJAX

populate the select option values with folder dirs:

// Use live. Because the other selects will be filled with jquery. $("select").live("change", function() < var folder = $(this).val(); var select_id = $(this).attr("name").replace('folder', ''); $.ajax(< url: 'ajax.php', type: "POST", data: , success: function(data) < var select = $(""); select_id++; select.attr("name", "folder"+select_id).append(data); $(".selects").append(select); > >); >); 

I did not tested it there could be some spelling mistakes but this should do the trick

get directory-paths using methods discussed here —> Using scandir() to find folders in a directory (PHP)

Collect strin(paths) of child dir/files and construct next level of

  1. Make your AJAX request via JQuery on select change of the first select with a container appended in the selector, like this: $(‘ajax_process.php #select_a’).post()
  2. Setup your receiving AJAX page like this:
//"; > $select .= ""; //now $select contains your HTML code for your select box. ?> //break out of php, then: 

PHP File Upload, Without the requirements above, the file upload will not work. Other things to notice: The type=»file» attribute of the tag shows the input field as a file …

Upload file to server through AJAX [duplicate]

you can’t upload a file using this javascript syntax

use the jquery ajax form to submit forms with file elements in it. also ensure the form has a enctype=multipart/form-data

To get ajax form to work first you setup your html form

Then you can have the jquery code attached to the form submit event by simply doing

$('#myform').ajaxForm(); //you can pass the same options as you would pass to $.ajax(); 

Jquery — Get response from PHP file using AJAX, in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this: $.ajax ( < type: "POST", url: …

Receiving file(s) via AJAX in server-side PHP

The append is never reached because you are grabbing only a single value from the input with .prop(‘files’)[0] . So, files.length is undefined in your loop. You should be grabbing the entire array of files:

var files = $('input[type=file]').prop('files'); //File list 

Jquery — How to ajax call a php file hosted on remote, This is because your PHP script is hosted on a different server and your AJAX call code is on local. For AJAX to run, there is same-origin policy. …

Where should I host php file for ajax call?

It needs to be on a webserver. It doesn’t work like HTML where you can just place the file where ever and have it run correctly. Download and install WAMP, then run WAMP and place your code in the WWW directory. (if you are on windows, if not — look into LAMP). It stands for Windows/Linux, Apache, MySQL, and PHP. Apache will be your webserver. There are tons of installation guides online. I am not sure which one will work best for you.

If you have a file called test.php in that folder. you will just go to localhost/test.php or 127.0.0.1/test.php

Sorry for the Wamp referral I just saw that you are on linux .

Where should I host php file for ajax call?, The PHP script must be executed and its output must be sent to the browser. Now, you don’t need a webserver to execute a PHP file, but you need it to make it (or …

Источник

Php code for downloading a file from server

See Selecting table data with PDO statements User HTML and CSS to design the user interface. So you need to first retrieve the saved data (user info and folder path to the cv) from database table.

How to download a file from server, using PHP Code

You can use Curl to download file from web using php

function curl_get_file_contents($URL)

pass url to this function and download contents. alternatively you can use file reader/writer

private function downloadFile ($url, $path) < $newfname = $path; $file = fopen ($url, "rb"); if ($file) < $newf = fopen ($newfname, "wb"); if ($newf) while(!feof($file)) < fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 ); >> if ($file) < fclose($file); >if ($newf) < fclose($newf); >> 

from : This stack question

How to Download a File in PHP, Also, you can notice, that the urlencode() function is applied for encoding the image file names in a way that they may be safely passed like a URL parameter. The reason is that file names may include unsafe URL characters. The entire code of the download.php, forcing image download looks as follows:

How to retrieve files from server folder using PHP and display/download it on a webpage using javascript?

Its very broad so i will try to brief.

Here is the steps you could follow

  1. As you said you have already created uploading and inserting components and it works. So i will leave that part and go directly to the next step. What you want to achieve is show the saved data along with the uploaded file.
  2. So you need to first retrieve the saved data (user info and folder path to the cv) from database table. To do this use PDO or mysqli with php. User Select query to select matching content from database table. See Selecting table data with PDO statements
  3. User HTML and CSS to design the user interface. Show the fetched data to the design through php. including the download link to the pdf file. i will show an example of php download file below. see how to make pdf file downloadable in html link?

Link to the pdf download could be like this

download.php could be like this

header("Content-Type: application/octet-stream"); $file = $_GET["file"] .".pdf"; header("Content-Disposition: attachment; filename=" . urlencode($file)); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($file)); flush(); // this doesn't really matter. $fp = fopen($file, "r"); while (!feof($fp)) < echo fread($fp, 65536); flush(); // this is essential for large downloads >fclose($fp); 

Php — send a file to client, I want to write a text file in the server through Php, and have the client to download that file. How would i do that? Essentially the client should be able to download the file from the server. Stack Overflow. About; Products For Teams; Stack Overflow Public questions & answers; Stack Overflow for Teams Where developers & …

Downloading files from server

I’ve had the same problem that you are having, and my solution was the next:

1º Download all data you need 2º Download to the computer the image web direction 3º Execute an asynctask per Image to download it and update your Activity while is needed

Maybe i’m not so exact and i would need some more details to give a better solution.

File — PHP download from remote server via sftp, Update: I was kindly corrected that this doesn’t use sftp, but instead uses ftps. Here’s a Stackoverflow link discussing using PHP to do SFTP.. The PHP docs already cover most of what you should need for this. Here’s an example for fetching a list of the contents in the remote directory:

Download files from ftp server in PHP

 else < echo "There was a problem\n"; >// close the connection ftp_close($conn_id); ?> 
true == ( $data = @ file_get_contents('ftp://username:password@server_name/folder_name/xyz#123.csv') ) ? file_put_contents('xyz#123.csv', $data) : exit; 
$output = exec("wget -N ftp://username@ftp.server.com/path/to directory/file 2>&1 |grep 'filename w/o extension'|grep -v ftp|grep -v ="); print $output

How to retrieve files from server folder using PHP and, When the user passes filename or a specific id, to download.php, its a job of download.php to find that specific file.its the safe way, else you could provide user with direct path to file in the link and when the user clicks the link the whole link to be sent to download.php –

Источник

Download a file from the URL in PHP

In this post, I will try to explain to you how you can download any file by its URL with the help of PHP. You can do it in many ways but in this tutorial, I will explain to you a few tricks.

First Method

We will use file_get_contents() a built-in function of PHP. This function is similar to file() the only difference is file_get_contents() returns the file in a string. This function uses memory mapping techniques and it is a preferred way to read file content.

file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string

The function returns the read data or FALSE on failure.

The above function will save the file on the same path where you run the script of PHP. If you want to download the file in your desired location then you need to set some headers. That is why I write a function given below that you can use to save file form URL into your local system.

The usage of the above function is given below.

Second Method.

In this method, I will show you how you can download a file with the helo of CURL another built-in function of PHP. If you use the below function you can save the file directly into your system by giving your desired location.

The usage of the above function is given below.

$urlPdf = 'http://www.africau.edu/images/default/sample.pdf'; dfCurl($urlPdf);

You can use any above function to download the file into your system or into your server.

Источник

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