header location not working but stuck in page - php

so I have a button
<input type="button" value="add" onclick="document.location.href='add.php?myUcode=<?=$row['ucode'];?>'" />
to another page (let's call it Page1). in Page1, I want to add a value to $_SESSION['employees'] and then redirect it back to home.php. but when I click the button, it gets stuck in add.php. there is no echo or whitespace before I call the Header method. now I have no idea what is wrong with my code :
<?php
session_start();
if ($_POST['tambah_ucode']) {
if (isset($_SESSION['jum_petugas'])) {
$_SESSION['jum_petugas'] = 1;
$ctr = $_SESSION['jum_petugas'];
} else {
$ctr = $_SESSION['jum_petugas'];
$ctr++;
$_SESSION['jum_petugas'] = $ctr;
}
$_SESSION['ucode_petugas'][$ctr] = $_POST['tambah_ucode'];
header('Location: localhost/hrm2.1/lembur_add.php');
}
?>

Try this,
header('Location: lembur_add.php');
exit;
OR
header('Location: http://localhost/hrm2.1/lembur_add.php');
exit;

header('location:localhost/hrm2.1/lembur_add.php')
without space

Try the following
header('Location:http://localhost/hrm2.1/lembur_add.php');

Instead of header(...), try
echo "<script type='text/javascript'> document.location = 'yourLocation'; </script>";

Related

How do I Redirect to Login page using PHP

I am trying to redirect my php login page so that if user is authorised, it goes to a page (r_index.php) and if the user isn't authorised they go back to the login page (login.html).
This is my code:
<?php
if ("password"=="$password") { // Start the condition ?>
Manage classes
<?php } // End the condition ?>
<?php if ("password"=="") { ?>
Login
<?php }
?>.
What am I doing wrong? How should I resolve it?
replace your code with this:
<?php
if ("password"== $password) {
header("location:r_index.php");
}
else if ($password=="") {
header("location:login.html");
}
?>
If you want to redirect you should use:
header('Location: http://www.example.com/r_index.php');
in your code.
<?php
$accessGranted = false;
if($password == 'password') {
$accessGranted = true;
}
if($accessGranted) {
header('Location: r_index.php');
}
else {
header('Location: login.html');
}
exit;
Actually your syntax is wrong, else there is no problem of using HTML inside php. It will work well and good.
Just make sure not to put your variable inside quotes, and change the statement as follows:
if($password=="password")
and
if($Password==" ")

Click the button, save the data and go to next php page

I don't know what is the problem. After i click the button, it only the data into database but will not go to next php page. Help me find out what is problems. Thank you.
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
header('Location: mcreport.php');
if($AddMCResult)
echo "<script>alert('Record Added.');</script>";
}
//button
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit"/>
Try this
<?php
if(isset($_POST['btnSubmit']))
{
$txtName=$_POST['txtName'];
$txtFrom=$_POST['txtFrom'];
$txtTo=$_POST['txtTo'];
$txtReason=$_POST['txtReason'];
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('$txtName','$txtFrom','$txtTo','$txtReason')";
$AddMCResult = mysql_query($AddMCQ,$link);
if($AddMCResult)
{
echo "<script language=\"JavaScript\">\n";
echo "alert('Record Added.');\n";
echo "window.location='mcreport.php'";
echo "</script>";
}
}
?>
Your "Problem" is the result in $AddMCResult
After your have use header('Location: mcreport.php');
Your Script redirect to the given url and the result in $AddMCResult is not given any more
So a quick and dirty solution could be
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
$_SESSION['AddMCResult'] = $AddMCResult;
header('Location: mcreport.php');
}
AND on mcreport.php
if(isset($_SESSION['AddMCResult']) && $AddMCResult)
echo "<script>alert('Record Added.');</script>";
...
But check, that session_start() was called on both files ...
Check Carefully Table Name and Passing Parameters - Through one to another page - see get and post method-
<?php
include 'config.php';
$submit="submit";
$page = $_SERVER['PHP_SELF'];
$sl_no=$_POST['sl-no'];
$f_name=$_POST['f_name'];
$l_name=$_POST['l_name'];
if($submit)
{
$sql = "INSERT INTO table_name(sl_no,f_name,l_name) values('$sl_no','$f_name','$l_name')";
$result = mysql_query($sql);
echo "Thank you! Information entered.\n";
}
else
{
echo "There Is Something Going Wrong While Insertion";
header('Location: error.php');
}
After your header put die() like
header('Location: mcreport.php');
die();
And better you use Absolute urls.Also you can use exit() instead of die().

Javascript alert and php header

I got a little problem. When I got my PHP script without header it's fine, I am getting javascript alert box. But when I use header before alert it's not working. It's redirecting me like it should, but it's not showing any box. Could someone help me?
if ( $pkt < 1 OR $user_id == 0) {
header("Location: http://dunno.com/file.php");
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('$message');
</SCRIPT>";
mysql_close();
}
And here's the one which work (but without heading)
if ( $pkt < 1 OR $user_id == 0) {
$message = 'This is a message.';
echo "<SCRIPT> //showing me
alert('$message');
</SCRIPT>";
mysql_close();
}
I would be thankful for help :)
#edit Maybe is there any command to make alert wait until whole browser load? (if it's the problem)
Maybe try redirect using JavaScript.
if ( $pkt < 1 OR $user_id == 0) {
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('$message')
window.location.replace('url of the page');
</SCRIPT>";
mysql_close();
}
I know this is a old post, but here is how I made it in a similar example. This example checks if the administrator has logged in from a specific IP address, if it returns false it should redirect the user back to the login page and show an error message.
User has logged in page:
if ($_SERVER['REMOTE_ADDR'] == "ip address"){
$admin = True;
}else{
session_start();
$_SESSION['errorMessage'] = "WARNING: You dont have access to this area.";
header("Location: login.php");
}
login.php:
session_start();
if(isset($_SESSION['errorMessage'])){
echo "<script type='text/javascript'>
alert('" . $_SESSION['errorMessage'] . "');
</script>";
//to not make the error message appear again after refresh:
session_unset($_SESSION['errorMessage']);
}
this is a redirect:
header("Location: http://dunno.com/file.php");
the code below wont work
Your error is in the structure of your code. PHP, even in OOP is procedural and will run each line one after the other. So the way you've structured your code means the page is redirected before your echo. A better method is to use the javascript alert box to redirect your page using:
var prompt=window.confirm("message here. \r\n"+"Do you want to redirect?");
if(prompt)document.location.href='http://dunno.com/file.php');
Aaroniker is correct with the redirect comment. One way to make it work would be to send the message with a session variable and then add the message creation to the next page like so.
session_start();
if ( $pkt < 1 OR $user_id == 0) {
$_SESSION['message']= "this is a message";
header("Location: http://dunno.com/file.php");
On file.php:
session_start();
echo "<SCRIPT> //not showing me this
alert($_SESSION['message']);
</SCRIPT>";
mysql_close();
}
Another option would be to pass them with you header. Like so:
if ( $pkt < 1 OR $user_id == 0) {
$message= "this is a message";
header("Location: http://dunno.com/file.php?message=" . $message . ");
Then on file.php:
echo "<SCRIPT> //not showing me this
alert($_GET['message']);
</SCRIPT>";
mysql_close();
}
Use $_SERVER 'php_self'. It will allow you to create script on same page where you want alert. In this way you won't have to add header.
Here's an example:
<form name="login" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" accept-charset="utf-8" class="form_class">
<ul>
<li>
<label for="usermail">Username</label>
<input type="text" name="username" placeholder="Enter username" required>
</li>
<li>
<label for="password">Password </label>
<input type="password" name="password" placeholder="Enter your password" required>
</li>
<li id="custom">
<input type="submit" value="Sign In">
</li>
</ul>
</form>
$sqluname="root";
$sqlpword="hrhk";
$database="registration";
$server="127.0.0.1";
$db_handle=mysql_connect($server,$sqluname,$sqlpword,$database);
$db_found = mysql_select_db($database, $db_handle);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uname = $_POST["username"];
$pword = $_POST["password"];
$ulength=strlen($uname);
$plength=strlen($pword);
if($ulength > 5){
$sqlquery="SELECT * FROM members WHERE username='$uname' AND password='$pword'";
$result=mysql_query($sqlquery);
$num_rows=mysql_num_rows($result);
if ($num_rows >0) {
echo "<script>alert('Logged In');</script>";
session_start();
$_SESSION['sid']=$uname;
header("location:Yahoo/yahoo.php");
}
else{
echo "<script>alert('Wrong Username or Password!');</script>";
}
}
else{
echo"<script>alert('Username should be greater than 5 characters.');</script>";
}
}
?>
The below header function will run a 302 redirect by default and redirect the client to http://dunno.com/file.php so any code after the code begin processed after the header function will not be seen as the client is redirected from the page this code is on.
header("Location: http://dunno.com/file.php");
Please read up further on the header function here: http://www.php.net/manual/en/function.header.php
You could make you program sleep/wait for a few seconds(lets say 10 seconds for this example) before redirecting if you need the message to display like so:
if ( $pkt < 1 OR $user_id == 0)
{
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('".$message."');
</SCRIPT>";
sleep(10);
mysql_close();
header("Location: http://dunno.com/file.php");
}

redirect based on the keyword the user entered

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();
}

Refresh button on Browser

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.

Categories