http referrer question

Posted on 2009-02-10
Last Modified: 2012-05-06
when i fill out my form correctly and submit i am redirected to the "lastpage" :

<input type="hidden" name="lastpage" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />

When I submit my form without a required field, the server side validation works and the form is reloaded with text telling me i have to enter something - all good.

however, at this point after i fill in the form fields properly i am still redirected back to the "lastpage" which is at this point the form -  i need to go return to the initial list of titles that i'm clicking on get me to the form.

in other words - i need to go back 2 pages after my form reloads because of validation and is then resubmitted


if (!defined('KEYMASTER')) {

	echo "<p><strong>You cannot access this page directly</strong></p>";



echo "<h1>Resources Articles</h1>\n";

switch ($subaction) {

	case "add":

		editPost($new = true);


	case "view":



	case "edit":



	case "delete":



	case "publish":







	function viewPost() {

		global $d, $action, $ak, $my, $start, $limit;

		$sortorder = sort_::getSortSession($action, 'leadpost DESC, start_date DESC');

		$sql = "SELECT id, title, leadpost, type, start_date, end_date, is_active FROM articles ORDER BY $sortorder";

		$resultset = $d->dbQuery($sql, $start, $limit);

		//Get total number of rows (for paging)

		$sql = "SELECT COUNT(*) AS total FROM articles";

		$totalrows = $d->getRowCount($sql);


		<p class="first">Manage all resources-related articles here. <?	html::infoLink($action); ?></p>

    <?	statusMessage(); ?>

	<?	html::addLink(); ?>

	<form action="index.php?action=<?= $action; ?>" method="post" name="admin">

		<input type="hidden" name="id" value="" />

		<input type="hidden" name="subaction" value="" />

		<input type="hidden" name="sort_cat" value="<? echo SORT_CAT; ?>" />

		<input type="hidden" name="sort_order" value="<? echo SORT_ORDER; ?>" />

		<table cellpadding="3" cellspacing="0" class="recs">

			<tr class="title">

				<th width=""><a href="javascript:sortList('title','<? echo sort_::reverse(SORT_ORDER); ?>');">Title</a></th>

                <th width=""><a href="javascript:sortList('type','<? echo sort_::reverse(SORT_ORDER); ?>');">Type</a></th>

				<th width="">Lead</th>

				<th width=""><a href="javascript:sortList('start_date','<? echo sort_::reverse(SORT_ORDER); ?>');">Start</a></th>

                <th width=""><a href="javascript:sortList('end_date','<? echo sort_::reverse(SORT_ORDER); ?>');">End</a></th>

				<th width="" align="center">Published</th>

				<th width="">Action</th>


		<?	if (!$d->dbNumRows($resultset)) { ?>


            	<td colspan="7">No Records Found</td>


		<?	}

			while ($row = $d->dbFetchObject($resultset)) { ?>


				<td><? echo cleanup::truncString($row->title, 25); ?></td>

                <td><? echo $row->type; ?></td>

                <td><? echo ($row->leadpost) ? "Yes" : "No"; ?></td>

				<td><? echo strftime("%m/%d/%y", strtotime($row->start_date)); ?></td>

                <td><? 	if ($row->end_date != '0000-00-00 00:00:00'):

							echo strftime("%m/%d/%y", strtotime($row->end_date));

						endif; ?></td>

				<td align="center"><? html::publishLink($row->id, $row->is_active, $action); ?></td>

				<td><? html::editLink($row->id); ?> &nbsp; <? html::deleteLink($row->id); ?></td>


		<?	} ?>


        <table cellpadding="3" cellspacing="0" class="recs">

	<?	rsPages::next_previous($limit, $totalrows); ?>



<? }

function publishRecord() {

	global $d, $action;


	$status = db::updatePublishRecord('articles');

	redirectOk("Record has been $status", $action);


 function editPost($new = false) {

		global $d, $action, $my, $ak;

		if (!$new) {

			$id = (int)$_REQUEST['id'];

			$sql = sprintf("SELECT * FROM articles WHERE id = %u", $id);

			$result = $d->dbQuery($sql);

			$post = $d->dbFetchObject($result);


		$title 		= ($new) ? "" : $post->title;

		$subtitle	= ($new) ? "" : $post->subtitle;

		$content	= ($new) ? "" : (HTML_EDITOR) ? stripslashes($post->content) : cleanup::populateHTML($post->content);

		$startdate	= ($new) ? "" : $post->start_date;

		$enddate	= ($new) ? "" : $post->end_date;

		$type		= ($new) ? "" : $post->type;

		$leadpost	= ($new) ? 0 : $post->leadpost;

		$filename	= ($new) ? "" : $post->filename;

		$url		= ($new) ? "" : $post->url;

		$publish	= ($new) ? 0 : $post->is_active;

		$id			= ($new) ? "" : $id;


		//Validate data and insert into database

		if (isset($_REQUEST['do_db'])) {

			$errors = editDB($new);


			//If errors occurred, make sure that the formfields still contain their information so user doesn't have to re-enter

			foreach($_POST as $k=>$v)

				${$k} = $v;


		//End validate/database


		//Determine which selection to default for the article type if editing.

		$selected = '';

		if (!$new) {

			if (strlen($content))

				$selected = 'text';

			elseif (strlen($filename))

				$selected = 'file';


				$selected = 'url';



	<?	err::validationError(); ?>

		<form action="index.php?action=<?= $action; ?>" method="post" name="admin" enctype="multipart/form-data" onSubmit="return checkForm();">

			<input type="hidden" name="subaction" value="<? echo ($new) ? "add" : "edit"; ?>" />

            <input type="hidden" name="do_db" value="1" />

			<input type="hidden" name="id" value="<?= $id; ?>" />

			<p class="first">Edit Articles</p>

        <?	html::backToView(); ?>

			<table cellpadding="4" cellspacing="0" width="650">


					<td>Title:<br />

					<input type="text" name="title" size="50" maxlength="255" value="<?= $title; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></td>



					<td>Subtitle:<br />

					<input type="text" name="subtitle" size="50" maxlength="255" value="<?= $subtitle; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></td>



                	<td>Type of Content:<br />

                    <select name="n_type" size="1">

                    	<option value="news" <?  if ($type == 'news') echo 'selected'; ?>>News</option>

                        <option value="event" <?  if ($type == 'event') echo 'selected'; ?>>Event</option>




					<td>Article Body:<br />

					<?	html::createTextarea('content', $content, HTML_EDITOR); ?></td>



                	<td><h3>Optional Media Attachment (choose one)</h3></td>


                <? if (strlen($filename)) { ?>


					<td>PDF: <a href="../uploads/<?= $action; ?>/<?= $filename; ?>" target="new"><?= $filename; ?></a> (Delete this image: <input type="checkbox" name="deleteimage" value="1" tabindex="<?= $ak->tabindex($key); ?>" />)</td>


				<input type="hidden" name="currentimage" value="<?= $filename; ?>" />

				<? } ?>


					<td>File: <em><small><? if (strlen($filename)) echo "Upload only to overwrite exisiting file"; ?></small></em><br />

					<input type="file" name="filename" size="25" maxlength="255" tabindex="<?= $ak->tabindex($key); ?>" /></td>



                	<td>External URL:<br />

                    <input type="text" name="url" size="25" maxlength="255" value="<?= $url; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></td>



                	<td><h3>Publish Dates</h3></td>



					<td><br />Start Date:<br />

					<div id="holder"><input type="text" name="startdate" onfocus="showCalendar('',this,this,'','holder',0,20,1)" size="25" maxlength="10" value="<?= $startdate; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></div></td>



					<td><br />End Date: (<small>Leave blank to keep up all the time</small>)<br />

					<div id="holder2"><input type="text" name="enddate" onfocus="showCalendar('',this,this,'','holder2',0,20,1)" size="25" maxlength="10" value="<?= ($enddate == "0000-00-00 00:00:00") ? '' : $enddate; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></div></td>



					<td><br /><? html::activeCheck($publish); ?></td>



					<td><br />Lead Article:

					<input type="checkbox" name="leadpost" value="1" <? if ($leadpost) echo "checked"; ?> tabindex="<?= $ak->tabindex($key); ?>" /></td>



					<td><br /><p><? html::submitButton(); ?> &nbsp; <? html::cancelButton($action); ?></p></td>



            <input type="hidden" name="lastpage" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />


<? } ?>

<? function editDB($new = false) {

		global $d, $action, $errors;

		$title 		= cleanup::stripHTML($_POST['title']);

		$subtitle 	= cleanup::stripHTML($_POST['subtitle']);

		$content	= (HTML_EDITOR) ? trim(addslashes($_POST['content'])) : cleanup::stripHTML($_POST['content']);

		$leadpost	= isset($_POST['leadpost']) ? 1 : 0;

		$startdate	= trim($_POST['startdate']);

		$type		= $_POST['n_type'];

		$enddate	= trim($_POST['enddate']);

		$url		= trim($_POST['url']);

		$del_image	= (isset($_POST['deleteimage'])) ? 1 : 0;

		$publish	= (isset($_POST['active'])) ? 1 : 0;

		$id			= (int)$_POST['id'];

		if (!strlen($title)) $errors[] = "You must enter an article title.";

		if (strlen($url) && strlen($_FILES['filename']['name'])) $errors[] = "You can only select a URL or PDF file, but not both.";

		if (strlen($subtitle) && !strlen($title)) $errors[] = "You cannot enter a subtitle without a main title.";

		if (!validate::checkDate($startdate)) $errors[] = "Start date must be in 'yyyy-mm-dd' format.";

		if (strlen($enddate)) {

			if (!validate::checkDate($enddate)) $errors[] = "End date must be in 'yyyy-mm-dd' format.";

			if (strtotime($startdate) > strtotime($enddate)) $errors[] = "Your end date cannot be before the start date.";



		if (!count($errors)) {

			$filename = fu::uploadImage($_FILES['filename'], NEWS_F);

			//If error returned from file upload, appened to list.

			if (is_array($filename))

				$errors[] = $filename;


		if (!count($errors)) {


			if (!$new) {

				if (strlen($filename) && strcmp($filename, $_POST['currentimage']) != 0 || $del_image) {

					unlink(NEWS_F . FS . $_POST['currentimage']);

					if ($del_image) $filename = '';

				} else

					$filename = $_POST['currentimage'];



			//If selected as lead post, remove any other record that has the lead post flag

			if ($leadpost) $d->dbQuery("UPDATE articles SET leadpost = 0 WHERE 1");


			if ($new) {

				$sql = "INSERT INTO articles (title, subtitle, content, start_date, end_date, type, leadpost, filename, url, is_active)\n";

				$sql .= "VALUES ('$title', '$subtitle', '$content', '$startdate', '$enddate', '$type', $leadpost, '$filename', '$url', $publish)";

			} else {

				$sql = "UPDATE articles SET

					\n title = '$title',

					\n subtitle = '$subtitle',

					\n content = '$content',

					\n start_date = '$startdate',

					\n end_date = '$enddate',

					\n type = '$type',

					\n leadpost = $leadpost,

					\n filename = '$filename',

					\n url = '$url',

					\n is_active = $publish

					\n WHERE id = $id";



			redirectOK("News Entry successful.", $_POST['lastpage']);

		} else {

			return $errors;




<? function deletePost() {

		global $d, $action;

		$id = (int)$_POST['id'];

		$file = $d->dbQuery("SELECT title, filename FROM articles WHERE id = $id");

		$fn = $d->dbFetchObject($file);

		//Delete any file associated with record

		if (strlen($fn->filename))

			unlink(NEWS_F . FS . $fn->filename);


		//Delete any SEF record associated

		$sef_id = sef::getsefId($fn->title, $id);

		if ($sef_id)

			$d->dbQuery("DELETE FROM sef WHERE id = $sef_id");

		$d->dbQuery("DELETE FROM articles WHERE id = $id");



		redirectOK("Article deletion successful.", $action);



Open in new window

Question by:phillystyle123
    LVL 2

    Accepted Solution

    Now I must say PHP is far from my favorite programming language (never had much time to dig into it that is). But basically you'll want to do this.
    - Normally when you submit a form you can request the values you had in the fields of that form. I think that's something like $_POST["name_of_field"] in PHP right?
    - Check if the page is being posted, if false then use the echo referrer thing to set your hidden field, if true then use the $_POST["referrer"] value to redirect the page
    I could try coding that in PHP but I think you are better at it and with this simple example you might be able to pull it off yourself. =)
    LVL 19

    Assisted Solution

    how about this, first time the post won't be set so it will use the referer next time it will use the initial value of the lastpage post
    <input type="hidden" name="lastpage" value="
    if ($isset($_POST['lastpage'])
      echo $_POST['lastpage'];
      echo $_SERVER['HTTP_REFERER']; 
    ?>" />

    Open in new window

    LVL 2

    Assisted Solution

    Ok ok I can't help myself =P I tried to code it for you, see if you understand what I'm doing =)
    <input type="hidden" name="lastpage" value="<?
    if (isset($_POST["lastpage"]))
    	echo $_POST["lastpage"];
    	echo $_SERVER['HTTP_REFERER'];
    ?>" />

    Open in new window


    Author Closing Comment

    THANKS to the both of you - works perfectly and i understand the logic

    Featured Post

    What Is Threat Intelligence?

    Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

    Join & Write a Comment

    Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
    Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now