<?php
if ( get_post_meta(get_the_ID(), 'test_file', true) ) :
$GET11 = wp_get_attachment_url ( get_post_meta(get_the_ID(), 'test_file', true) );
?>
<form method="POST">
<input type="submit" value="downlode" name="test_downlode">
</form>
<?php
if ($_POST['test_downlode']){
$number_downlode = get_post_meta($postID, 'downlode_registration', true);
$number_downlode++;
update_post_meta($postID, 'downlode_registration', $number_downlode);
$file = ($GET11);
if (file_exists($file)) {
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));
readfile($file);
exit;
}
}
endif;
?>
Но она не работает для ссылок
add_action('template_redirect','pchv_ew_template_redirect');
function pchv_ew_template_redirect() {
if ($_SERVER['REQUEST_URI']=='/downloads/result.csv') {
$opt = unserialize(get_option('import_info')); // Получаум опцию
if (!$opt['resultfile']) { exit; }
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile($opt['resultfile']);
exit();
}
}
<?php
if ( get_post_meta(get_the_ID(), 'test_file', true) ) :
$GET11 = wp_get_attachment_url ( get_post_meta(get_the_ID(), 'test_file', true) );
echo $GET11 ;
?>
<form method="POST">
<input type="submit" value="downlode" name="test_downlode">
</form>
<?php
if ($_POST['test_downlode']){
add_action('template_redirect','pchv_ew_template_redirect');
function pchv_ew_template_redirect() {
if ($_SERVER['REQUEST_URI']== $GET11) {
$opt = unserialize(get_option('import_info')); // Получаум опцию
if (!$opt['resultfile']) { exit; }
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".jpg");
header("Pragma: no-cache");
header("Expires: 0");
readfile($opt['resultfile']);
exit();
}}}
endif;
?>
unserialize — Создает PHP-значение из хранимого представления
$_SERVER['REQUEST_URI'] содержит имя скрипта, начиная от корневой директории виртуального хоста
Но похоже я делаю что не так
<form method="POST">
<input type="submit" value="downlode" name="test_downlode">
</form>
add_action('template_redirect','pchv_ew_template_redirect');
function pchv_ew_template_redirect() {
if ( get_post_meta(get_the_ID(), 'test_file', true) ){
$GET11 = wp_get_attachment_url ( get_post_meta(get_the_ID(), 'test_file', true) );
if ($_POST['test_downlode']){
if ($_SERVER['REQUEST_URI']== $GET11) {
$opt = unserialize(get_option('import_info')); // Получаум опцию
if (!$opt['resultfile']) { exit; }
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".jpg");
header("Pragma: no-cache");
header("Expires: 0");
readfile($opt['resultfile']);
exit();
}}}}
$GET11 = http://localhost/wor/wp-content/uploads/2018/12/BI7GI_8-01_IL_01-k1.jpg
class="php"><?php
add_action('template_redirect','pchv_ew_template_redirect');
function pchv_ew_template_redirect() {
if ($_SERVER['REQUEST_URI']== 'BI7GI_8-01_IL_01-k1.jpg') {
$opt = unserialize(get_option('import_info')); // Получаум опцию
if (!$opt['resultfile']) { exit; }
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".jpg");
header("Pragma: no-cache");
header("Expires: 0");
readfile($opt['resultfile']);
exit();
}}
?>
error_log('$GET11: ' . print_r($GET11, true) . PHP_EOL, 3, __DIR__ . "my-errors.log" );
localhost/wor/wp-content/uploads/2018/12/BI7GI_8-0...
/wor/ru/2018/12/04/frtt/
<?php if ($_SERVER['REQUEST_URI']== $GET11)
if ($_SERVER['REQUEST_URI']== $GET11)
и нужна для того, что бы понять что сейчас обрабатывается запрос который должен вернуть файл. if ($_SERVER['REQUEST_URI']== '/wor/ru/2018/12/04/frtt/')
add_action('template_redirect','pchv_ew_template_redirect');
function pchv_ew_template_redirect() {
if ( get_post_meta(get_the_ID(), 'test_file', true) ){
$GET11 = wp_get_attachment_url ( get_post_meta(get_the_ID(), 'test_file', true) );
if ($_SERVER['REQUEST_URI']== '/wor/ru/2018/12/04/frtt/') {
$opt = unserialize(get_option('import_info')); // Получаум опцию
if (!$opt['resultfile']) { exit; }
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".jpg");
header("Pragma: no-cache");
header("Expires: 0");
readfile($opt['resultfile']);
exit();
}}}
<?php
/**
*
*
* Plugin Name: Скачивание файла по ссылке
* Plugin URI:
* Description:
* Author: Анатолий Пычев
* Version: 1.0.2
* Author URI:
*/
// код плагина
add_action('admin_menu', 'pchv_ew_add_admin_pages');
add_action('template_redirect','pchv_ew_template_redirect');
function pchv_ew_template_redirect() {
if ($_SERVER['REQUEST_URI']=='/downloads/result.csv') {
$fn = _DIR_ . '/tocsv.csv'; // Получаум опцию
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile($fn);
exit();
}
}
function pchv_ew_add_admin_pages(){
// Добавляем новую страницу настроек
$hook_suffix = add_options_page('Заголовок страницы', 'Загрузка Файлов', 8, 'pchv_upload_file', 'pchv_options_page');
}
function pchv_options_page(){
echo "<h2>Загрузка файлов по ссылке</h2>";
echo "<p>Автор плагина Анатолий Пычев (email: tpychev@ukr.net, sqype: pychevhome)</p>";
// Создаем фронтенд блока страницы настроек
$df = home_url('downloads/result.csv');
?></br><a href ="<?php echo $df ?>" id="ew-getresult" >скачать файл результатов</a></br><?php
}
?>
if ($_SERVER['REQUEST_URI']=='/wor/downloads/result.csv')
<br />
<b>Warning</b>: Use of undefined constant _DIR_ - assumed '_DIR_' (this will throw an Error in a future version of PHP) in <b>C:\xampp\htdocs\wor\wp-content\plugins\plagin downlode\index.php</b> on line <b>22</b><br />
<br />
<b>Warning</b>: readfile(_DIR_/tocsv.csv): failed to open stream: No such file or directory in <b>C:\xampp\htdocs\wor\wp-content\plugins\plagin downlode\index.php</b> on line <b>28</b><br />
function pchv_ew_template_redirect() {
if ($_SERVER['REQUEST_URI']=='/wor/downloads/result.csv') {
$fn = ' http://localhost/wor/wp-content/uploads/2018/12/BI7GI_8-01_IL_01-k1.jpg'; // Получаум опцию
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=result".date("_d.m.y_H:i:s").".jpg");
header("Pragma: no-cache");
header("Expires: 0");
readfile($fn);
exit();
}
}
get_post_meta(get_the_ID(), 'test_file', true)
//readfile($fn);
echo get_post_meta(get_the_ID(), 'test_file', true);
readfile( get_post_meta(get_the_ID(), 'test_file', true));
get_post_meta(get_the_ID(), 'test_file', true);
wp_get_attachment_url ( get_post_meta(get_the_ID(), 'test_file', true) );
Есть ли способ с помощью PHP скачать файл из базы данных wordpress?
//1 - получить id вложения и локальный путь к файлу
$atach_id = get_post_meta(get_the_ID(), 'test_file', true); // надеюсь там просто число а не массив
$local_path = get_post_meta($atach_id, '_wp_attached_file', true);
//2 - получить каталог вложений
$upload_dir = wp_upload_dir();
$basedir = $upload_dir['basedir'];
//3 - собрать путь к вложению
$fn = $basedir . '/' . $local_path;
...
// отправляем в поток
readfile($fn);
$number_downlode = get_post_meta($postID, 'downlode_registration', true);
$number_downlode++;
update_post_meta($postID, 'downlode_registration', $number_downlode);
<?php
/*
Plugin Name: File Download Counter
Plugin URI: http://александрсоболев.рф
Description: Плагин-виджет, реализующий счетчик кликов
Author: Александр Соболев
Version: 1.1
Author URI: http://александрсоболев.рф
*/
function js_includer() { wp_register_script('my_click_counter', plugins_url('js/my_click_counter.js', __FILE__)); wp_enqueue_script('my_click_counter'); wp_localize_script( 'my_click_counter', 'ajaxurl', admin_url('admin-ajax.php') );}
function register_my_counter() { register_setting( 'my_click_counter', 'counter', 'intval' ); }
function count_plus(){$all_options = get_option('my_click_counter'); $count = intval($all_options['counter']); $new_val= ++$count;update_option( 'my_click_counter', $new_val ); wp_send_json($new_val); }
function show_counter(){get_option('my_click_counter'); $count = intval($all_options['counter']); $counter_div='<div id="my_counter_accept">Тест счечика.</div><div id="my_click_counter">'.$counter_div.'</div>';return $counter_div;} add_shortcode( 'show_counter', 'show_counter' );
add_action( 'admin_enqueue_scripts', 'js_includer' ); add_action( 'wp_enqueue_scripts', 'js_includer' ); add_action( 'admin_init', 'register_my_counter' ); add_action( 'wp_ajax_count_plus','count_plus' ); add_action( 'wp_ajax_nopriv_count_plus','count_plus' );
?>
jQuery(document).ready(function(){
jQuery('#my_counter_accept').on('click',function(){
jQuery.ajax({ type: "POST", url: ajaxurl, dataType: 'json', data: { action: 'count_plus'}, beforeSend: function(){jQuery('.класс ссылки').remove(); }, success: function(new_val) { console.log('Файл скачен '+new_val+' раз'); } });
})
});