Fetch the variable value by using ajax without post get method - php

here I have a shortcode that coontains input file type which I want to load a php file on .blur function.
// Where the input file is embedded
<input class="vh-radio-toggle" id="toggle8" type="radio" name="toggle" />
<label class="accordion-label" for="toggle8">I have an inspiration neon sign.</label>
<section id="content8">
<label for="avatar">Send your inspirational custom neon logo image here:</label>
<?php echo do_shortcode('[neon-inspire]');?>
</section>
Here is the input file html. I just made it in shortcode.
function misha_uploader_callback(){
return '<input type="file" accept="image/png, image/jpeg" name="profilepicture" size="25" />
<input type="text" name="neon_inspi" value="' . echo $neonInspi; .'">';
}
Here's my jquery ajax function.
jQuery("#neon-inspi").blur(function() {
var url = "http://localhost/neonew/wp-content/themes/twentytwenty/process_upload.php";
jQuery.post(url, {} , function(data) {
// The data here represents the answer from the server
console.log("Data Loaded: " + data);
});
});
Here's my process_upload.php. I want to load this php file by the .blur function . And I want to get the
$neonInspi value to return to my input field below the input file html
<?php
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
// $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2017/05, for multisite works good as well
// $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file
$i = 1; // number of tries when the file with the same name is already exists
$profilepicture = $_FILES['profilepicture'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
if( empty( $profilepicture ) )
die( 'File is not selected.' );
if( $profilepicture['error'] )
die( $profilepicture['error'] );
if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
'post_content' => '',
'post_status' => 'inherit'
), $new_file_path );
// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
// Show the uploaded file in browser
// wp_redirect( $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ) );
$neonInspi = $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ) ;
}

Related

List contents of a directory in HTML form dropdown and button to move selected file into a different directory

I am trying do two things.
Build a HTML form dropdown that lists the files in a specific directory.
On submit of a selected file from the dropdown list move the selected file from its current location to a new directory.
So far I have the following HTML/PHP for the dropdown:
</div>
<div class="u-form u-form-1">
<form action="end.php" method="POST" class="u-clearfix u-form-spacing-25 u-form-vertical u-inner-form" source="email" name="End" style="padding: 10px;">
<div class="u-form-group u-form-select u-form-group-1">
<label for="select-7512" class="u-custom-font u-heading-font u-label u-label-1">Select File</label>
<div class="u-form-select-wrapper">
<select id="select-7512" name="end" class="u-border-1 u-border-custom-color-1 u-custom-font u-heading-font u-input u-input-rectangle u-radius-50 u-white u-input-1" required="required">
<?php
$path = "/usr/local/data/";
$show = array( '.conf' );
$file_matcher = realpath(dirname(__FILE__)) . '/usr/local/data/*.{conf}';
foreach( glob($file_matcher, GLOB_BRACE) as $file ) {
$file_name = basename($file);
$select .= "<option value='$file'>$file_name</option>\n";
}
echo "$select";
?>
</select>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1" class="u-caret"><path fill="currentColor" d="M4 8L0 4h8z"></path></svg>
</div>
</div>
<div class="u-align-left u-form-group u-form-submit">
<a href="#" class="u-btn u-btn-round u-btn-submit u-button-style u-custom-color-2 u-custom-font u-heading-font u-radius-50 u-btn-1">End<br>
This is getting me a dropdown menu but it does not list any of the files in the /usr/local/data/ directory. I have checked and the permissions to this directory are okay. I believe my code must be wrong.
Once a file has been selected from the dropdown list I would like the submit button to run a PHP script that will move the selected file from its current dir /usr/local/data/ to /usr/local/archive/ maintaining its filename. I am not so familiar with PHP so I believe my script is probably majorly wrong here but I was building something like this:
<?php
$filePath = '/usr/local/data/';
$destinationFilePath = '/isr/local/archive/';
rename($source_file, $destination_path . pathinfo($source_file, PATHINFO_BASENAME));
}
else {
echo "The file has been moved";
}
?>
Apologies in advance for any glaring problems but could someone please help me as to where I am going wrong with both steps here. Thanks for any guidance!
UPDATE
<?php
# the pattern for file matching by file extension
$pttn='#(\.conf)$#i';
# the folder to scan /path/to/directory ~ ie: /usr/local/data/
$path="/usr/local/data/";
# find the files using glob and file match using preg_grep
$files=preg_grep( $pttn, glob( $path . '/*.*' ) );
# process file found that match the pattern and build the select menu
echo '<select name="end">';
foreach( $files as $filepath )printf('<option value="%s">%s', realpath( $filepath ), pathinfo( basename( $filepath ),PATHINFO_FILENAME) );
echo '</select>
<!--
handle the user selection from dropdown menu...
-->
<script>
document.querySelector("select[name='end']").addEventListener("change",function(e){
if( this.options.selectedIndex > 0 ){
let fd=new FormData();
fd.set("filepath", this.value );
fetch( "archivefile.php", { method:"post", body:fd } )
.then( r=>r.text() )
.then( text=>{
this.removeChild( this.options[ this.options.selectedIndex ] );
alert( text )
})
}
})
</script>';
file archive script
<?php
if( isset( $_POST['filepath'] ) ){
$source = realpath( $_POST['filepath'] );
$targetdir = sprintf( '%s/usr/local/archive', __DIR__ );
$destination = sprintf( '%s/%s', $targetdir, basename( $source ) );
if( !file_exists( $targetdir ) )mkdir( $targetdir, 0777, true );
clearstatcache();
if( $source && file_exists( $source ) ){
$status=rename( $source, $destination );
}
clearstatcache();
exit( $status ? 'Success ' : 'Failure.' );
}
?>
The filepath you cite in the question is a *nix type path and I have no means by which to test this script as it is written on a windoze system so the path variable might need tweaking?!
The following scans the current working directory ( __DIR__ ) and lists the .conf or .config files found therein - should be simple enough to use your path and possibly tweak the regex pattern if you need more filetypes added.
# the pattern for file matching by file extension
$pttn='#(\.conf|\.config)$#i';
# the folder to scan /path/to/directory ~ ie: /usr/local/data/
$path=__DIR__;
# find the files using glob and file match using preg_grep
$files=preg_grep( $pttn, glob( $path . '/*.*' ) );
# process file found that match the pattern and build the select menu
echo '<select name="end">';
foreach( $files as $filepath )printf('<option value="%s">%s', realpath( $filepath ), pathinfo( basename( $filepath ),PATHINFO_FILENAME) );
echo '</select>
<!--
handle the user selection from dropdown menu...
-->
<script>
document.querySelector("select[name=\'end\']").addEventListener("change",function(e){
alert( this.value )
})
</script>';
updates
The Javascript I would modify like this so that it fires off an AJAX request to whatever backend script determined to be the upload/move handler.
document.querySelector("select[name='end']").addEventListener("change",function(e){
if( this.options.selectedIndex > 0 ){
let fd=new FormData();
fd.set("filepath", this.value );
fetch( "file-move-target.php", { method:"post", body:fd } )
.then( r=>r.text() )
.then( text=>{
this.removeChild( this.options[ this.options.selectedIndex ] );
alert( text )
})
}
})
And the endpoint to handle the file move:
<?php
if( isset( $_POST['filepath'] ) ){
$status=false;
$source = realpath( $_POST['filepath'] );
$targetdir = sprintf( '%s/usr/local/archive', '' );
$destination = sprintf( '%s/%s', $targetdir, basename( $source ) );
if( !file_exists( $targetdir ) )mkdir( $targetdir, 0777, true );
clearstatcache();
if( $source && file_exists( $source ) ){
$status=rename( $source, $destination );
}
clearstatcache();
exit( $status ? 'File moved' : 'Error: unable to move file' );
}
?>

Generate HTML file from Gravity Form Submission

How do I generate an html file (with specific styling) from a Gravity Form submission using PHP? Right now, I'm using Gravity Form with Gravity PDF to generate PDFs, but I also need these pdfs to be generated as html files. I was told that I could use a gf hook called gform_notification. Here is what I have so far:
add_filter( 'gform_notification_30', 'add_attachment_html', 10, 3 ); //target form id 2, change to your form id
function write_html($filename, $entry){
$filename = fopen( 'file_'.'rand(0, 999999)'.'.html', "w");
$text = $entry;
$path = '/public_html/wp-content/uploads/HTML/';
fwrite($path.$filename, $text);
fclose($filename); }
function add_attachment_html( $notification, $form, $entry ) {
//There is no concept of user notifications anymore, so we will need to target notifications based on other criteria,
//such as name or subject
if( $notification['name'] == 'HTML' ) {
//get upload root for WordPress
$upload = wp_upload_dir();
$upload_path = $upload['basedir'];
//add file, use full path , example -- $attachment = "C:\\xampp\\htdocs\\wpdev\\wp-content\\uploads\\test.txt"
$attachment = $upload_path . $filename;
GFCommon::log_debug( __METHOD__ . '(): file to be attached: ' . $attachment );
if ( file_exists( $attachment ) ) {
$notification['attachments'] = rgar( $notification, 'attachments', array() );
$notification['attachments'][] = $attachment;
GFCommon::log_debug( __METHOD__ . '(): file added to attachments list: ' . print_r( $notification['attachments'], 1 ) );
} else {
GFCommon::log_debug( __METHOD__ . '(): not attaching; file does not exist.' );
}
}
//return altered notification object
return $notification;
}
I'm brand new to coding so please bear with me. My biggest issue is generating the new HTML file. I think I can figure out how to attach it to the notification email (function add_attachment_html) once I get that part done.

Wordpress file upload

I have this plugin im making and in the file upload system i have this:
$mimes = array('image/jpeg','image/jpg','image/gif','image/png','application/pdf');
if(in_array($_FILES['attach']['type'], $mimes)){
$error = 0;
}
else {
$error = 1;
}
Then, along with other error checking i have this to upload the files to a custom folder
if($error == 0) {
$folder = PLUGIN_DIR . '/uploads/';
if(is_dir($folder)) {
$file = $_FILES["attach"]["tmp_name"];
move_uploaded_file($file, $folder.date('Ymd').'_'.$name);
}
}
This works perfectly. I've tested it but, is it ok to do like this? Or is there a better way to do it?
Thanks in advance!
I think better use this codex.wordpress.org
<?php
// We will check the protection of nonce and that the user can edit this post.
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// all OK! We continue.
// These files must be connected to the front end (front end).
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress catch the download.
// Do not forget to specify the attribute name field input - 'my_image_upload'
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
echo "Error loading media file.";
} else {
echo "The media file has been successfully uploaded!";
}
} else {
echo "Verification failed. Unable to load file.";
}
?>
check whether free space availability. I had the same issue I have checked every thing and done more but the issue was with my file storage

wordpress upload file error

I have this upload file system in wordpress and everything is working fine but the file wont go into the folder. Here's what i have right now:
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
// Change your upload directory
function my_upload_dir(){
return PLUGIN_DIR . '/uploads/';
}
// Register our path override.
add_filter( 'upload_dir', 'my_upload_dir' );
// Set where to get the file from
$uploadedfile = $_FILES["attach"];
$upload_overrides = array( 'test_form' => false );
// Do the file move
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
// Set everything back to normal.
remove_filter( 'upload_dir', 'my_upload_dir' );
// Return an error if it couldn't be done
if (!$movefile || isset( $movefile['error'])) {
echo $movefile['error'];
}
its seems to be working fine (no errors) but the image wont show in the folder.
any help would be appreciated.
I think This code is working Fine.
$date=strtotime(date('Y-m-d H:i:s'));
$pro_image_name = $date.$_FILES['your Input type File Name']['name'];
$allowed = array('gif','png','jpg');
$ext = pathinfo($pro_image_name, PATHINFO_EXTENSION);
$root_path = get_template_directory();
if(!in_array($ext,$allowed) ) { ?>
<span style="font-size:22px; color:red;">Uploaded File Not Supported</span>
<?php } else {
move_uploaded_file($_FILES['updateimg']['tmp_name'],$root_path."/images/".$pro_image_name);
$image_get_path = site_url()."/wp-content/themes/prathak/images/".$pro_image_name;
update_user_meta(get_current_user_id() , 'userpic' , $image_get_path );
}
Good Luck

Wordpress - upload files and rename with custom user meta

when my users upload a file, I need to rename it using a specific user_meta value. So, using wp_handle_upload I've set a callback function for $upload_overrides like this:
$upload_overrides = array( 'test_form' => false, 'unique_filename_callback' => 'change_document_name' );
and my callback function is
function change_document_name($dir, $name, $ext){
global $current_user;
$doc_type = get_user_meta($current_user->ID, 'document_type', true);
return $doc_type . '_mydoc' . $ext;
}
Now as you can see, we are talking about users documents so I need to rename them according to the document type they've uploaded. For example, if they've uploaded a "passport" and selected the document type (of course), I should get the user_meta 'document_type', use it as prefix and place it in front of the filename uploaded, outputting something like
passport_mydoc.pdf
Of course my function doesn't work and I don't understand why it doesn't take the global $current_user or at least if there is some other method to accomplish this.
Many thanks.
EDIT
To explain it better, my fault, the function change_document_name() does rename the file like so:
_mydoc.ext (e.g _mydoc.pdf)
This means that the function is correctly called and runs, except for the first part ignoring $doc_type variable. For this reason I suppose that the $current_user it's not working. My complete code to upload the file is the following:
if(!empty($_FILES['docfile'])):
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
$upload_overrides = array( 'test_form' => false, 'unique_filename_callback' => 'change_document_name' );
add_filter('upload_dir', 'my_user_folder'); //A documents custom folder
$uploaded_file = wp_handle_upload($_FILES['docfile'], $upload_overrides);
remove_filter( 'upload_dir', 'my_user_folder' );
$doc_file_loc = $uploaded_file['file'];
$doc_file_title = $_FILES['docfile']['name'];
$doc_file_arr = wp_check_filetype(basename($_FILES['docfile']['name']));
$doc_file_type = $doc_file_arr['type'];
$doc_file_att = array(
'post_mime_type' => $doc_file_type,
'post_title' => addslashes($doc_file_title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => 0,
'post_author' => $uid
);
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$doc_file_id = wp_insert_attachment( $doc_file_att, $doc_file_loc, 0 );
$doc_file_url = wp_get_attachment_url( $doc_file_id );
update_user_meta($uid,'document_file', $doc_file_url);
endif;
The hook 'unique_filename_callback' is used according to the codex here https://developer.wordpress.org/reference/functions/wp_unique_filename/
I'm not sure why the global isn't returning the user. It should be. But try get_current_user_id() and see if it works:
function change_document_name( $dir, $name, $ext ){
if ( ! is_user_logged_in() ) {
error_log( "User not logged in." );
return;
}
$user_id = get_current_user_id();
// Uncomment to see if there is any value
// var_dump( $user_id );
$doc_type = get_user_meta( $user_id, 'document_type', true );
// Uncomment to see if there is any value
// var_dump( $doc_type );
if ( ! $doc_type ) {
error_log( "There is no doc type set for the current user with id $user_id" );
return;
}
return $doc_type . '_mydoc' . $ext;
}
I have added some var_dumps in there you can use to see what values are being returned, or you can debug if you have xdebug set up. But this should give you what you need. You can also remove the error logging if you don't want to log those errors. They are there so you can check the site logs and see what is in them.

Categories