Error in php redirect - php

I have a button:
<form method="post">
<input name="submit" type="submit" class="icon2" value=" " />
</form>
And a redirect with a header using following code:
<?php
$homepage = '/2013/php/nelson-test.php';
$currentpage = $_SERVER['REQUEST_URI'];
if(isset($_POST['submit']) && $homepage==$currentpage)
{
header('Location:/2013/php/nelson.php');
}
?>
I used the exactly same code yesterday in a different site and it works (I only changed the links), and now it gives me this error:
Warning: Cannot modify header information - headers already sent by (output started at /homez.121/pneuexpo/www/2013/php/nelson-test.**php:1**) in /homez.121/pneuexpo/www/2013/php/nelson-test.php on **line 6**
I don't understand why since in line one I only have the php beginning tag and on line 6 there is only the header. Any ideas?
(BTW the purpose of the button and the header is that when you click the button it redirect to the same page but in English (the page is currently in French))

Remove ';' after this
if(isset($_POST['submit']) && $homepage==$currentpage) //Remove ;
{
header('Location:/2013/php/nelson.php');
exit;
}

try this:
echo("<script>location.href = '/2013/php/nelson.php';</script>");

yes that is correct remove ; from it if you put ; then it interprete as a statement and it will raise error, and before header there should not be output on the page.

as i am gussing your if condition is valid then please add exit
<?php
$homepage = '/2013/php/nelson-test.php';
$currentpage = $_SERVER['REQUEST_URI'];
if(isset($_POST['submit']) && $homepage==$currentpage);
{
header('Location:/2013/php/nelson.php');
exit;
}
?>

remove all white space after
still if you cant remove error than redirect using javascript as follow
echo '<script type="text/javascript">window.location="nelson.php"</script>';

Related

Form validation with a php array

I'm hoping someone could help me finish off some php code (the avon guy already kindly helped me with this but I'm still struggling with the last bit).
All it is, is I have a form where I have 10 particular sequences of digits, which if entered, allows the form to redirect to the following page. If anything else is entered I want the page to deny access with some kind of error prompt.
At top of the php, in the part before any php is printed, avon guy suggested an array to check the 10 correct sequences against.
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) != false) {
//match code in here
} else {
// fail code in here
}
I'm not sure what to put in the //match code in here AND the //fail code in here, bits. Can someone help me with this last bit please?
Many thanks
Jon
If you are just trying to redirect to another page using php, you can use header('Location: mypage.php');. More information on header here.
So for your code example (edited based on comment):
invitation.php
<?php
//invitation.php
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) === false)
{
//If fail
header('Location: formpage.php?errorMessage=Incorrect code!');
exit();
}
//If success:
//All of the invitation.php html and success code below
formpage.php
<?php
//formpage.php
if(!empty($_GET['errorMessage'])){
echo '<span>' . $_GET['errorMessage'] . '</span>';
}
?>
<form action="invitation.php" method="post">
<input name="rsvp" type="text" />
<input type="submit" value="Submit" name="submit" />
</form>

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

basic php: redirect page using page id

I want to redirect if form update successfully, the page i edit
example:
<?php
header("Location: update_lbctn.php?order=2")
?>
my problem is in example above order=2 is dynamic it change depend on page ID
so I try like this
<?php
header("Location: update_lbctn.php?order=" . echo urlencode($current_id['id']) ." " ")
?>
but give me error: Parse error: syntax error, unexpected 'echo' (T_ECHO)
Try this -
header('Location:update_lbctn.php?order='.urlencode($current_id['id']));
exit;
There is no need to add the echo. Just concatenate the id.
In your Code you have used extra quotes. Just Put the following code. echo is not required while using header redirect as it is, itself a php function
header("Location: update_lbctn.php?order=" .urlencode($current_id['id']))
The header function will echo out the inner content so no need to write echo again.
For this you can write
<?php
header("Location: update_lbctn.php?order=".urlencode($current_id['id']);
?>
All you need to do is pass a string to the Location.
And with your code, it will redirect to the location specified by the string, not to print it.
So, in your code:
<?php
header("Location: update_lbctn.php?order=" . echo urlencode($current_id['id']) ." " ")
?>
The echo is unnecessary.
Why do it is giving syntax error:
Its because, you are putting echo just after the dot ..
echo is expected to come at the new line where other line ends or at the first line.
In short either after semi-colon : or right in the beginning of the file.
e.g.
$test = 'gg';
echo $test;
or
echo $_GET['DUMMY_VAR_FOR_TESTING'];
So, its producing syntax error.

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>

file_get_contents displays nothing when used with $_GET

I'm having a problem when using file_get_contents combined with $_GET. For example, I'm trying to load the following page using file_get_contents:
https://bing.com/?q=how+to+tie+a+tie
If I were to load it like this, the page loads fine:
http://localhost/load1.php
<?
echo file_get_contents("https://bing.com/?q=how+to+tie+a+tie");
?>
However, when I load it like this, I'm having problems:
http://localhost/load2.php?url=https://bing.com/?q=how+to+tie+a+tie
<?
$enteredurl = $_GET["url"];
$page = file_get_contents($enteredurl);
echo $page;
?>
When I load using the second method, I get a blank page. Checking the page source returns nothing. When I echo $enteredurl I get "https://bing.com/?q=how to tie a tie". It seems that the "+" signs are gone.
Furthermore, loading http://localhost/load2.php?url=https://bing.com/?q=how works fine. The webpage shows up.
Anyone know what could be causing the problem?
Thanks!
UPDATE
Trying to use urlencode() to achieve this. I have a standard form with input and submit fields:
<form name="search" action="load2.php" method="post">
<input type="text" name="search" />
<input type="submit" value="Go!" />
</form>
Then to update load2.php URL:
<?
$enteredurl = $_GET["url"];
$search = urlencode($_POST["search"]);
if(!empty($search)) {
echo '<script type="text/javascript">window.location="load2.php?url=https://bing.com/?q='.$search.'";</script>';
}
?>
Somewhere here the code is broken. $enteredurl still returns the same value as before. (https://bing.com/?q=how to tie a tie)
You have to encode your parameters properly http://localhost/load2.php?url=https://bing.com/?q=how+to+tie+a+tie should be http://localhost/load2.php?urlhttps%3A%2F%2Fbing.com%2F%3Fq%3Dhow%2Bto%2Btie%2Ba%2Btie. you can use encodeURIComponent in JavaScript to do this or urlencode in php.
<?
$enteredurl = $_GET["url"];
$search = urlencode($_POST["search"]);
if(!empty($search)) {
$url = urlencode('https://bing.com/?q='.$search)
echo '<script type="text/javascript">window.location="load2.php?url='.$url.'";</script>';
}
?>

Categories