I'm in the middle of designing a mobile site for our main ecommerce site. Because the site is composed of inflexible legacy code I've opted to look up the users user agent string and identify them as a mobile user each page request. That way no changes to the url structure are needed. This seems to be working nicely so far.
However, I thought it may be kind of cool to use this mobile version so that users can browse our ecommerce site on facebook via iframe (the dimensions are perfect). But, unlike the mobile browsers, I am having trouble finding a persistent way to identify the user as a facebook user. I know facebook sends a $_POST variable the first time a page is viewed via iframe, and I could simply just store that in a session variable and be done with it. The issue that arises though is that what if the user visits with facebook, gets marked as a facebook user in their session, then visits our regular ecommerce site? Well, they'd still be identified as a facebook user and get served the facebook version, which is not ideal.
Maybe you can tackle the problem for another angle and test if the website is loaded from a frame or not?
This is possible with javascript:
if (top === self) {
//not a frame
} else {
//a frame
}
Not sure if it's proper etiquette to answer my own question but I found an answer which is a combo of Hassou's answer and a javascript php detection script.
The script I altered is from here:
http://snippets.bluejon.co.uk/check4-js-and-cookies/check4-js-enabled-v2-phpcode.php
Essentially the idea is to use javascript to submit a form referencing the current url, the result tells you if javascript is enabled... However, the idea can easily be altered to submit a form only if javascript returns true for being in an iframe. You can then pass in the $_POST data into the form so that the $_POST data is carried over (only needed if the $_POST data is referenced within the display layer of your application). Here's the basic idea:
<?php
/* Include head of your application goes here, this should do whatever
session handling code you have and all processing done to the $_POST variables */
// ~~~~~~Full Url Function - Works With Mod_Rewrite~~~~~~~~~ //
// important thing is function will grab all $_GET vars
function fullurlnav()
{
$fullurlsortnav = 'http';
$script_name = '';
if(isset($_SERVER['REQUEST_URI']))
{
$script_name = $_SERVER['REQUEST_URI'];
}
else
{
$script_name = $_SERVER['PHP_SELF'];
if($_SERVER['QUERY_STRING']>' ')
{
$script_name .= '?'.$_SERVER['QUERY_STRING'];
}
}
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on')
{
$fullurlsortnav .= 's';
}
$fullurlsortnav .= '://';
if($_SERVER['SERVER_PORT']!='80')
{
$fullurlsortnav .=
$_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$script_name;
}
else
{
$fullurlsortnav .= $_SERVER['HTTP_HOST'].$script_name;
}
return $fullurlsortnav;
}
// ~~~~~~~~~~~End Full URL Function~~~~~~~~~ //
?>
<html>
<body>
<?php
// Only run this check if user has been identified as a facebook user in their session
// or if they've been identified via the $_POST['signed_request'], which facebook sends
// upon first request via iframe.
// Doing this removes the check when it's unneeded.
if (!isset($_POST['inIframe']) && ( isset($_SESSION['inIframe']) || isset($_POST['signed_request']) ) )
{
?>
<form name="postJs" action="<?php echo fullurlnav(); ?>" method="post">
<input type="hidden" name="inIframe" value="1">
<?php
// Carry over $_POST
foreach($_POST as $key => $value)
{
echo '<input type="hidden" value="'.$value.'" name="'.$key.'" />';
}
?>
</form>
<script type="text/javascript">
<!--
// If in an iframe
if (top !== self)
{
document.postJs.submit();
}
//-->
</script>
<?php
}
elseif(isset($_POST['inIframe']) && ( isset($_SESSION['inIframe']) || isset($_POST['signed_request']) ) )
{
$_SESSION['inIframe']=1;
}
else
{
$_SESSION['inIframe']=0;
}
if ($_SESSION['inIframe']== 1){
echo 'IS in an Iframe';
}else{
echo 'IS NOT in an Iframe';
}
// echo out rest of your template code
?>
</body>
</html>
It gets a little tricky skating around your page display code output and it's workings, but that's the basic idea i have so far. Technically one could separate the form generation block from the elseif else statements below, and use those above your code before any display output, that may be easier to handle. Note that the above code is untested, just given to provide the basic idea for others with the same issue.
Related
I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well
I am fairly new to PHP and am using a couple of _GET variables to determine page layout/web service data and some other logic on the page. I am not storing the data or writing to a DB of any kind. What kind of sanitization should I be using for this?
For example, one var I'm using is like this:
$querystring = $_SERVER['QUERY_STRING'];
if(isset($_GET['semester']) && $_GET['semester'] != ''){
$listxml = simplexml_load_file("http://path/to/webservice/?".str_replace('semester','term',$querystring));
What's going on there is if the querystring has the ?semester= set and not blank then I replace it with 'term' and pass through the querystring as is to a web service URL (the web service uses the term variable but the term variable interferes with wordpress and redirects to the posts page for that 'term' (tag/category in WP) so I pass it through WP as semester and then just change it to term for the web service call.
So in this case I'm not doing anything with the _GET except passing it on as is to a web service what the web service does with the querystring is out of my hands, but should I 'prep' it in any way for them?
--
I've also got cases similar to this:
$display = '';
if (isset($_GET['display'])) {
$display = $_GET['display']; //set sort via querystring
} else {
$display = 'interest'; //set to default by interest
}
later:
<div id='byalphabet' class='<?php global $display; if($display != 'alphabet'){echo 'hide';} ?>'>
and
<div id="byinterest" class="<?php global $display; if($display != 'interest'){echo 'hide';} ?>">
--
Also using for some dynamic javascript:
$view = '';
if (isset($_GET['view'])) {
$view = $_GET['view']; //set view via querystring
}
Later:
<script>
<?php if ($view != ''){ $view = str_replace('/','',$view); ?>
jQuery('#<?php echo $view; ?>').trigger('click'); //activate view option accordion pane
jQuery('html,body').animate({'scrollTop':jQuery('#<?php echo $view; ?>').offset().top - 50},500); //scrollTo view
</script>
--
Other cases include searching an array for a _GET value array_search($_GET['major'], $slugs); and redirecting a page using:
$parts = explode('/',$_SERVER['REQUEST_URI']);
Header( "HTTP/1.1 301 Moved Permanently" ); //SEO friendly redirect
Header( "Location: http://www.site.ca/programs/outline/".$parts[3]."/" );
Edit: I have read many of the suggested similar questions that popped up but they mostly refer to using the data in some other way such as inserting into a DB.
You should always sanitize input parameters. Even if you aren't using them in the database, you are still vulnerable to cross site scripting/XSS attacks.
<?php $view = $_GET['view'] ?>
<script>jQuery('#<?php echo $view; ?>').trigger('click');</script>
For example given the above code, everything is fine if ?view=page_one because your JavaScript looks like jQuery('#page_one').trigger('click');.
But what if your querystring is ?view=hacked%27)%3B%20alert(document.cookies)%3B%20jQuery(%27%23page_one - now your javascript looks like the following on the page:
jQuery('#hacked'); alert(document.cookies); jQuery('#page_one').trigger('click');
The alert() could just as easily be an AJAX request to send auth tokens, etc to a different server.
Ultimately the type of sanitizing you do depends on the context that you are using the input. In this example, you might want to make sure you escape single quotes for example, but what is appropriate may differ between implementations.
Good article on sanitizing inputs here: http://coding.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/
I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!
To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.
What are the best practices for:
How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?
How to handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)
(An excerpt of the code I have written so far is in the history.)
Do a separate SELECT to check whether the username is already in use before attempting to INSERT.
More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.
<?php
// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();
// If the user is submitting the form ..
if ($_POST) {
// Validate the input.
// This includes checking if the username is taken.
$errors = validate_registration_form($_POST);
// If there are no errors.
if (!count($errors)) {
// Add the user.
add_user($_POST['username'], $_POST['password']);
// The user has completed.
$form_completed = true;
// Optionally you could redirect to another page here.
} else {
// Update the page title.
$title = "Registration, again!"
}
}
?>
<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>
<?php if ($form_complete): ?>
<p>Thanks for registering!</p>
<?php else: ?>
<?php if (count($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit">
</form>
<?php endif; ?>
</body>
</html>
Well, one thing you can do instead of repeating code down near the bottom is this:
if( $result === true ) {
$gPageTitle = 'Registration successful';
$response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
$gPageTitle = 'Username already taken';
$response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
trigger_error('This should never happen');
}
require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';
Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.
Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.
One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:
function error($field)
{
global $error;
if(isset($error[$field]))
{
echo $error[$field];
}
}
and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.
Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].
Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:
$pageTitle = "My Website";
if(isset($gPageTitle))
{
$pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";
Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.
I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app.
I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember.
You could pass the function call directly into the IF statement.
if (addUser($username, $passwd));
I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables.
Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it
display_title($pgTitle);
or
display_title("Registration Successfull");
or
$header->display_title("Registration Successfull")
if you like OO style better
Let me know if that helps. :)
You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
Suppose the username entered is in a post variable such as $_POST['username'].
Have your database check where that username exist:
$res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "Username exists.";
// more code to handle username exist
} else {
// ok here.
}
What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.
ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.