Programming with P4PHP

The following example illustrates the basic structure of a P4PHP script. The example establishes a connection, issues a command, and tests for errors resulting from the command.

<?php

$p4 = new P4();
$p4->port = "1666";
$p4->user = "fred";
$p4->client = "fred-ws";

try {
  $p4->connect();
  $info = $p4->run( "info" );
  foreach ( $info[0] as $key => $val ) {
    print "$key = $val\n";
  }
  $p4->run( "edit", "file.txt" );
  $p4->disconnect();
} catch ( P4_Exception $e ) {
  print $e->getMessage() . "\n";
  foreach ( $p4->errors as $error ) {
    print "Error: $error\n";
  }
}
?>

This example creates a client workspace from a template and syncs it:

<?php

$template = "my-client-template";
$client_root = "/home/user/work/my-root";
$p4 = new P4();

try {
  $p4->connect();

  // Convert client spec into an array

  $client = $p4->fetch_client( "-t", $template );
  $client['Root'] = $client_root;
  $p4->save_client( $client );
  $p4->run_sync();

} catch ( P4_Exception $e ) {
  // If any errors occur, we'll jump in here. Just log them
  // and raise the exception up to the higher level
}
?>

Submitting a Changelist

This example creates a changelist, modifies it, and then submits it:.

<?php

$p4 = new P4();
$p4->connect();

$change = $p4->fetch_change();

// Files were opened elsewhere and we want to
// submit a subset that we already know about.

$myfiles = array(
  '//depot/some/path/file1.c',
  '//depot/some/path/file1.h'
);

$change['description'] = "My changelist\nSubmitted from P4PHP\n";
$change['files'] = $myfiles;
$p4->run_submit( $change );

?>

Logging into Perforce using ticket-based authentication

On some servers, users might need to log in to Perforce before issuing commands. The following example illustrates login using Perforce tickets.

<?php

$p4 = new P4();
$p4->user = "bruno";
$p4->connect();
$p4->run_login( 'my_password' );

$opened = $p4->
run_opened();

?>

Connecting to Perforce over SSL

Scripts written with P4PHP use any existing P4TRUST file present in their operating environment (by default, .p4trust in the home directory of the user that runs the script).

If the fingerprint returned by the server fails to match the one installed in the P4TRUST file associated with the script's run-time environment, your script will (and should!) fail to connect to the server.

Changing your password

You can use P4PHP to change your password, as shown in the following example:

<?php

$p4 = new P4();
$p4->user = "bruno";
$p4->password = "MyOldPassword";
$p4->connect();

$p4->run_password( "MyOldPassword", "MyNewPassword" );

// $p4->password is automatically updated with the encoded password

?>