PHP redirect not working - php

The code below simple checks if the user enters in a valid JSON data as denoted in the if statement below. The if statement works just fine for me, it's just getting the page to redirect is not. Could anyone explain why this might be? Thanks
<?php
//Retrives name var from form on previous page
$name = $_REQUEST['name'];
//Changes the title tag based on the users name
$pageTitle = "Thanks ".$name."!";
//
$section = "contact";
//Retrives the product ID based on what the user requested
$productId = $_REQUEST['productId'];
//Retrives the email var from form on previous page
$email = $_REQUEST['email'];
?>
<?php
//Acts as a place holder var for the url containing the productID the user specfied.
$url = 'xxx.xxx.xxx';
//Fetchs the contents of the of the url var address, and returns them into a JSON var
$JSON = file_get_contents($url);
//Puts the JSON var into a parameter that actually does the decoding into JSON
$data = json_decode($JSON,true);
if (empty($data)){
header('Location: http://www.google.com');
exit;
} else {
echo "it's valid";
//References the header file for CSS
include("inc/header.php");
}

You send a few whitespaces before the redirect, when you close and reopen php around your line 14.
And Headers cannot be sent after the body of response is already started. (There should be a warning somewhere unless it is turned off.)

There is a whitespace / enter between
?>
<?php
Once you send any char, a redirect is no longer working. Put everything into a single
<?php ... ?>
and it should work.

Just a hunch but try removing the
?>
<?php
in the middle as this might be sending some information to the client before your asking to send the header. This could cause the header redirect to fail.

In your else statement you don't have a header location specified, all you're doing is echoing that it's valid and you're including a file but not redirecting to a different page.
What you have is this:
else {
echo "it's valid";
//References the header file for CSS
include("inc/header.php");
}
Shouldn't you have a header in there?

Related

How to get current url and get code from it in PHP

Im making an email verification system on PHP in cPanel, and when i press register, it sends an email to me with a link like this "../verified.php?code=1cbb402a59e8ec26dac0", i would need to get the full link and would have to chop it so it leaves me with just the code "1cbb402a59e8ec26dac0" so i can check if the code exists in database and then verify the account.
So from this
../verified.php?code=1cbb402a59e8ec26dac0
To This
"1cbb402a59e8ec26dac0
Purchasing the hostings for the first time fried my brains, so would be thankful if anyone could help me,
For getting the text after the code: in the link, you can use the PHP $_GET function. You can use this code in your verified.php to get the text after code:
<?php
if(isset($_GET['code']))
{
$Data=$_GET['code'];
}
else{
echo "Invalid Email Verification";
?>
Now the part after the code= gets stored in the variable Data.
You can change that to your desired variable.
Sometimes even when the code is set, it might be empty, so to check that, the empty() function in PHP can be used.
You can add this code to your verified.php:
<?php
if (empty($Data))
{
echo "Invalid Verification ID";
}
else
{
echo "Email Verification Success";
//your other codes to update it on the server
}
?>
Well you have chosen to pass parameters which will be available in the global $_GET[] (as opposed to $_POST[]).
So in your verified.php you will need to examine for the presence of $_GET['code'] and take the appropriate action.
Using $code = $_GET['code']; is very bad as you need to qualify it.
At a minimum you would need to...
<?php
// Ternary to give $code a value to prevent undefined variable error.
$code = isset($_GET['code']) ? $_GET['code'] : NULL;
if($code === NULL){
// error
} else {
// Check its a valid code and take the appropriate action.
}

Five unique pages lead to one page. Can I change the <h1> according to the page they came from?

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

How to display error messages on redirect?

It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting

PHP Header relocating and $_GET

I have a website that allows users to upload a picture, but I don't want any nudity in the photos. I found a scan written in php that I have succesfully implemented. The file and record are deleted if nudity is found to be in the file. I am just having trouble alerting the user as to why there pic wasn't kept. It just reloads the page. What could be the problem?
This code is the beginning of non commented code in my new2.php file:
if (isset($_GET['error'])) {
echo "Nudity found. Please try again with a more appropriate picture.";
sleep(5);
header("Location: new2.php");
}
This code is the code that scans the pic for nudity:
if($quant->isPorn()) {
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
header('Location: new2.php?error=1');
} else {
header("Location: index.php?id=$id");
}
Any help would be greatly appreciated!
Your echo output won't be seen by the user. Output hasn't been sent to the browser yet, that happens at the end of your script. You redirect before that happens.
If you want to send a message, wait 5 seconds, and then redirect, do it client side.
<?php if (isset($_GET['error'])) { ?>
<p>Nudity found. Please try again with a more appropriate picture.</p>
<script>
setTimeout("self.location='new2.php'",5000);
</script>
<?php } ?>
Javascript is not needed. Just output the page containing your error, but change
sleep(5);
header("Location: new2.php");
to
header("Refresh: 5; url=new2.php");
This has the same effect as a <meta http-equiv="refresh">.
Don't do it from header. Use this instead:
<script> location="whatever.php?a=1"; </script>

PHP empty not working

I am just trying to check if a form variable is empty. The code sets the variables $getsubject and $getsubject to the $_POST of the form, then I am checking if they are, empty and if they are I want to set them to "No Message" or "No Subject". I tried with isset as well and it didn't work. I even tried setting an else statement that does the same thing and it doesn't change it.
$getsubject = $_POST['subject'];
$getmessage = $_POST['message'];
if(empty($getsubject)) {
$getsubject = "<No Subject>";
}
if(empty($getmessage)){
$getmessage = "<No Message>";
}
I found the problem .. the code is working - however the since there were brackets "<" and ">" ... when I retrieved the data from the SQL table, it was not appearing. Not sure why, but when I removed the brackets it worked.
If you are not sure id the data from the form exist you must use !isset to check it before you declare the variables, so:
if(!isset($getsubject)) {
$getsubject = "<No Subject>";
}
else{
$getsubject = $_POST['subject'];
}
if(!isset($getmessage)){
$getmessage = "<No Message>";
}
else{
$getmessage = $_POST['message'];
}
The data from $_POST['subject'];, for example, might not exist, and if you declare it php will give you an error
I suggest that you use a full if conditional to display the results you are looking for combined with html.
IF subject has content
then echo Great subject
ELSE
then echo No Subject
END IF
IF message has content
then echo Thank You for the message
ELSE
then echo No Messgae was entered
END IF
^this is the basic logic not the code
Also look into the trim php code which will trim blank space off of the submission. This helps eliminate blank responses or spaces counting as characters (will not remove space between characters)

Categories