• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 534
  • Last Modified:

http referrer question

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>";
	exit;
}
 
echo "<h1>Resources Articles</h1>\n";
 
switch ($subaction) {
	case "add":
		editPost($new = true);
		break;
	case "view":
		viewPost();
		break;
	case "edit":
		editPost();
		break;
	case "delete":
		deletePost();
		break;
	case "publish":
		publishRecord();
		break;
	default:
		viewPost();
		break;
}
 
	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>
			</tr>
		<?	if (!$d->dbNumRows($resultset)) { ?>
        	<tr>
            	<td colspan="7">No Records Found</td>
            </tr>        
		<?	}
			while ($row = $d->dbFetchObject($resultset)) { ?>
			<tr>
				<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>
				</tr>
		<?	} ?>
		</table>
        <table cellpadding="3" cellspacing="0" class="recs">
	<?	rsPages::next_previous($limit, $totalrows); ?>
    	</table>
	</form>
<? }
 
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';
			else
				$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">
				<tr>
					<td>Title:<br />
					<input type="text" name="title" size="50" maxlength="255" value="<?= $title; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></td>
				</tr>
				<tr>
					<td>Subtitle:<br />
					<input type="text" name="subtitle" size="50" maxlength="255" value="<?= $subtitle; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></td>
				</tr>
                <tr>
                	<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>
                    </select></td>
                </tr>
				<tr>
					<td>Article Body:<br />
					<?	html::createTextarea('content', $content, HTML_EDITOR); ?></td>
				</tr>
                <tr>
                	<td><h3>Optional Media Attachment (choose one)</h3></td>
                </tr>
                <? if (strlen($filename)) { ?>
				<tr>
					<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>
				</tr>
				<input type="hidden" name="currentimage" value="<?= $filename; ?>" />
				<? } ?>
				<tr>
					<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>
				</tr>
                <tr>
                	<td>External URL:<br />
                    <input type="text" name="url" size="25" maxlength="255" value="<?= $url; ?>" tabindex="<?= $ak->tabindex($key); ?>" /></td>
                </tr>
                <tr>
                	<td><h3>Publish Dates</h3></td>
                </tr>
                <tr>
					<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>
				</tr>
                <tr>
					<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>
				</tr>
                <tr>
					<td><br /><? html::activeCheck($publish); ?></td>
				</tr>
				<tr>
					<td><br />Lead Article:
					<input type="checkbox" name="leadpost" value="1" <? if ($leadpost) echo "checked"; ?> tabindex="<?= $ak->tabindex($key); ?>" /></td>
				</tr>
				<tr>
					<td><br /><p><? html::submitButton(); ?> &nbsp; <? html::cancelButton($action); ?></p></td>
				</tr>
			</table>
            <input type="hidden" name="lastpage" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
		</form>
<? } ?>
 
<? 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";
			}
			$d->dbQuery($sql);
 
			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");
		optimizeTable('news');
		
		redirectOK("Article deletion successful.", $action);
	}
?>

Open in new window

0
phillystyle123
Asked:
phillystyle123
  • 2
3 Solutions
 
willem1985Commented:
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. =)
0
 
Michael701Commented:
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'];
else
  echo $_SERVER['HTTP_REFERER']; 
?>" />

Open in new window

0
 
willem1985Commented:
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"];
else
	echo $_SERVER['HTTP_REFERER'];
?>" />

Open in new window

0
 
phillystyle123Author Commented:
THANKS to the both of you - works perfectly and i understand the logic
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now