PHP - Echo A Message On Header Location Return
I have this working script below. I never managed to turn it into a function... I think it's because there's classes in it.
I stopped that investigation and instead I choose to:- keep it on another page, trigger it with the a <form> button, then return to the form page using header location. This is probably much more elaborate than it needs to be... but it seems to be working fine.
I'd like to print out "email sent" if successful. The collection of confusion at the end of this script, is me trying to get it to return the - "email sent" message <index.php> <?php require 'includes/PHPMailer.php'; require 'includes/SMTP.php'; require 'includes/Exception.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(); $mail->isSMTP(); $mail->Host = "smtp.gmail.com"; $mail->SMTPAuth = "true"; $mail->SMTPSecure = "tls"; $mail->Port = "587"; $mail->Username = "email@gmail.com"; $mail->Password = "pass"; $mail->Subject = "Test email using PhPmailer"; $mail->setFrom("email@gmail.com"); $mail->isHTML(true); //$mail->addAttachment('img/movie.mp4'); $mail->Body = "<h1>This is a HTML heading</h1></br><p>This is a html title</p>"; $mail->addAddress("email@gmail.com"); if ($mail->Send() ) { echo "Email sent..!"; } else{ echo "Error..!"; } $mail->smtpClose(); ob_start(); $Message = urlencode("Email Sent"); header("Location:EmailBut.html?Message=".$Message); die; ob_flush(); ?> The stuff at the beginning of this next script is me trying to get it to print out email sent. I can get it to return the message in the URL but it won't print out. <EmailBut.html> <?php ob_start(); if(isset($_GET['Message'])){ echo $_GET['Message']; } echo $_GET['Message']; ob_flush(); ?> <html> <body> <form action="index.php" method="POST"> <button type="submit">Send</button> </form> </body> </html> Can you please give me a push in the right direct here? Edited January 30, 2020 by JonnyDrillerSimilar TutorialsI have a class ServerBridge which is used to proxy browser ajax requests received by a web server to another API server. To update a record (or create a record is similar): Browser client makes PUT request to web server. Web server modifies the uri path and passes the body plus headers connection, accept, accept-encoding, accept-language, content-type, content-length only to the API server. The API server does work and returns the location of the resource on itself to the web server. The web server modifies the location header to point to the resource location on itself, and returns all received headers except Date, Server, X-Powered-By, Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers to the browser client. Browser client makes another undesired PUT request to web server.Why is step 5 occurring and how do I prevent it? I don't really mind the browser client making another request to the resource, but it would need to be GET and not PUT. Also, is my white-list headers to forward to api server and black-list headers to return to browser client appropriate? I haven't posted the ServerBridge script (but can if needed), but did include the requests and headers related to the browser client, web server, and api server below. Browser client JavaScript $('.edit-record').simpleEdit('/api/accounts'); jQuery.fn.extend({ simpleEdit: function(url, options) { var dOptions={type: 'text', ajaxOptions: {type: "PUT"}, placement: 'right', send: 'always' }; options=options?options:{}; return this.each(function() { var $t=$(this); var o=Object.assign({ url: url+'/'+$t.closest('tr').data('id'), title: 'Enter '+$t.data('name') }, dOptions, options); $t.editable(o); }); } }); Web-server index.php $c['serverBridge'] = function ($c) { return new \Greenbean\ServerBridge\ServerBridge( new \GuzzleHttp\Client([ 'base_uri' => $c['settings']['server']['scheme'].'://'.$c['settings']['server']['host'], 'headers' => ['X-Secret-Key' => $c['settings']['server']['key']], 'timeout' => 30, 'allow_redirects' => false, ]), new \Greenbean\ServerBridge\SlimHttpClientHandler() ); }; $app->put('/api/accounts/{id:[0-9]+}', function (Request $request, Response $response) { return $this->serverBridge->proxy($request, $response, function(string $path):string{ return substr($path, 4); //Remove "/api" from uri }, function(array $headers):array{ if(!empty($headers['Location'])) { $headers['Location'] = ['/api'.$headers['Location'][0]]; //Add "/api" to redirect header if it exists } return $headers; } ); }); $app->POST('/api/accounts/{id:[0-9]+}', function (Request $request, Response $response) {/*Similar to PUT*/});
<?php class ServerBridge { public function __construct(\GuzzleHttp\Client $httpClient, ?HttpClientHandlerInterface $httpClientHandler=null){ $this->httpClient=$httpClient; $this->httpClientHandler=$httpClientHandler; //Whether to use Slim or Sympony HTTP requests and responses } public function proxy($clientRequest, $clientResponse=null, \Closure $modifyPath=null, \Closure $modifyHeaders=null) { //Accept a Slim or Sympony HTTP request, forward it to API server via cURL, and return the cURL response //$modifyPath will modify REQUEST_URI before sending to API server //$modifyHeaders will modify response headers before sending to calling client return $response; } } API Server index.php $app->put('/accounts/{id:[0-9]+}', function (Request $request, Response $response, $args) { $this->accounts->update($args['id'], $request->getParsedBody()); return $response->withRedirect('/accounts/'.$args['id'], 302); }); $app->post('/accounts', function (Request $request, Response $response) { $account = $this->accounts->create($request->getParsedBody()); return $response->withRedirect('/accounts/'.$account['id'], 302); });
Web Server
I was wondering if it's possible to retain loaded files and the current error setttings after a
header("Location: xxxx.php")is issued, for example in this: // Start up the session - not used yet but there just in case session_start(1); // Enable the Autoloader and initialise it require_once 'Autoloader.php'; Autoloader::init(); // Check if the application has been installed yet ---------------------------- if(!file_exists('Engine/config.php')){ session_write_close(); header("Location: install/index.php"); die(); }And I get a class not found error when I open the install/index.php session_start(1); // @todo: Disable this in the production version .... I already did this in the main index -- do I have to do this on all pages that may error? error_reporting(E_ALL & ~E_STRICT); ini_set("display_errors",1); // Because we jumped here, we have to reinstall the autoloader -- why? require_once '../Autoloader.php'; Autoloader::init();While I can understand I wouldn't want this if I was firing off to a completely different site, is there anyway to retain the settings within the same server environment or do I have to reset everything as above. I even tried using session in the hope that this would 'remember' but it didn't work. Hi! I'm not a very experienced PHPer. I keep getting this error... Warning: Cannot modify header information - headers already sent by (output started at /home/content/j/2/6/j26183102/html/referral.php:11) in /home/content/j/2/6/j26183102/html/referral.php on line 295 Any suggestions? It works on one server but not my customers godaddy hosting site. Hi, Im new to all this coding stuff but get by ok with help from the wealth of info on the internet however in this instance i cant solve a PHP redirect issue im having. Ive got a very simple php script to redirect to a secure paypal item link using the header function. header("Location:https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=XYX96W3MSFQZ6"); The problem is when the script is called upon in IE it loops endlessly however works perfectly in Chrome, Firefox, Opera and the Andriod stock browser. I originally tried the redirect directly within the meta tag although this failed on all browsers so now i have the meta tag point to this PHP file. (The meta tag is in a script that submits form data and displays a temporary 'redirecting...' page. Has anyone expirenced this problem before or know of ways to fix it for IE? Could it be an issue with security in IE because the paypal link is secure? Any help would be greatly appreciated. I've made a Login Script and I'm trying to make it re-direct me to the Homepage after the login is complete. However, it's doing nothing at all... Code: [Select] <?php require('./includes/header.php'); require('./includes/functions.php'); ?> <div id="loginHolder"> <div id="title"></div> <h2>Login</h2> <hr /> <?php if(@$_POST['submit_login']) { echo '<div id="loginBox">'; $username = protect($_POST['username']); $password = protect(encrypt($_POST['password'])); $loginCheckQ = mysql_query("SELECT * FROM `users` WHERE `username`='".$username."'"); $loginCheckF = mysql_fetch_assoc($loginCheckQ); $dbusername = $loginCheckF['username']; $dbpassword = $loginCheckF['password']; if($username == $dbusername && $password == $dbpassword) { $_SESSION['loggedUser']=$username; echo '<font color="green">You have successfully logged in as '.$username.'.</font>'; header('location: index.php'); } else { echo '<span>Incorrect Username or Password.</span>'; } echo '</div>'; } ?> <form action="login.php" method="POST" autocomplete="off"> <table cellspacing="0" cellpadding="0"> <tr> <td>Username: </td><td><input type="text" name="username" /></td> </tr> <tr> <td>Password: </td><td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Login" class="submit" name="submit_login" /></td> </tr> </table> </form> </div> <?php require('./includes/footer.php'); ?> It works perfectly fine on Localhost, but when I upload it, it doesn't work. this little piece of code doesn't seem to work: Code: [Select] if($rs_teamcheck['team_id'] != $team{ header( "Location: http://domain/page.php" ) ;} If I replace the header location part with an echo the output is fine, so why isn't the redirect working? Hi Everyone, I'm having a bit of a problem if someone could help me with? I have a simple registration form with fields userid, username, password, clientaddress So when the user logs in with their username and password it will redirect to their client address but I cant get the redirect working. Here is my code: Code: [Select] $clientaddress = trim($_POST['clientaddress']); $_SESSION['start'] = time(); header("Location:$clientaddress"); exit; } also note if I add: Code: [Select] $clientaddress = 'http://www.google.com'; it redirects ok to google. It's getting the field from the database I think thats the problem Can somone help it just wont redirect to the client address Hello everyone. I want to use php to obtain the 'location' value from a header of a url. However, when I use get_headers() it automatically follows the redirect and gives me the header information of the new page. I don't want this, I need the headers of the original page. (I need the value of the 'location' variable in the header). Hope you can help me out. I dont understand why my header(Location) isnt working. Does any one see why?
<?php include 'core/init.php'; logged_in_redirect(); include 'includes/overall/header.php'; if (empty($_POST) === false) { $required_fields = array('first_name', 'last_name', 'username', 'password', 'password_again', 'email'); foreach($_POST as $key=>$value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'All field are required'; break 1; } } if (empty($errors) === true) { if (user_exists($_POST['username']) === true) { $errors[] = 'Sorry, the user \'' . $_POST['username'] . '\' is already taken'; } if (preg_match("/\\s/", $_POST['username']) == true) { $errors[] = 'Your username can not have spaces'; } if (strlen($_POST['password']) < 6) { $errors[] = 'Your password must be at least 6 characters long'; } if ($_POST['password'] !== $_POST['password_again']) { $errors[] = 'Your passwords do not match'; } if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'A valid email address is required'; } if (email_exists($_POST['email']) === true) { $errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already is use. Please contact your site adimn is this is incorrect.'; } } } if (isset($_GET['success']) && empty($_GET['success'])) { echo '<div class="container"><div class="background-success text-center"><div class="alert alert-success center-background">You\'ve be registered successfully! Please check your email to activate your account</div><div class="center-background"><div class="center-text-background">if any issues occur please send us an email!! support@bettergamerzunited.com</div></div></div>'; } else { if(empty($_POST) === false && empty($errors) === true) { $register_data = array( 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'username' => $_POST['username'], 'password' => $_POST['password'], 'email' => $_POST['email'], 'email_code' => md5($_POST['username'] + microtime()) ); register_user($register_data); header('Location: register.php?success'); exit(); } ?> <div class="container background"> <form action="" method="POST" class="form-horizontal" role="form"> <div class="form-group"> <label for="inputfirstname3" class="col-sm-2 control-label">First Name</label> <div class="col-sm-10"> <input type="text" name="first_name" class="form-control" id="inputfirstname3" value="" autocomplete="off" placeholder="First Name"> </div> </div> <div class="form-group"> <label for="inputlastname3" class="col-sm-2 control-label">Last Name</label> <div class="col-sm-10"> <input type="text" name="last_name" class="form-control" id="inputlastname3" value="" autocomplete="off" placeholder="Last Name"> </div> </div> <div class="form-group"> <label for="inputusername3" class="col-sm-2 control-label">Username</label> <div class="col-sm-10"> <input type="text" name="username" class="form-control" id="inputusername3" value="" autocomplete="off" placeholder="Username"> </div> </div> <div class="form-group"> <label for="inputemail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" name="email" class="form-control" id="inputemail3" value="" autocomplete="off" placeholder="Email Address"> </div> </div> <div class="form-group"> <label for="inputpassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" name="password" class="form-control" id="inputpassword3" autocomplete="off" placeholder="Password"> </div> </div> <div class="form-group"> <label for="inputpassword_again3" class="col-sm-2 control-label">Validate Password</label> <div class="col-sm-10"> <input type="password" name="password_again" class="form-control" id="inputpassword_again3" autocomplete="off" placeholder="Validate Password"> </div> </div> <div class="form-group"> <div class="col-sm-10"> <p class="info">Please be aware that this does not mean that you are a member of Better Gamerz United. If you would like to be come a member please contuine with the registration and then fill out our application. Other wise you will have limited use of this site. Thank you Team BGU!! </p> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary pull-right register">Register</button> </div> </div> </form> </div> <?php } include 'includes/overall/footer.php'; ?> I have a form, where I'm collecting registration info - like name, address, email, password. I'm calling another php file at server side code, where it will check whether the email exists or not. Pretty simple, just receiving those post variables and check with the database. The issue, if I find a match, I want to go back to the registration.php page, using the following code: if ($email_already_use == "y") { $_SESSION['ERROR'] = "Error"; $_SESSION['MESSAGE'] = "This email address already used. Please try another"; header("location: ".$settings['site_url']."registration.php"); exit; } Now, I would like to place the user input at the registration.php file, but I do not want to use pass variable at URL like this: header("location: ".$settings['site_url']."registration.php?".name=$name&address=$address&email=$email; Is there anyway, I can retrieve those variables at registration.php, without specifying .name=$name&address=$address&email=$email ? Thanks for your help. I see some sites has similar implementation, but did not find anything like how to do it. Hi, I have a div which reloads every 10 seconds but I want it so that if it equals something then redirect the whole page when at the moment it just loads the whole page in in the div but need the div as it stores all my variables, anyone know of anything else I can use? Thanks I want the page to refresh on with the query string, but this isn't working for me... Code: [Select] header("Location: " . $_SERVER['php_self'] . "?" . $_SERVER['query_string'] ); I'm trying to rewrite the old jpmaster77 login script that I used back in the day quite extensively, but I'm having problems getting the $form->error messages to the correct page.
Login form, on the index.php:
<div> <h3>Login</h3> <form method="post" action="process.php" id="sublogin"> /* error message should be displayed here when username is empty or == username */ <p> <?php echo $form->error("user"); ?> <input class="loginside" type="text" name="user" value="username" /> ?> <br /> <input class="loginside" type="password" name="pass" value="password" /> <br /> <input type="hidden" name="sublogin" value="1"> <input type="checkbox" name="remember">Remember me <br /> <input class="sublogin" type="submit" value="login" style="border: 0; margin: 5px 0 0 1px;" /> </p> </form> Not registered yet? Sign up here! </div> process.php class Process { /* Class constructor */ function Process(){ global $session; /* User submitted login form */ if(isset($_POST['sublogin'])){ $this->procLogin(); } /** * Should not get here, which means user is viewing this page * by mistake and therefore is redirected. */ else{ header("Location: index.php"); } } function procLogin(){ global $session, $form; /* Login attempt */ $_POST = $session->cleanInput($_POST); $retval = $session->login($_POST['user'], $_POST['pass'], isset($_POST['remember'])); if($retval){ header("Location: correct.php"); } else{ $_SESSION['value_array'] = $_POST; $_SESSION['error_array'] = $form->getErrorArray(); header("Location: index.php"); } /* if instead the $_SESSION and header I enter echo $form->error("user") then the error message is displayed in process.php, and not in index.php */ } } $process = new Process; ?>But when instead the $_SESSION and the header location I enter here echo $form->error("user"); then all is fine. But the error message should not be displayed in the process.php, but rather above the login form on the index.php session.php <?php include "database.php"; include "form.php"; class Session { var $time; function Session(){ $this->time = time(); $this->startSession(); } function startSession(){ $session_name = 'sec_session_id'; // Set a custom session name $secure = true; // This stops JavaScript being able to access the session id. $httponly = true; // Forces sessions to only use cookies. if (ini_set('session.use_only_cookies', 1) === FALSE) { header("Location: ../error.php?err=Could not initiate a safe session (ini_set)"); exit(); } // Gets current cookies params. $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); // Sets the session name to the one set above. session_name($session_name); session_start(); // Start the PHP session session_regenerate_id(true); // regenerated the session, delete the old one. } function login($subuser, $subpass, $subremember) { global $database, $form; /* username check */ $field = "user"; if(!$subuser || $subuser == "username") { $form->setError($field, "* Username incorrect"); } /* password check */ /* if e-mail welcome, check if user activated account */ /* Return if form errors exist */ if($form->num_errors > 0){ return false; } return true; } function cleanInput($post = array()) { foreach($post as $k => $v){ $post[$k] = trim(htmlspecialchars($v)); } return $post; } }; $session = new Session; $form = new Form; ?> form.php <?php /** * Form.php * * The Form class is meant to simplify the task of keeping * track of errors in user submitted forms and the form * field values that were entered correctly. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ class Form { var $values = array(); //Holds submitted form field values var $errors = array(); //Holds submitted form error messages var $num_errors; //The number of errors in submitted form /* Class constructor */ function Form(){ /** * Get form value and error arrays, used when there * is an error with a user-submitted form. */ if(isset($_SESSION['value_array']) && isset($_SESSION['error_array'])){ $this->values = $_SESSION['value_array']; $this->errors = $_SESSION['error_array']; $this->num_errors = count($this->errors); unset($_SESSION['value_array']); unset($_SESSION['error_array']); } else{ $this->num_errors = 0; } } /** * setValue - Records the value typed into the given * form field by the user. */ function setValue($field, $value){ $this->values[$field] = $value; } /** * setError - Records new form error given the form * field name and the error message attached to it. */ function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } /** * value - Returns the value attached to the given * field, if none exists, the empty string is returned. */ function value($field){ if(array_key_exists($field,$this->values)){ return htmlspecialchars(stripslashes($this->values[$field])); }else{ return ""; } } /** * error - Returns the error message attached to the * given field, if none exists, the empty string is returned. */ function error($field){ if(array_key_exists($field,$this->errors)){ return "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>"; }else{ return ""; } } /* getErrorArray - Returns the array of error messages */ function getErrorArray(){ return $this->errors; } }; ?>Does anyone know why the $form->error("user") variable cannot be transfered to the index.php? Is something wrong with the session_start or something? thanks in advance guys! Edited by dde, 07 January 2015 - 03:49 PM. I'm using jQuery ajax for my login script. However my linked php file with ajax doesn't change the screen with header('location') whats a way to change the page on login using ajax? Thanks Hello, When i want a custom site search i need to process like google "site:600host.net terms" however my php just pulls a blank page when trying to output this i think its to do with : Quote <?php $keywords = $_REQUEST["keywords"]; $keywords2 = "$keywords"; $lowerCase = strtolower($keywords2); header("Location: ".$lowerCase.".html"); ?> Thanks any help appreciated! So I have a site in which a user logs in. When they click the submit button on the login page, it checks to see if a username and password combo exists in an array. If it doesn't exist, the user is supposed to be redirected back to the login page.
This code USED to work, and I think I added one thing completely away from the code that should do any of this, but now it doesn't work any more.
I've read that you can't have anything output before the header code, so I've double checked, and can't find any spaces, echo statements or anything of the like. I've thrown in a random echo statement to see if my if's else's were being entered correctly, and they are. I definitely get into the else statement with the header(location: blah) code when an incorrect username/password is used...
Here's the code I'm looking at. (And there is More HTML under this...)
<?php session_start();?> <?php include("passwords.php"); //this statement will be entered if coming from the login.php page. if ($_POST["ac"]=="log"){ //check if submitted username and password exist in $PASSWORD array if ($PASSWORD[$_POST["username"]]==$_POST["password"]){ //set various session variables $_SESSION["username"]=$_POST["username"]; $_SESSION["firstname"]=$FIRSTNAME[$_POST["username"]]; $_SESSION["lastname"]=$LASTNAME[$_POST["username"]]; $_SESSION["email"]=$EMAIL[$_POST["username"]]; } else{ //if username and password do not exist, set session variable for "incorrect username/password" message and redirect to login.php $_SESSION['incorrect'] = "incorrect"; header('Location: login.php'); }; }; // check if user is logged in already when they are coming from a random place. If not, redirect to login.php check_logged(); ?>Any ideas out there why my header('Location: login.php'); line is not working? Hey people! I've been setting a coding script for experience and this is my situation: To buy a virtual flower, one needs to have 50 virtual coins. So I first extract the number of coins the person has from the DB. If the user doesn't have the sufficient number of coins, the BUY button will not be available and vice versa. When the BUY button is clicked, I update the database, adding the flower to the user's inventory and subtracting 50 from the total number of coins the user has. This I do in that page itself using if(isset($_POST['submit'])) Now, I need to know how I could check whether the user has at least 50 coins even if the button is available. I hope that you could understand this. I want to do it for validation purposes. Its to prevent the user spending the coins he has in another browser window and then returning to the visible button to click it. I hope that I make sense. Thanks in advance! Regards, Thauwa Hello, I am trying to echo a message before redirecting the visitor to another page. The destination is a variable. This is what i have so far: Code: [Select] <?php if (array_key_exists($_GET[id],$links)) { $red = $links[$_GET[id]]; header("HTTP/1.1 301 Moved Permanently;"); header("Refresh:3; url=$red"); echo "You will be redirected to.."; } else { header("Location: http://www.example.com"); } exit(); ?> The problem is that it works in Firefox, but not IE. In IE it will work if there is no message and no delay, like the code below: Code: [Select] <?php if (array_key_exists($_GET[id],$links)) { $red = $links[$_GET[id]]; header("HTTP/1.1 301 Moved Permanently;"); header("Location: $red"); } else { header("Location: http://www.example.com"); } exit(); ? Does anybody have any idea, what is wrong with this code? Thank you in advance! For SEO purposes I am told that either 301/302 redirects are better. I use header("Location: $url everywhere, is this 301 or 302 ? Also, I see somewhere that this is the proper way to do it. Code: [Select] header ('HTTP/1.1 301 Moved Permanently'); header ('Location: '.$location); .. what if I didn't use the first line (I have sites all over the place littered with header Location, but have only used the 2nd line)? Would it make a difference - it works that's for sure. Hi.. I have query for insert then I just want to add condition that after it save it will locate on the previous page: here is my code: Code: [Select] $sql = "INSERT INTO receiving_materials (sr_date, sr_number, si_num, s_name, po_num, qty, mat_code, mat_desc, wh_code, bin_loc) VALUES ('$sr_date', '$sr_number', '$si_num', '$s_name', '$po_num', '$qty', '$mat_code', '$mat_desc', '$wh_code', '$bin_loc') ON DUPLICATE KEY UPDATE sr_date = '$sr_date', sr_number = '$sr_number', si_num = '$si_num', s_name = '$s_name', po_num = '$po_num', qty = '$qty', mat_code = '$mat_code', mat_desc = '$mat_desc', wh_code = 'wh_code', bin_loc = '$bin_loc'"; $res_receiving = mysql_query($sql, $con) or die(mysql_error()); Thank you |