Can I use an XSS vulnerability to read files on the server by injecting PHP code to the page? Ex: Use
document.write to inject PHP code that read the file.
There is a variant of XSS, sometimes called "Server-side cross-site scripting". It is much less common than client-side XSS. In fact, I have only seen it once on a live web site.
It occurs when the server renders HTML documents. This can happen when the server produces a PDF (e.g. a printable invoice) and HTML is part of the chain. If the attacker can inject tags into this HTML, they can reference local resources on the server. In the example I saw, it was only possible to include images, but variants may allow including other file types.
Some people may argue that this is not XSS. It is an example of CWE-610: Externally Controlled Reference to a Resource in Another Sphere. Other examples would be XML External Entities and external references from Word or SVG documents. I think "Server-side XSS" is a reasonable name for it, but I'm open to other suggestions.
You are mixing up scripts that run on the server, and scripts that run on the client.
You can not use
You could inject PHP code if there is a vulnerability in the server side code that lets you execute code. E.g. if you have something like this
you could use it to execute arbitrary PHP code and steal files from the server. Such a vulnerability is much more serious than a normal XSS vulnerability, but also much less common.
Lets imagine that there is admin-account in specially crafted webapp and that account has rights to get certain files from server (like, if admin requests /getfile.php?filename.txt, the getfile.php returns content of "filename.txt"). Then you could inject ajax-request to admin's client side and request files with that.