Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP_SELF - How to use it correctly. 3

Status
Not open for further replies.

peterv12

Technical User
Dec 31, 2008
108
US
I've been told that PHP_SELF can be used with forms in the action field. Can someone point me to an explanation of how this works? I've searched the net and forums and haven't found anything that makes sense. From what I've gathered, you can use PHP_SELF in the action field and that will display the form if it hasn't already been submitted. I've tried it, but it will display the form and accept data in the form fields, but I want to put that data into a MySQL database. I've done it other ways, but have had to "manually" redisplay the input form. I apologize for the ambiguity of this post, but I'm not sure how to explain it. If anyone can help me out with maybe an example of a form using PHP_HELP that also can submit data to a MySQL database, I'd appreciate it.
 
Hi

Peter said:
I've been told that PHP_SELF can be used with forms in the action field.
It has nothing to do with the [tt]form[/tt]s. It is always defined.
Peter said:
PHP_SELF - How to use it correctly.
As [tt]$_SERVER['PHP_SELF'][/tt]. See [tt]$_SERVER[/tt] for more.


Feherke.
 
Yup, its an always present variable that holds the name and path of the page the current script is running on.

If you wanted to use it in the action property of a form, you just set it to output the value as:

Code:
<form action="<?PHP echo $_SERVER['PHP_SELF']">

When the page is loaded the action will be populated with the name and path of the page.

It helps when you may have to rename the page but need the script to keep running regardless of what its name is. If you have several forms that post to the same page, and want to avoid having to go in and alter their action property if the name of the page changes. It will do it for you automagically.





----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Please note that in (fairly recent) PHP versions, this variable contains TWICE what it should (appended). So if you have trouble using it, this may be the reason why. I wrote this function to overcome this:

Code:
function PhpSelf()
        {$strResult = $_SERVER['PHP_SELF'];
         if((strlen($strResult) % 2)==0):
            $strHalf = substr($strResult, 0 , strlen($strResult)/2);
            if($strResult == $strHalf . $strHalf):
               $strResult = $strHalf; // No idea what happens here? There is a bug in PHP that can cause the PHP_SELF to be duplicate.
            endif;
         endif;
         return $strResult; }


+++ Despite being wrong in every important aspect, that is a very good analogy +++
Hex (in Darwin's Watch)
 
Everyone,
I guess I'm kind of confused. I must have misread what PHP_self is used for. I'd appreciate it if you'd read the summary of what I'm trying to do, and tell me if there is a simpler or better way to do it.

data_entry_form.html
execute_sql.php
display_message.php

The first page is an html form for entering data. The "action" parameter is set to a php file (execute_sql.php) that brings in the data from the form using $_POST. It then executes MySQL commands to process the data. At this point, I have an include statement to display the display_message_php page, which is actually just a copy of the initial form with a "record processed" message displayed. (I'd like to know if there's a way to redisplay the initial form with a message, thus eliminating the need for the additional message page.) On this page the "action" item is set to the original data_entry_form.html page, which is accessed by a "back" button.

Any ideas on how this process might be improved? Getting this to work isn't the problem, I want to learn how to make this efficient, using good coding practice, so any suggestions are very welcome!

 
There are several ways to do this.

1. Turn the data_entry_form.html to a php page, data_entry_form.php. Set the form action to either data_entry_form.php or $_SERVER['PHP_SELF'],
and:
1.A)Put your processing code in a block inside data_entry_form.php to process the data from the form.

1.B) Use an include() to bring in the processing code from execute_sql.php. and have it process the data from the form.

These two slightly different methods allow you to show the form again very easily, you can either have it with the filled in values if you need it. And you can show the message right there after everything is done.

However if your processing code is very long, and/or complex, option A) may make the file harder to maintain.
While B) maintains a separation and lets you do everything from the same basic data_entry_form.php page.


2. Provided nothing is output to the screen in execute_sql.php then you can use a header redirect, to send the browser back to data_entry_form.html and display a message based on a parameter you use in the URL.



3. Generate a completely new data_entry_form in display_message.php to display with the message.
(not an option I'd recommend)


Overall I think 1.B) is the way I would have done it, if I needed to re-display the form after processing.

This allows me to keep the processing code separate from the form, but still let me re-display the form should something be wrongfully filled in, or missing etc. with the least amount of effort.




----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Phil, I like option 1B as well. I'm working on doing that now, and it may take me until tomorrow, but I'll be back with either more questions, or hopefully, a thank you after successfully coding this. Thanks again for all your help.
 
Phil,
I'm trying your 1B suggestion, but I'm a little confused. If I put the sql code in an include file, where should it go in the file? Also, if the "action" is PHP_SELF, how does the form get processed before the sql include file? I think I need to find a PHP/HTML form tutorial, I don't want to keep bugging you with beginner questions.
 
personally i do it like this (all one file). if the forms get very complex then an include might be more efficient.

Code:
<?php

if (empty($_POST['submit'])){
	displayForm();
} else {
	if (TRUE === ($result = processForm())){
		showsuccessmessage();
	} else {
		displayForm($result);
	}
}

function processForm(){
	$fields  =array ('lastname');
	foreach ($fields as $field){
		if (isset($_POST[$field])){
			$data[$field] = mysql_real_escape_string($_POST[$field]);
		} else {
			$data[$field] = '';
		}
	}
	$sql = "insert into sometable (id, lastname) values (NULL, '%s')";
	$query = vsprintf($sql, $data);
	$result = @mysql_query($query);
	if ($result === false){
		return 'Error found in the query: '. mysql_error() .' <br/>query was: '.$query;
	} else {
		return true;
	}
}
function showSuccessMessage(){
	echo <<<HTML
Record successfully added. <br/>
Click <a href="{$_SERVER['PHP_SELF']}">here</a> to add another
HTML;	
}
function displayForm($message = ''){
	$message = empty($message)? '' : "<div class=\"errorMessage\">$message</div>";
	$fields = array('lastname'=>'text');
	foreach ($fields as $field=>$type){
		if(empty($_POST[$field])){
			$$field = '';
		} else {
			$$field = $_POST[$field];
		}
	}
	echo <<<HTML
$message
<div class='formHolder'>
	<form action="{$_SERVER['PHP_SELF']}" method="post">
		<fieldset>
			<input type="text" name="lastname" value="$lastname" />&nbsp; Type your surname<br/>
			<input type="submit" name="submit" value="submit" />
		</fieldset>
	</form>
</div>
HTML;
}
?>
 
I think you've given the game away by confessing your a beginner!

What you are trying to do is quite often called a postback. If you search google for postback php you'll get more than enough to confuse you. Let me add a little to that confusion!.

As you will know forms that are PHP scripts are always generated by running some code on the web server as opposed to a simple display of HTML, The PHP might not do anything except output html but it still executes. In general the PHP code will consist of some actual PHP code at the top followed by HTML (which may have PHP inter-mingled into it). So you might see forms coded like:

Code:
<input type=text name=userid value = "<?php echo $userid;?>">

And perhaps later on things like:

Code:
user name: <?php echo $username; ?>

When the PHP script runs for a form it can decide whether this script was as the result of clicking a submit or not. If not it will usually be as the result of a user navigating to the page perhaps from a link or from just typing in the name of the page into the address bar. The script is only ever in one or other of these two states. If it is because of a submit it's often called a postback.

If the PHP script decides that the page is not as a result of a postback it will probably just do some initialisation (e.g set $userid and $username to spaces). This initialisation is important as PHP will try to use the variables later on inside the form. If the PHP scripts decides it is in a postback it will do something with the form fields which are usually in $_POST. This might involve going to the data base with $userid and populating $username with the result.

So that's essentially it. Your script needs to understand if it's in a postback or not. I've seen various methods for doing this such as having a hidden variable in the form called $postback. The script checks to see if this variable exists, if it does it's in a postback as the submit processing will have automatically created the $postback variable in $_POST. Other techniques involve just looking at the $_POST to see if it has expected values, or checking if this page was as the result of an HTTP GET or HTTP POST

So to address some specific points, PHP_SELF is just the name of the executing script. Others posters mention putting code in include scripts. This is quite correct but I suspect you need to get you head around the basic PHP page architecture before you move onto to stuff like that.

 
peterv12 said:
Phil,
I'm trying your 1B suggestion, but I'm a little confused. If I put the sql code in an include file, where should it go in the file?

Also, if the "action" is PHP_SELF, how does the form get processed before the sql include file? I think I need to find a PHP/HTML form tutorial, I don't want to keep bugging you with beginner questions.[/quote]


I'm assuming you mean: "where should it go in the file that has the form"?

If so then you need to put it where it will begin to
process the form.

for example (and this is the way I usuall do it):
[code
if(isset($_POST['process'])){
include("processingfile.php");
}
<form action="<?PHP echo $_SERVER['PHP_SELF']; ?>" method="POST">
...
<input type=submit name="process" value="Submit">
</form>

[/code]

What this does is it checks whether or not $_POST['process'] exists or is set by using the isset function. If it is set, then the form has been submitted, as the value from the submit button has been passed and a variable created for it.

It then just includes the file that holds all the processing code. So it does all the work.

This same file decides what to do after wards.
And then as a last tihng if the form was not submitted or its done processing, then it displays the form.
Now you can conditionalize the display of the form if you need to based on the result of the processing script.

The only thing is to check whether the form has been submitted before attempting to include the file if only to avoid errors related to non existent variables at the time. This is what postback is all about. Since everything is done in the same script, you need to check at what point in the flow you currently are.

jpadie posts uses the 1.A method. which I use if the processing is short and simple, and will not make future reading of the file too complex.






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Excellent Phil. Thank you for your time and knowledge!
 
Phil, just an update. This worked perfectly! (As have all your past suggestions.) I really appreciate your assistance. Since you are a guru, I was wondering how you gained all your knowledge. Also, would you have any suggestions for a good PHP book? Thanks again!
 
Guru? Hardly, I'd have to leave that title for jpadie.

How I gained my knowledge hmm lets see: I started out at college one of my classes involved PHP. So I learned the basics there.
The rest was basically self taught.

But I can say with confidence, that I learned by doing and writing code, and by helping out here. Most of the time you learn by trying to help with other people's problems.

You get scenario's you likely would never have seen other wise. And even if I don't post I try to read the posts and often learn from them.

Like everything in life its about practice.

Books will help you out with the basics, but after that you need to start coming up with the solutions yourself.

The PHP online manual is an invaluable resource.
Functions, examples, etc... Its a great place to start looking for help with the less basic stuff.






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
I now have a "bug" to figure out. I'm checking a variable's value to determine what to do next. The first check I do is for zero. Is there something special about the way you have to test for either zero or NULL? The reason I'm asking is that when the value of $rows is either zero or NULL it always takes the zero branch. If it is NULL, it should not take that branch. It seems like it is treating NULL as if it is zero. If $rows is > 0, that is working fine. Looking at the code, I have no idea why the zero check is failing. Can anyone help me out?


Code:
<?php
    $rows = NULL;
echo "rows: $rows prior to NULL check...<br>";
   [b][COLOR=red]if ($rows == 0)[/color][/b] {
       $display_block = "Record Not Found<br>$rows record(s) processed.";
       echo "<br><center><b>$display_block</b></center>";
    }elseif($rows > 0) {
        $suffix = "d";
        switch ($formoption) {
        case 'Delete':
          $action_taken = $formoption."d";
          break;
        case 'Add':
          $action_taken = $formoption."ed";
          break;
        case 'Update':
          $action_taken = $form_option."d";
          break;
        case 'Search':
          $action_taken = "Found.";
        }
        if ($display_block != "Record Not Found." &&
           $display_block != "**** ERROR: did you select Author instead of BOOK?") {
        }
       $display_block = "$rows record(s) processed.<br><b>$fname $lname was $action_taken</b>";
       echo "<br><center><b>$display_block</b></center>";
    }
//    echo "<br><center><b>$display_block</b></center>";
    ?>
 
Normally, 0 and Null would be considered the same thing: The variable has technically no value.

However if you really need to discriminate between the two, you can ask PHP to check for both type and value.

So an integer 0 would be different to that of a Null value.

You can do this by supplying one more = (equal sign) to the comparison.
Code:
if(x ==[red]=[/red] y){
...
}




----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Phil, Thank you so much! It would have taken me weeks to figure all this out with trial and error. I'm reading a beginning PHP tutorial, so hopefully the questions will get tougher. Have a good weekend!
Peter V.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top