Accessing database for mobile web applications - php

I have a question about login and accessing database for mobile web applications.
Namely, the fact that all the pages are usually in one page separated by ids, how do you send form data using PHP? There are no separate files to send data to.
Doesn't opening a connection at the top of the HTML file without logging in cause a security problem? If they do not login successfully, you are essentially redirecting to the same HTML file.
If someone could redirect to a tutorial (which I can't seem to find online) or give an overview, that would be awesome.
<?php
//1. Open connection
//2. Select database
?>
<html>
<body>
<section id="page1">
<form action="page2" method="POST"><!-- since the data needs to be send to #page2, do I just POST to the same html file? -->
</form>
</section>
<section id="page2">
<?php
//3.query database
//4. display results
?>
</section>
<section id="page3">
</section>
</body>
</html>
<?php //5. close connection?>

1) You can keep separate files in PHP, they don't have to be in the same page. For example, you have a file named login.php.
<?php ?>
<html>
<form action="index.php" method="post>
<input type="text" name="username"/>
<input type="password" name="pasword"/>
</form>
</html>
Then in your index.php file you would have something like this.
<?php
if($_POST['username']=="admin" && $_POST['password']=="admin")
//query database
//display results
?>
So you don't have just one file containing different pages.
2) You can include a main.php file in all your pages and check if user is logged in, if not, redirect him to some other page. In adition you could learn a little bit about session variables.
<?php
include("main.php");
?>
In your main.php
<?php
session_start();
if(!$_SESSION['islogged'])
header("location: otherpage.php";)
?>
So if the user is logged in there will be no redirection but other way it will.
Hope this helps you.

1)
Check out the following link. http://www.w3schools.com/php/php_post.asp
It explains how to access form data that has been sent to your php page. You need a decent understanding of HTML before you ever start working with PHP.
2)
The user isn't the one logging in. They never see the php code. It stays on the server. What they see is HTML. The connection is so the php page can connect to the database and retrieve information.

Related

login/logout, config, session inactivity codes in php

I have a php file admin_trace.php in which I have integrated everything (config, session inactivity, login/logout, username/password verification and JS codes).
The php file admin_trace.php belongs to the following url http://example.com/admin_trace.php (let us suppose)
In the php file admin_trace.php, I have
a. database configuration code
b. session inactivity code (which forces logout of the page when there is no activity)
c. login/logout code
d. username/password verification code
e. if user is not logged in then it it will display the login page.
// Is user logged in?
<?php
if(!isset($_SESSION['pageadmin'])){ ?>
<form action="/admin_trace.php" method="post">
<div style='width:350px;'>
<fieldset>
<legend>Login</legend>
<div>
<label for="user_name">User Name</label>
<input type="text" name="user_name">
</div>
<div>
<label for="user_pass">Password</label>
<input type="password" name="user_pass">
</div>
<div>
<button type="submit">Login</button>
</div>
</fieldset>
</div>
</form>
<?PHP } else { ?>
f. JS code at the bottom
The issue which I am having right now that all my codes are in one file admin_trace.php which is making things difficult and making some part of the code (like JS) not working
Problem Statement:
I am wondering what would be the best way to architect any login form page that has config code, session inactivity code, login/logout code, username/password verification code and JS code. When I say architect I meant to say the relative locations of the files w.r.t. to admin_trace.php where config code, session inactivity code, login/logout code, username/password code etc will be placed.
PHP has the ability to split code into multiple files. You can bring this code in conditionally with if statements via the include and require statements (and corresponding include_once and require_once.

Permanently post some form data on another page

The question looks quite similar, however it's not been answered anywhere. What I want is I'm designing a website with login option. There is a particular page named "announcements.php" where I want site visitors to be able to see announcements made by admin. So, In order to do so I have made a page which only admin can access and add an announcement ("newbroadcast.php"). The page contains a form where admin can write an announcement and submit it. However that announcement should be accessible to all the users which visit announcements.php
Code (newbroadcast.php)
<div class="newbroad">
<img src="content/images/broadcast.png" align="center" width="160px" height="160px">
<form method="post" action="announcements.php">
<strong>BROADCAST : </strong>
<input type="text" name="broadd" placeholder="Write your new announcement here...">
<input type="submit" name="submit">  <input type="reset" name="reset">
</form>
</div>
Code (announcements.php)
<div class="markcontent">
<center><h1 class="whiteboard">CDC DEPARTMENT WHITEBOARD</h1></center>
<hr>
<?php
$mynewbroad=$_POST["broadd"];
?>
<marquee behavior="scroll" direction="down" scrollamount="2" onmouseover="this.stop();" onmouseout="this.start();">
<center>
<?php
echo $mynewbroad;
?>
</center>
</marquee>
What is actually happening?
Everything works fine, however when admin writes a new announcement or broadcast it gets posted on the page ("announcements.php"), where I actually want to post it. However that is not permanent. Whenever I open the page itself it shows an error => Undefined index: broadd
Is their any way to permanently show the broadcasts made by admin? What is the possible solution to this error?
POSTing data to a PHP page does not automatically "store" the information you are posting to it. It merely sends the data from newbroadcast.php to the announcements.php, and announcements.php can do what it is programmed to do with the data. In your case, announcements.php is displaying the data - but not storing it for future.
To store the data for future, you must save it somewhere on the server and re-factor announcements.php to check on the server for such data, and (if such data is found) display all the announcements via some sort of loop.
So how to store the announcements?
You can use PHP commands such as fwrite or file_put_contents to save the announcements into a specific folder, and then write a loop to read all the file in that folder and spit them out onto the page.
But the better way is to use a database.
References:
http://www.tutorialrepublic.com/php-tutorial/php-mysql-insert-query.php
https://www.youtube.com/watch?v=mpQts3ezPVg

Prevent browser form-resubmission alert

How can I avoid the the browser form-resubmission alert?
This question seems to have been discussed a lot here on SO, for example:
Preventing form resubmission
Prevent Back button from showing POST confirmation alert
Never ever respond with a body to a POST-request
What I do not get from the previous discussion, is how I can use the posted data and incorporate it into the html. The previous links discuss how to use the php header function to send a get request to itself. But when sending this get request, the posted data will no longer be available to the new page, (since we cannot use the php post method..)
I would like to do this without using the php or javascript session storage technique (or saving the posted data to a temporary mySQL database).
For a simple example:
<html>
<body>
<form action="post.php" method="post">
User name: <input type="text" name="user"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
where post.php is:
<html>
<body>
<?php
echo "<p>".$_POST['user']."</p>";
?>
</body>
</html>
Pressing CTRL-R in google chrome on the second page brings up the alert.
Do a redirect from post.php. Save data in session or in database and retrieve from redirect page.
Example Scenario:
Submit the form
Save the user record to db, get the id of the new record e.g. in $id
redirect using header, something like:
header('Location: result.php?user_id='.$id);
get the user record from db, with the provided id and show it to the
user.
Use this:
<script>
if(window.history.replaceState)
{
window.history.replaceState(null,null,window.location.href);
}
</script>
you may rewrite the browser history object
history.replaceState("", "", "/the/result/page");
See this

PHP is not passing my user entries

Hi I'm learning php of a tutorial and these are my two files. I browse to my apache2 server via http://myservers-ip/form2.php
fill out the forms and hit the submit button, it calls my result.php page, but all it displays is "Hi ." where it should be like "Hi (userentry)."
Please help :-(
form2.php:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter your name</h1>
<form method="post" action="result.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
and my result.php
Hi <?php print $username; ?>.
Using apache2 and mysql running on my box.
I'm not sure if the source code is correct or if there might be a misconfiguration? if so which config files would you need?
Thanks
Data sent via a form with POST action will be in the superglobal $_POST array. You would want to sanitize it before trying to use it for anything, but just starting with $_POST['username'] will get you closer to your end goal.
Edit: Whatever tutorial you are using, abandon it. It's clearly waaaaay outdated.
You're sending data from form via post so you need to get them in your result.php file from POST superglobal like so:
Hi <?php print $_POST['username']; ?>.
The data is being sent to results.php via POST method.
All post params are stored in $_POST param. So to get user name you need to get it from $_POST, in results.php. E.g:
<?php
// file: results.php
if (isset($_POST['username']){
echo "Hi, {$_POST['username']}.";
} else {
echo "No user name."
}

Displaying error messages based on form data in php

I'm trying to create a pretty standard user creation form for a website I'm working on, but my PHP amateur status is preventing me from accomplishing my goal.
Essentially what I want to do is have the user fill out a registration form, and then have a server-side script attempt to register that information. If the registration succeeds, then the user will be redirected to a page telling them to look for a verification email. If that registration fails (the email address is already in the system, not matching passwords, whatever), I would like to reload the page, but display the error message to the user above the form. Currently the form I have is being echoed out of a php file which is separate from the HTML from where the page is stored. My three questions are this.
From what I've read, the way to redirect users on success is to use header("Location: http://foo.com"). Is that correct, or is there a more proper way to do it?
How can I get access to the error(s) that caused the first user to fail? I've read that setting a session variable is a poor idea for a number of different reasons, but without that how can I keep track of the errors thrown by the form validation? Should I just create a global $errors variable that I clear every time I echo the registration form?
For this case, should the page that the registration form is on have a .html extension or a .php extension, or does it not matter? More generally, is there any rule for when a page is .html vs .php/.asp/something else?
Edit: added code below. Note, the form is rendered from a file called in ../views/register_form.php (I assume this is how I'd work on getting something MVC-like in PHP)
The page that the form is rendered on (called index.html)
<body>
<script type="text/javascript"> <!-- put the jquery load stuff into here -->
$(function(){
$("#registration_form").load("views/register_form.php");});
</script>
<div class="topbar"><!-- Create the top bar layout-->
<div class="fill">
<div class="container">
<a class="brand" href="#">Website!</a>
<ul class="nav">
<li class="active">Home</li>
<li> About</li>
</ul>
<form action="scripts/login_user.php" method="post" class="pull-right">
<input class="input-medium" id="login-email" type="text" name="email_addr" placeholder="email" />
<input class="input-medium" id="login-password" type="password" name="password" placeholder="password" />
<button class="btn" type="submit">Login now!</button>
</form>
</div>
</div>
</div>
<div class="container">
<div class="content">
<div class="page header">
Page header!
</div>
<div id="registration_form">
</div>
The script
if(//some of the data in the form isn't set)
{
//Set error conditions based on missing data
}
$confirm_password=$_REQUEST['confirm_password'];
$password=$_REQUEST['password'];
if($confirm_password != $password){
//report passwords don't match}
$email_addr=$_REQUEST['email_addr'];
$first_name=$_REQUEST['first_name'];
$last_name=$_REQUEST['last_name'];
try
{
$successful_creation=create_user_and_send_verification_email($email_addr, $password, $first_name, $last_name);
}
catch(Exception $e)
{
/*SQL errors are caught here*/
}
if($successful_creation==FALSE)
{
//If it couldn't be inserted for a non exception generating reason. If I get here, should I echo a page that has those errors printed, but is otherwise identical to the previous one?
}
else
{
//redirect to a "wait for a verification email" page
}
Yes that is the correct way to do it, but all headers must be sent before you try to render anything to the page. Also, you don't necessarily need to redirect, you can generate the correct output with PHP depending on the form data.
The script that receives the submitted form should check the submitted data for errors and can then output those errors to the page that is generated by that script.
If the page has php code in it then usually it needs a php extension unless your server is set up to process html pages as php. Otherwise, .html is fine.
I hope that helps point you in the right direction, although a more focused question with the code you have up to now would generate a better answer.
There are lots of tutorials on this on the web, you should follow one of those and experiment.
why dont you write the server side code on the same page and for every form input use a flag
for eg: if email is not valid $email=1.
den after submission if any flag is initialized,check for the flag and if $email=1 echo error else redirect.

Categories