You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP集成SlimerJS并实现动态属性值设置

Got it, let's break down your two needs step by step—making your SlimerJS script use dynamic values instead of hardcoding, and integrating that script with PHP. Here's everything you need to know:


1. Make Your SlimerJS Script Use Dynamic Values

First, a quick fix: your original script has a common SlimerJS pitfall—you can't directly access document in the main Phantom/Slimer context. You need to use page.evaluate() to run code in the page's DOM context. I'll include that fix in the dynamic versions below.

Option 1: Pass Values via Command Line Arguments

This is perfect for one-off runs or when you want to inject values from external tools (like PHP later):

var page = require('webpage').create();
var system = require('system');
var url = 'http://localhost/slimerjs';

// Check if we got enough arguments
if (system.args.length < 3) {
  console.error('Usage: slimerjs your-script.js <username> <password>');
  slimer.exit(1);
}

// Grab dynamic values from command line
var username = system.args[1];
var password = system.args[2];

page.open(url, function(status) {
  if (status === 'success') {
    // Run DOM operations in the page's context
    page.evaluate((user, pass) => {
      const usernameInput = document.getElementsByClassName("test")[0];
      if (usernameInput) usernameInput.setAttribute("value", user);
      
      const passwordInput = document.getElementsByClassName("class")[0];
      if (passwordInput) passwordInput.value = pass;
    }, username, password); // Pass values into the evaluate function
    
    console.log('Successfully set input values');
    slimer.exit();
  } else {
    console.error('Failed to load target page');
    slimer.exit(1);
  }
});

To run it, just pass your values directly:

slimerjs your-script.js "MyTestUser" "MySecurePass123"

Option 2: Load Values from a Config File

Great if you need to manage multiple sets of test data without changing the script:

  1. Create a test-config.json file:
{
  "url": "http://localhost/slimerjs",
  "username": "DevTestUser",
  "password": "DevPass456"
}
  1. Update your SlimerJS script to read the config:
var page = require('webpage').create();
var fs = require('fs');

// Load and parse the config file
try {
  var config = JSON.parse(fs.read('test-config.json'));
} catch (e) {
  console.error('Error reading config file:', e.message);
  slimer.exit(1);
}

page.open(config.url, function(status) {
  if (status === 'success') {
    page.evaluate((user, pass) => {
      const usernameInput = document.getElementsByClassName("test")[0];
      if (usernameInput) usernameInput.setAttribute("value", user);
      
      const passwordInput = document.getElementsByClassName("class")[0];
      if (passwordInput) passwordInput.value = pass;
    }, config.username, config.password);
    
    console.log('Values loaded from config file');
    slimer.exit();
  } else {
    console.error('Page load failed');
    slimer.exit(1);
  }
});

Now you just edit the JSON file to switch test values—no script changes needed.


2. Integrate SlimerJS with PHP

PHP can call external commands like SlimerJS using exec() or shell_exec(). Here's how to do it safely and reliably:

Example PHP Code

<?php
// Configure paths and dynamic values
$slimerJsPath = '/usr/local/bin/slimerjs'; // Update to your actual SlimerJS path
$scriptPath = '/var/www/html/your-slimer-script.js'; // Path to your script
$username = "UserFromPHPDB"; // Pull this from DB, form input, etc.
$password = "PassFromPHP";

// Build the command safely (prevents command injection)
$command = escapeshellcmd($slimerJsPath) . ' --headless ' . 
           escapeshellarg($scriptPath) . ' ' . 
           escapeshellarg($username) . ' ' . 
           escapeshellarg($password);

// Execute the command and capture output/errors
$output = [];
$returnStatus = 0;
exec($command, $output, $returnStatus);

// Handle results
if ($returnStatus === 0) {
  echo "SlimerJS script ran successfully:<br>" . implode("<br>", $output);
} else {
  echo "SlimerJS script failed:<br>" . implode("<br>", $output);
}
?>

Key Notes for PHP Integration

  • Headless Mode: Add --headless to the command if you're running on a server with no graphical interface (most production environments).
  • Permissions: Make sure the web server user (e.g., www-data for Apache, nginx for Nginx) has:
    • Execute permissions for SlimerJS and Firefox (SlimerJS depends on Firefox)
    • Read access to your SlimerJS script and config files
  • Path Accuracy: If SlimerJS isn't in your system's PATH, use the full absolute path to the executable.
  • Security: Always use escapeshellcmd() and escapeshellarg() to sanitize commands and parameters—this prevents malicious command injection attacks.

内容的提问来源于stack exchange,提问作者blitz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:09:21