php populate locked Word template form

I have a ms Word doc template that is locked via password so I can't get to the field properties.  I don't have access to the password either.

I want to be able to populate the fields via a PHP form so I can capture the field data into a MySQL database and then also produce the word document but with the fields filled out so I can then print it.

Let me just say that LiveDocX is not a viable option because of security concerns for the content of the form.  All processing has to stay in our intranet.
Who is Participating?
GrahamSkanConnect With a Mentor RetiredCommented:
I don't know PHP, but if you can use COM and hence the Word Object Model, you don't need to remove forms protection to fill in the forms.

In VBA, it is:
objDoc.FormFields("Text1").Result = "Some Text"
objDoc.FormFields("Check1").CheckBox.Value = True

If you don't know the field names, you could use the numerical index instead:
objDoc.FormFields(1).Result = "Some Text"

And you could list the names as in this VBA macro

Sub ListFormFieldNames
    Dim i as Integer
    Dim ffld as FormField

    For i = 1 to ActiveDocument.FormFields.Count
         Debug.print i, ffld.Name
    Next i
End Sub

Finally, because forms protection is a convenience and not a security measure, you can get an unprotected copy of the document. In the Word application, create a blank document and 'Insert' the form document. In Word 2007, that is done by:
Insert tab> Text group> Object > Text from file...
As I recall, in earlier Word versions, you go via the Insert menu item on the standard toolbar.

yoshcomputersAuthor Commented:
Here is the actual file I want to be able to populate via PHP.  I have saved it as an XML file and can get to the field names, but not sure how to populate it back with values.
Helen FeddemaCommented:
Here is some code that works with a document made from a partially locked template, unprotects the appropriate section to update doc properties filled from VBA Automation code, and then reapplies protection  If there is a password, it is set using the Password argument:
With appWord
   .Visible = True
   Debug.Print "Going to save as " & strSaveNamePath
   .ActiveDocument.SaveAs strSaveNamePath
   .Selection.HomeKey unit:=wdStory
   If strWordTemplate = "Needs Protection.dotx" Then
       doc.Sections(1).ProtectedForForms = False
   End If
End With

If strWordTemplate = "Needs Protection.dotx" Then
   'Protect section with form fields for user data entry
   doc.Sections(1).ProtectedForForms = True
   doc.Protect Password:="", Type:=wdAllowOnlyFormFields
   doc.Sections(2).ProtectedForForms = False
End If

Open in new window

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Helen FeddemaCommented:
This particular document had both DocProperty fields filled from Access, and form fields, to be filled in by the user.
yoshcomputersAuthor Commented:
I was able to unprotect the document and can get to the bookmarked names of the fields.  But I still don't know how to populate them with PHP.  I would need examples for PHP, not VBA.  I would prefer not to use a COM because it is very likely the servers I am dealing with won't have Microsoft Office installed.  But even if all I could get was a COM example, I would be happy.

Here are 5 of the Bookmarknames for the fields:
Text1, Text2, Text3, Check17, Check18

An example to include populating the fields and having Check17 and Check18 mark as true and save the file with a new filename would award you all the points.
yoshcomputersAuthor Commented:
OK...moving right along.  I figured out how to edit the Text fields via a COM interface (still not my preference)...but I haven't been able to get checkboxes to show they are checked.  I have tried values of true, checked, and even 'X' but it just displays text next to the checkbox instead of showing the checkbox is checked.

I wonder if it is a factor of the document has to be in unprotected mode to be able to edit the fields.  However if I put it in protected mode, I get an error saying I can't access the fields because the document is protected.
I think that everyone is on a learning curve here. There definitely shouldn't be any restriction on updating form fields while protection is on. That is the whole point of forms protection. In fact it is better to keep protection on when updating the form field contents: when protection is re-enabled there is a specific argument to keep the previous form field contents.

Does PHP have an equivalent of the VB boolean values of True and False? Perhaps you should show the code that you are using, so that any PHP as well as Word experts can pool resources and see what methods you are trying.
yoshcomputersAuthor Commented:
Fair enough comment form Graham.  I am including the code for accessing the file and then writing the Text values.  I have a suspicion that the Range->Text is the problem with making a checkbox checked instead of putting the textual value next to it.  But I don't know what term to try.  I have tried Range->Value and Range->Checked but it reports an error 'Unable to lookup `Checked' or 'Value'


$word = new COM("word.application") or die("Unable to instantiate Word");

// use like this. Place your's word file in C drive
echo $current_date = date("m/d/Y");

$tim= date("Y-m-d");

$info_array=array(  "Text1"      => "Yosh",
                    "Text2" => "$tim" ,
                    "Text3"   => "sparsh" ,
                    "Check17"   => True,
                    "Check18"   => 'Checked') ;

foreach($info_array as $bookmarkname => $re)
        $objBookmark = $word->ActiveDocument->Bookmarks($bookmarkname);
		echo $bookmarkname."<br>";
        $range = $objBookmark->Range;
	echo $range->Text = $re ;

$new_file = "C:/Files/Form1818_newedit.doc";



$word = null;

Open in new window


Even VB programmers are tempted to use the form field's bookmark and try to extract the data from it.

However the .Result method of the formfield object is actually designed to get the relevant information. This is because the text of range of its bookmark includes extra unneeded text that would have to be stripped off with a complex algorithm.

Thought I'm sure that it is possible, I can't see how the PHP code does exactly what we would do in VB. For instance, in VB, the For Each construct walks through the whole collection, and not through a particular named subset.

This my best guess at shoehorning my code into PHP. I've used an asterisk-> 'FormFields(*)' to wildcard the list, so that it will include all items.

        $ffld = $word->ActiveDocument->FormFields(*);
            echo $ffld.Name"<br>";
      echo $ffld->Result = $re ;
yoshcomputersAuthor Commented:
I figured it out myself and here is the workaround code I have in place for now.
In order to access a Checkbox state you have to access it via the FormFields Object, not the Bookmarks Object.

If the Type is 'TextInput' You can access the 'Results' property to keep the data in an input field or you could use 'Range->Text' to just display the data.
For Type is CheckBox you have to then access the CheckBox Value state to toggle it from True or False.

The following code is using the $info_array to capture the name of the Field/Bookmark and its value as described in the prior code example above.
foreach($info_array as $bookmarkname => $re)
        $objFormFields = $word->ActiveDocument->FormFields($bookmarkname);
		echo "<br>".$bookmarkname." = ".$objFormFields->Type;
		if ($objFormFields->Type == 70){ //Type 70 is 'TextInput' , Type 71 is 'CheckBox'
			echo $objFormFields->Result = $re ;
		} else {
			echo $objFormFields->CheckBox->Value = $re;


Open in new window

yoshcomputersAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 0 points for yoshcomputers's comment http:/Q_27290437.html#36482010

for the following reason:

I ultimately had to dig through Microsofts MSDN library to find the answer I needed<br /><a href="" target="_blank"><wbr />en-us/libr<wbr />ary</a>
yoshcomputersAuthor Commented:
On second review of the support answers, I realize that GrahamSkan had the right terminology but because it was in VBA and didn't specify I was using the wrong Object (the Bookmark object)  I didn't realize he was showing me the correct object to use (the FormFields object).  I just thought it was a different term for VBA vs PHP.

GrahamSkan should get 300 points.  I would have been able to award all of it had it been more clear about which object to use and that the protection problem I was having was because I was trying to access the Bookmark->Range->Text data instead of the FormFields->Results.  Also didn't address the CheckBox value issue I discovered on my own.
yoshcomputersAuthor Commented:
Keep in mind the code that I finally ended up using at the bottom of the results is correct for PHP
Thanks. Yes, it is sometimes hard to know what to be explicit about, and what to take as read.
All Courses

From novice to tech pro — start learning today.