I have created a page called profile.php that gets a value from mainpage.php, by using "get" method. But, If the value that was sent from mainpage.php is empty or wrong, the page redirects to the mainpage.php. However, I used "post" method in profile.php that allows users to post something in profile.php. So that If the user submits something, profile.php reloads and reloading profile.php makes the variable, that i get from mainpage, empty and directs the page to mainpage.php unwillingly.How can i fix it? Codes;
$another_user = $_GET['username'];//gets a value from mainpage.php
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."'");
$sent = mysql_fetch_array($check);
if(!$sent)
{
header('Location: mainpage.php');
exit();
}
//some codes around here
<form action="profile.php" method="post">
Commet: <input type="text" name="comment" placeholder = "comments?"/>
<input type="submit"/>
</form>
<?php
if(isset($_POST['comment'])&&!($_POST['comment']=""))
{
$writing = $_POST['comment'];
echo $writing;
}
Thanks
To start with you have a syntax error in your second line, as the colors show you already. So change it into:
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."')";
There are many solutions to your problem. One of them could be to verify which page the user is coming from. If this is mainpage.php you can verify the username and if this is profile.php you should check the comment variable.
You can make use of the $_SERVER['HTTP_REFERER'] variable to check which is the referer. So something like:
if ($_SERVER['HTTP_REFERER'] == "http://www.domain.com/mainpage.php") {
//do your username check
}
else if ($_SERVER['HTTP_REFERER'] == "http://www.domain.com/profile.php") {
//do your comment check
}
Another and maybe easier way would be to make sure that your $_POST['comment'] has not been set when dealing with the username.. Like this:
if (!isset($_POST['comment'])) {
$another_user = $_GET['username'];//gets a value from mainpage.php
$check = mysql_query("SELECT * FROM users WHERE user_name = '".$another_user."'");
$sent = mysql_fetch_array($check);
if(!$sent) {
header('Location: mainpage.php');
exit();
}
}
else {
//...
}
Related
i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)
i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.
I have a page where the user can enter what he is selling and be redirected to that page. I know the mysql LIKE '%%' function but I am not using database. If the case matches, I just would like to redirect to that page. How is that possible? whether it is javascript or php?
For examples: if the user enters "laptop" then he/she will be redirected to laptop.php(I have the pages). How can I do that?
The form structure:
<form class="sellcont" action="" method="post">
<input type="text" name="selling" >
<input type="submit" name="submit" value="Next" class="myButton">
</form>
<?php if(isset($_POST['submit'])){
$sell = $_POST['selling'];
if(!empty($_POST['selling'])){
//This is where I am lost.
}
}
After Comments
You use php header to redirect and check the input ($_POST['selling']) with in_array if its a good input.
$goodinput = array("laptop", "pc", "mac", "cellphone");
if(!empty($_POST['selling'])){
if (in_array($_POST['selling'],$goodinput)){ //checks if user input is a good input
header('Location: http://www.yoururl.com/'.$_POST['selling'].'php');
exit();
} else {
header('Location: http://www.yoururl.com/wedonthavethatpage.php');
exit();
}
}
Suggestion:
Instead of creating individual pages e.g.: laptop.php you store similar values in a database and create dynamic pages.
PHP code should be like this:
<?php if(isset($_POST['submit'])){
$sell = $_POST['selling'];
if(!empty($_POST['selling'])){
header('location: ./'.$_POST['selling'].'.php');
}
else {
header('location: ./index.php'); //index.php is PHP files on which user enter selling item
}
}
?>
You could also use the code in this answer:
How can I check if a URL exists via PHP?
to see if the what the user typed in is available. If so, do the redirect, if not, send it to an alternate page.
E.g.
if(!empty($_POST['selling'])){
$file = 'http://www.yourdomain.com/'.$_POST['selling'].'.php';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
if ($exists) {
header(sprintf('Location: %s', $file);
}
else {
header('Location: http://www.yourdomain.com/other_page.php');
}
exit();
}
// script.js
$(document).ready(function(){
$(".loginProzor").hide();
$(".login").click(function(){
$(".loginProzor").fadeToggle(300);
});
$("#prijavi").click(function(){
if($("#user").val() == "" || $("#pass").val() == ""){
$("#labelGreska").html("Unesite korisničke podatke");
}
else{
$.post($("#forma").attr("action"), $("#forma :input").serialize(),
function(data){
$("#labelGreska").html(data);
});}
$("#forma").submit(function(){
return false;
});
});
});
// form
<form id="forma" action="login.php" method="post">
<label>Korisničko ime</label><br>
<input type="text" name="user" id="user"><br>
<label>Lozinka</label><br>
<input type="password" name="pass" id="pass"><br>
<input type="submit" value="Prijavi se" id="prijavi">
<label id="labelGreska"></label>
</form>
//login.php
<?php
include 'funkcije.php';
include 'spojiBazu.php';
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!$user){
$greske[] = 'Unesite korisničko ime';
}
$pass = md5($pass);
$ucitaj = mysql_query("select * from login where username = '$user' and password = '$pass'");
session_start();
if(mysql_num_rows($ucitaj) === 0){
echo 'Korisnički podaci nisu validni, molimo pokušajte ponovo.';
}else{
$korisnik = mysql_query("select username from login where username = '$user'");
$podatak = mysql_result($korisnik, 0);
$_SESSION['user'] = $podatak;
header("Location: index.php");
}
?>
Hello
I'm learning web development and I ran into a problem. I created simple login form. It evaluates some errors using jQuery and the rest of errors are evaluated using PHP. Everything works except Header command in PHP. When user succesfully logs in, header command should redirect to index.php so user can verify it is logged in, but in this case header tag don't work.
Before applying jQuery (all errors were handled by PHP) header command worked with no problems. Can you tell what's wrong here?
Details,
Since AJAX happens "behind the scenes" (so to speak) your redirect will just interrupt the response to your javascript handler. So PHP cannot redirect your browser now, jQuery can. So use jQuery to redirect the user.
You'll need to return the URL and have your callback kick the browser to a new location.
On this note, since you have to return data to the front end, you'll want to add a status or similar variable so that you can switch your front end behavior based on whether the call "failed" or not.
Exactly what Marc B pointed,
"You're doing the ajax call - the php header will redirect the ajax response... not the page that the user is currently sitting on. You will have to modify your javascript code in the client to change the location."
A javascript redirect is as simple as window.location.href = "http://mylocation";.
Solution to your problem,
JQUERY
// script.js
$(document).ready(function(){
$(".loginProzor").hide();
$(".login").click(function(){
$(".loginProzor").fadeToggle(300);
});
$("#prijavi").click(function(){
if($("#user").val() == "" || $("#pass").val() == ""){
$("#labelGreska").html("Unesite korisničke podatke");
}
else{
$.post($("#forma").attr("action"), $("#forma :input").serialize(),
function(data){
if(data=="success"){
window.location.href = "index.php";
} else{
alert("login failed");
}
});
}
$("#forma").submit(function(){
return false;
});
});
});
PHP
<?php
include 'funkcije.php';
include 'spojiBazu.php';
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!$user){
$greske[] = 'Unesite korisničko ime';
}
$pass = md5($pass);
$ucitaj = mysql_query("select * from login where username = '$user' and password = '$pass'");
session_start();
if(mysql_num_rows($ucitaj) === 0){
echo 'failed';
exit;
}else{
$korisnik = mysql_query("select username from login where username = '$user'");
$podatak = mysql_result($korisnik, 0);
$_SESSION['user'] = $podatak;
echo "success";
}
?>
from http://www.php.net/manual/en/function.header.php
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called.
You can try with a javascript redirection or remake your source code with the header at the begining
header() will not work after output has been echoed to the screen.
Check funkcije.php and spojiBazu.php to see if any echo happening. If they are you need to find a way to remove the echos from those to included files before you call header() in login.php.
I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.