‘PHP_SELF’ and ‘SCRIPT_NAME’ Questions – PHP

  php

Q(Question):

Hello,

I am currently trying to write a quick form that I want to appear on all my pages. What I basically do is create 3 files for each page.header.php file.php footer.php The header and footer files stay the same site-wide and I just include them in ‘file.php’ in order to avoid retyping hundreds of lines of code. I am thinking about putting a form like this in the ‘footer.php’ file:

<form name="login" action="file.php" method="post">

The only problem I have is that the name of ‘file.php’ changes depending on the page I have.

I was wondering if I used $_SERVER[‘PHP_SELF’] or $_SERVER[‘SCRIPT_NAME’] in ‘footer.php’ would it return the path to ‘footer.php’ or to ‘file.php’.

I have also seen $_SERVER[‘REQUEST_URI’] around and that might be another option.

A(Answer):

http://php.net/manual/en/reserved.variables.server.php

Regards

A(Answer):

@chathura86

I have read the manual for those variables, but I want to know if it gives the path of the file in the url or the included ‘footer.php’ file.

For example, the url will be www.example.com/file.php, but the global variable will be run from ‘footer.php’ which is included in ‘file.php’ I want to know which one will show ‘file.php’ instead of ‘footer.php’. I am leaning toward ‘REQUEST_URI’ but I am not sure.

A(Answer):

all of them will give the file.php

example

inc1.php


<?php
echo $_SERVER['PHP_SELF'] . '<br>';
echo $_SERVER['SCRIPT_NAME'] . '<br>';
echo $_SERVER['REQUEST_URI'] . '<br>';
echo '<br>---------------------------------------' . '<br>';
?>

page1.php


<?php
echo $_SERVER['PHP_SELF'] . '<br>';
echo $_SERVER['SCRIPT_NAME'] . '<br>';
echo $_SERVER['REQUEST_URI'] . '<br>';
echo '<br>---------------------------------------' . '<br>';
include ('inc1.php');
?>

my request is http://localhost/test/page1.php?a=1


/test/page1.php
/test/page1.php
/test/page1.php?a=1
---------------------------------------
/test/page1.php
/test/page1.php
/test/page1.php?a=1
---------------------------------------

as you an see that REQUEST_URI has url parameters also

i useally use PHP_SELF but if i need the url parameters also
then i use REQUEST_URI

Regards

A(Answer):

Thank you very much for the clarification. Finally, with REQUEST_URI, does that also include information sent through the POST method?

A(Answer):

nope post date will not be included

Regards

A(Answer):

Thanks alot for all of your help.

LEAVE A COMMENT