Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've researched this problem in depth, but still stumped.

Simply stated, I have an external uploader script which loads WP. Yet I cannot seem to grab any of the actions/filters I've put into it. Why is this?

I've tried various methods to load WP in the script.

This returns a 404 when the uploader (javascript) calls it:

define( 'WP_USE_THEMES', false );
require_once('../../wp-blog-header.php');

So a work-around I found, seems to do fine:

require_once('../../wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();

This above example seems to work, except I cannot find any conceivable way to hook into it. Even if I put the entire upload processor into a function which hooks to various places such as ...

add_action('plugins_loaded', 'the_upload_processing_function');
//or
add_action('wp_loaded', 'the_upload_processing_function');
//and so forth...

Dead air...no response. The script will run if I leave it outside of a function, just running under the load wordpress-start-up code, but the hooks / actions do not work.

The result I cannot seem to achieve:

  • Plugin calls the uploader script via javascript, upload.php (works)...
  • The plugin hopefully loads before the upload script, and depending on $_POST var, it will alter the target directory path using a filter:

This is the filter...

$targetDir = apply_filters('ss_upload_destination', $targetDir);
  • The $targetDir should thus be altered, but the hooks seem invisible to the plugin. Absolutely no way to grab it.

I've tired to describe the problem without making the issue too long. I'd appreciate any insight that can be shared.


For reference, here is the entire upload script:

<?php

require_once('../../wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();

//define( 'WP_USE_THEMES', false );
//require_once('../../wp-blog-header.php');

if(!is_user_logged_in())
    die();

// Make sure file is not cached (as it happens for example on iOS devices)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

/* 
// Support CORS
header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit; // finish preflight CORS requests here
}
*/

// 5 minutes execution time
//@set_time_limit(5 * 60);

// Uncomment this one to fake upload time
// usleep(5000);

// Settings
$targetDir = ss_upload_dir . ss_blog_path . '/';

if(!is_numeric($_REQUEST['upload_destination']))
    die;

$blog_id = $_REQUEST['upload_destination'];

switch_to_blog($blog_id);

$path = ss_get_blog_path($blog_id);

$targetDir = ss_upload_dir . $path . '/';

$targetDir = apply_filters('ss_upload_destination', $targetDir);

//$targetDir = 'uploads';
$cleanupTargetDir = false; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds

// Get a file name
if (isset($_REQUEST["name"])) {
    $fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
    $fileName = $_FILES["file"]["name"];
} else {
    $fileName = uniqid("file_");
}

$filePath = $targetDir . $fileName;

// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;

// Remove old temp files    
if ($cleanupTargetDir) {
    if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
    }

    while (($file = readdir($dir)) !== false) {
        $tmpfilePath = $targetDir . $file;

        // If temp file is current file proceed to the next
        if ($tmpfilePath == "{$filePath}.part") {
            continue;
        }

        // Remove temp file if it is older than the max age and is not the current file
        if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
            @unlink($tmpfilePath);
        }
    }
    closedir($dir);
}   


// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}

if (!empty($_FILES)) {
    if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
    }

    // Read binary input stream and append it to temp file
    if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
    }
} else {    
    if (!$in = @fopen("php://input", "rb")) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
    }
}

while ($buff = fread($in, 4096)) {
    fwrite($out, $buff);
}

@fclose($out);
@fclose($in);

// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
    // Strip the temp .part suffix off 
    rename("{$filePath}.part", $filePath);
    do_action('ss_file_upload_complete', $filePath);
}

do_action('ss_after_upload');

// Return Success JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
share|improve this question
    
Why not use the AJAX API? –  Milo May 9 at 4:07
    
Because it would interfere with the js of uploader I'm working with. –  user1915665 May 9 at 4:24
    
how would targeting admin-ajax.php instead of your upload.php script interfere with your uploader? –  Milo May 9 at 4:32
    
I'll give it a try...since the js is interactive with upload.php on a continual basis (its an uploader) I figured wordpress API would just get in the way. –  user1915665 May 9 at 4:39
    
but you apparently need the WordPress API, and that's the most reliable way to get it. –  Milo May 9 at 4:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.