How to get your command line PHP script working with WordPress-MU 2.7

OK, this one is obscure. I only post about what I can’t find on Google!

Until recently it has been possible to run command-line PHP scripts that include wp-config.php or wpmu-settings.php, in order to give those scripts access to WordPress globals like $wpdb, functions such as wp_insert_post etc.

These scripts worked with WordPress-MU until recently — now the scripts just exit with no output.

The reason? WPMU now initiates a redirect in the bootstrap process (search for ‘header( “Location: “‘ in wpmu-settings.php). A browser can follow that redirection, but a command line script cannot. So, if you want to initiate scripts that run from the command line, you will have to get the web server involved by invoking a text browser such as curl, wget, or links.

It’s best not to force your scripts to figure out where to find wp-config.php anyway. I have taken to using a method suggested in this thread, as shown in the code sample below. The good news is, you know that your script will work the same whether initiated from a plugin in a graphic browser, used in an Ajax call, or initiated from cron or the command line shell.

So instead of kicking your script off with something like

/usr/bin/php -q myscript.php

You will create the script as a proper plugin and do something like

/usr/bin/curl -d mypp_cmd=status http://mywpmusite.com

Sample plugin code used for the above example follows. The prefix for the functions is ‘mypp’, which of course stands for ‘MY Plugin Prefix’ to create a unique namespace. The code below returns results as JSON encoded, and calls die()/exit() at the end to prevent an entire page being created. For log files run from cron, you may choose to return plain text instead.

  /**
   * Add a query var for this plugin
   * This allows Ajax programs to operate without requiring file paths
   * Instead, Ajax functions look for the query var 'mypp_cmd'
   */
  function mypp_query_vars($qvars) {
    $qvars[] = 'mypp_cmd';
    return $qvars;
  } // function mypp_query_vars
 
  /**
   * Handle AJAX requests in the template_redirect action
   * We recognize our requests from the query var 'mypp_cmd'
   * Here we allow GET requests using $_REQUEST; to restrict to POST, use $_POST instead
   */
  function mypp_template_redirect() {
    global $wpdb;
    $cmd = get_query_var('mypp_cmd');
    $response = array();
    if ($cmd) {
      switch($cmd) {
      case 'status':
	$response['status'] = array('success' => true,
				    'message' => 'Sample status message');
	break;
      default:
	$response['status'] = array('success' => false,
				    'msg' => 'Unknown command',
				    'cmd' => $cmd);
	break;
      } // switch $cmd
      header('Content-type: text/x-json; charset=utf-8');
      print utf8_encode(json_encode($response));
      die();
    } // $cmd is set
  } // function mypp_template_redirect
 
add_filter('query_vars', array($this, 'mypp_query_vars'));
add_action('template_redirect', array($this, 'mypp_template_redirect'));
This entry was posted in Development, wordpress, wordpress-mu and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. James
    Posted May 27, 2010 at 4:04 am | Permalink

    Even easier than this is to set $_SERVER['HTTP_HOST'] to the correct domain before loading wp-load.php – then your PHP cli scripts work as before.

  2. Posted October 12, 2010 at 9:36 am | Permalink

    Greg, this was very useful. I was calling a script in the way you described and having the same problem. Searched for a good while before coming here and now it works. Thanks

  3. Richard
    Posted October 28, 2010 at 6:48 am | Permalink

    I found the following to work on Wordpress 3.01:

    //WP Functions that I’m overriding
    //Don’t Redirect
    function auth_redirect(){};

    //Pretend to be a real user
    function wp_get_current_user() {
    global $current_user;
    wp_set_current_user(1);
    get_currentuserinfo();

    return $current_user;
    }

    $_SERVER['PHP_SELF'] = ‘/wp-admin/admin.php’;
    $_SERVER['REQUEST_URI'] = ‘/wp-admin/admin.php?page=page_to_fake’;
    $_SERVER['HTTP_HOST'] = ‘domain’;
    $_GET['page']=’page_to_fake’;

    //Path to the admin file
    include(’../../../../wp-admin/admin.php’);

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*
  • randy moss combine results
  • tea party zombies download
  • search 78search 800 numbers
  • randy moss bio
  • dis systems
  • archos
  • randy moss yahoo stats
  • roses
  • dis quand reviendras-tu
  • xanadu bengals
  • zara phillips and the queen
  • 4pm cspancspan area 51cspan 90.1
  • freida pinto miral
  • search lsu.edu
  • mtv oddities
  • seagate
  • battleship aurora
  • greg olsen university of miami
  • mtv kings of leon
  • chad ochocinco sisterchad ochocinco twitter
  • tolerance
  • search engines cookiessearch engines definition
  • bonus
  • gears
  • hartmann
  • dis 0 0.9
  • vince young yahoo stats
  • radar
  • beers
  • search 2.0
  • homeless
  • dis boards cruise
  • search engines us
  • chad ochocinco johnson
  • bengals qb situation
  • gregg olsen books
  • zara phillips dating
  • vince young uncle rico gif
  • freida pinto green dress
  • bea luna
  • chicago bears media relations
  • framed
  • la ink 2011 season 5
  • deed
  • battleship vittorio veneto
  • di's hallmark
  • meant
  • chicago bears 61
  • vince young depression
  • cspan hosts
  • ratchet
  • new england patriots gillette stadium
  • chicago bears 08 record
  • chicago bears bleacher report
  • battleship yamato wreck
  • chicago bears training camp
  • la ink corey
  • chicago bears 1985
  • search engines watch
  • search engines questions
  • pendant
  • cspan facebook
  • connecticut renaissance faire
  • battleship egg hunt
  • serenity
  • kilo
  • bangles eternal flame mp3bengals forum
  • prairie
  • afternoon
  • greg olsen vikingsgreg olsen wife
  • springhill
  • tea party birthday
  • vince young quiz
  • bea zuberbühler
  • battleship ipad
  • betty
  • search engines of the world
  • bea 0b0 105
  • dis x
  • chicago bears tattoos
  • greg olsen vancouver
  • hp support 530
  • chicago bears expo
  • quran
  • legend
  • search engines 9
  • 60 search engines virus
  • zara phillips baby
  • freida pinto zac posen
  • connecticut education
  • battleship yamato 2010
  • search vim
  • hp support error 1005
  • pads
  • connecticut post
  • mtv executivesmtv fantasy factory
  • connecticut secretary of state
  • search 990 finder
  • rooster
  • homeowners
  • wein
  • chicago bears 96
  • vince young yahoo stats
  • worst
  • c span yesterdayc span zelaya
  • randy moss jail
  • new england patriots 98.5
  • hp support quick test pro
  • zara phillips baby
  • la ink games online
  • chicago bears pictures
  • chad ochocinco bears
  • zara phillips wedding hat
  • chad ochocinco vs skip bayless
  • chad ochocinco and cheryl burke
  • new england patriots jake locker
  • tijuana
  • hp support englandhp support forum
  • bengals arrests
  • c span video contest
  • mtv dougie
  • new england patriots 80
  • tea party zombies download
  • vince young redskins
  • cspan presidents
  • palma
  • bear gryllsbea hive dance studio
  • zara phillips kids
  • battleship galactica
  • randy moss 98 vikings
  • beagle
  • extending
  • hp support id
  • connecticut 5th district
  • vince young football camp
  • search tumblr
  • la ink cast
  • search 32
  • battleship wilmington nc
  • randy moss 07 08 highlights
  • hose
  • dis pater
  • crimper
  • la ink 03x05
  • mandolin
  • hp support 6500a plus
  • battleship bismarck wreck
  • search engines before google
  • cspan washington correspondents dinner 2011
  • reign
  • chad ochocinco quotes video
  • bea goldfishberg
  • dependency
  • spherical
  • coronado
  • randy moss vikings 2011
  • battleship lexington
  • mtv true life
  • vince young endorsementsvince young foundation
  • hiding
  • search and seizure
  • search engines usage statistics 2010
  • connecticut lottery
  • dressing
  • licensed
  • mtv overdrive
  • tea party nj
  • hp support chat
  • hp support greece
  • connecticut juvenile training schoolconnecticut kids
  • hp support error 1005
  • dis lyrics
  • bea 71 series staples
  • odessey
  • bea test
  • mtv 5 cover
  • new england patriots needs
  • la ink 04x01
  • vince young 99 yard video
  • rotation
  • search operatorssearch people
  • battleship hacked
  • bea verdi
  • zara phillips fascinator