I'm trying to use the dropzone JS plugin, and PHP to upload multiple files and then output each file url.
I have this so far:
$upload_dir = 'files';
for($i=0; $i<count($_FILES['file']['tmp_name']); $i++) {
$tempFile = $_FILES['file']['tmp_name'][$i];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$mainFile = $uploadPath.time().'-'. $_FILES['file']['name'][$i];
$mainFile_short = time().'-'. $_FILES['file']['name'][$i];
if(move_uploaded_file($tempFile,$mainFile)) {
}
}
I can't seem to make this work though, I'm not sure where I'm going wrong. Any ideas would be great!
$img = $_FILES['file'];
$upload_dir = 'files';
if(!empty($img))
{
$img_desc = reArrayFiles($img);
print_r($img_desc);
foreach($img_desc as $val)
{
$tempFile = $val['tmp_name'];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$mainFile = $uploadPath.time().'-'. $val['name'];
$mainFile_short = time().'-'. $val['name'];
if(move_uploaded_file($tempFile,$mainFile)) {
}
}
}
Related
I have finally managed to combine all my WordPress Javascript from my theme and plugins into a single bundle using the function below:
function merge_all_scripts() {
global $wp_scripts;
$wp_scripts -> all_deps($wp_scripts -> queue);
$merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'merged-script.js';
$merged_script = '';
foreach( $wp_scripts->to_do as $handle) {
$src = strtok($wp_scripts->registered[$handle]->src, '?');
if (strpos($src, 'http') !== false) {
$site_url = site_url();
if (strpos($src, $site_url) !== false) $js_file_path = str_replace($site_url, '', $src);
else $js_file_path = $src;
$js_file_path = ltrim($js_file_path, '/');
} else {
$js_file_path = ltrim($src, '/');
}
if (file_exists($js_file_path)) {
$localize = '';
if (#key_exists('data', $wp_scripts->registered[$handle]->extra)) {
$localize = $obj->extra['data'] . ';';
}
$merged_script .= $localize . file_get_contents($js_file_path) . ';';
}
}
file_put_contents ( $merged_file_location , $merged_script);
wp_enqueue_script('merged-script', get_stylesheet_directory_uri() . '/merged-script.js', array(), '1.0', false );
foreach( $wp_scripts->to_do as $handle ) {
wp_deregister_script($handle);
}
}
add_action( 'wp_enqueue_scripts', 'merge_all_scripts', 99 );
Problem is it erases all inline woocommerce js defined in the "get_script_data" woocommerce function. I want it to include that aswell.
Otherwise content such as this will not get injected into the DOM, and therefore prevent the site from working properly:
var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","wc_ajax_url":"\/?wc-ajax=%%endpoint%%","i18n_view_cart":"Se kurv","cart_url":"https:\/\/lawrence.dk\/bag\/","is_cart":"","cart_redirect_after_add":"no"};
I have a canvas which I need to save to a directory and store the URL in a database.
When I save the file without storing the URL in the database it works fine, and vice versa.
However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?
When I try to call the "success" on AJAX, nothing shows up. I get no response.
This could possibly be an easy fix! I think I've been staring at this code for too long.
JavaScript:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'doodleupload.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
PHP:
<?php
session_start();
/* AUTOMATED VARIABLES */
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$upload_dir = "images/external/doodles/";
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
require_once 'php/connect.php';
try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "File in database";
}
else
{
echo "Not in database";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Move $upload_dir at the top, as you are calling it before you initialize it.
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
i try use the media manager from wordpress i use the post editor outside admin wordpress and users can create a posts whit a featured image.
I use _wp_post_thumbnail_html function to show image or show link to upload file, all users whit a rol "publisher" can upload images and upload work but doesn't work show featured image or assign to post.
on wp-ajax whit action: set-post-thumbnail returns 0 and image aren't assign to new post.
wp-ajax.php:
json:true thumbnail_id:3952
_wpnonce:b02e8553f1 action:set-post-thumbnail
response: 0
My code as:
<?php $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
//$postid = get_post( $post_id );
echo _wp_post_thumbnail_html( $thumbnail_id, $post_id );
?>
<br>
Very simple, show the media manager from wordpres, allow upload featured image but not allow assign to new post. Any solution?
edit: in edit post works fine allow change featured image i suppose because featured image required a post id, but on new post from wordpress allow upload image and asign this to new post.
This is proper image-uploading code.
<?php
global $wpdb;
include ('../../../../wp-load.php');
if ( $_FILES ) {
if(!function_exists('wp_handle_upload')){
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$upload_overrides = array('test_form' => false);
$response = array();
ini_set('max_execution_time', 0);
foreach($_FILES as $file){
$movefile_profile = wp_handle_upload($file, $upload_overrides);
$filename = $movefile_profile['url'];
$parent_post_id = $post_id; // please provide post id must
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
$filepath = $wp_upload_dir['path'] . '/' . basename( $filename );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail($post_id, $attach_id); // this set_post_thumbnail will set you post thumbnail
$response['message'] = 'Done';
}
echo json_encode($response);
die();
}
And for Ajax code, go to this link. If you any problems, then please comment below.
I want to rename a file uploaded with dropzone.js. I have read the other question of rename file with dropzone, but I don't understand.
I've tried this:
this.on("sending", function(file, xhr, formData) {
var abdocument.getElementById("a").value
var nick = document.getElementById("b").value;
formData.append("fileName", a+ " - " + b);
});
}
};
but then how can I use this "fileName"? I've to use in php function? This is mine:
<?php
$upload_folder = 'uploads';
if (!empty($_FILES)) {
$temp_file = $_FILES['file']['tmp_name'];
$target_path = dirname( __FILE__ ) . '/' . $upload_folder . '/';
$target_file = $target_path . $_FILES['file']['name'];
if( file_exists( $target_path ) ) {
move_uploaded_file($temp_file, $target_file);
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
}
?>
or can I rename via javascript?
Thanks to all
Ok, I have to do this:
$_FILES['file']['name'] = ($_POST["fileName"]);
simply set it at $_FILE superglobal as follow:
$_FILES['file']['name']="your_new_file_name";
I am attempting to use JSONP to return an array from PHP to JavaScript. Hopefully, my code will demonstrate exactly what I'm trying to do because I am not even so sure how to word it...
My PHP file, port 80, hence the need to use JSONP and not JSON (I tried already)
I am not sure if I am forming the $_GET variables correctly either, I'm pretty certain it's wrong though and my lack of knowledge is the reason for this...
<?php
$directory = './thumbnails/';
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file;
$nofiles++;
}
}
//$i = rand(0, 3);
//$output = "{";
for($i=0; $i < 3; $i++){
$json[i] = json_encode($thumbs[$i]);
$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
//$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}
//$output = $output . "}";
//echo $_GET['thumbnails'] ."(".$json.")";
echo $output;
?>
Then in JavaScript on port 8080 (cross-domain and yes it worked fine until I tried to use this array as opposed to just passing one image url) I want to get each image url from the PHP array so that I can make icons using the image..
function makeThumbs(data, layer){
var icon = new OpenLayers.Icon(data);
layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
for(var m = 0; m < layer.markers.length; m++){
layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
$("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
}
}
$.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails2=?', function(data) {makeThumbs(data, markers);});
again the url I am passing to the $.getJSON method is also probably wrong. I need to know how to select the exact photo url from the array being passed, not all the JSONP data.
I appreciate your time and feedback for helping me with this.
elshae
I actually found one way of doing it..Here goes..
<?php
$directory = './thumbnails/';
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file;
$nofiles++;
}
}
//$i = rand(0, 3);
$output = $_GET['thumbnails'] . "({";
for($i=0; $i < 3; $i++){
//$json[i] = json_encode($thumbs[$i]);
//$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}
$output = $output . "})";
//echo $_GET['thumbnails'] ."(".$json.")";
echo $output;
?>
That outputs:
({'thumb0':'http://localhost:80/mapScripts/thumbnails/Tibet2.jpeg','thumb1':'http://localhost:80/mapScripts/thumbnails/lhasa.jpeg','thumb2':'http://localhost:80/mapScripts/thumbnails/Tibet.jpg',})
Then in JavaScript I just:
function makeThumbs(data, layer){
alert("already Here "+ data);
var icon = new OpenLayers.Icon(data);
alert(icon.url);
layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
for(var m = 0; m < layer.markers.length; m++){
layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
$("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
}
}
$.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails=?', function(data) {makeThumbs(data.thumb2, markers);});
So it seems after the $_GET variable you can put typical JSON data and fetch it as you normally would (notice the data.thumb2 in the JavaScript).