I know how to include external PHP pages and how to start sessions etc, but I think there is something messed up with my logic on what I am working on. Hoping someone could take a look...
I have an html page that is a form that pulls up a PHP view page with the info it sends to it. I wanted to put my function in an external page, along with using sessions, but I keep getting a syntax error.
When I send my form it goes to the following:
<?php
session_start();
include 'functs.php';
if ($_POST && !empty($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
$_SESSION['time'] = $_POST['time'];
confirmed();
}
else {
print unconfirmed();
}
?>
My external page with the functions is this:
<?php
function confirmed() {
echo "<head>";
echo "<title>Confirmation Page</title>";
echo '</head>";
echo "<body>";
PRINT <<<HERE
if (isset($_SESSION['name'])) {
echo 'Thank you, '.$_SESSION['name']. ' your reservation is confirmed for ' . $_SESSION['time'] ;
}
else {
echo 'There seems to have been an error processing your reservation. Please ensure that you have cookies enabled and try your request again' ;
}
HERE;
echo "</body></html>";
?>
The error I am getting is Parse error: syntax error, unexpected 'name' (T_STRING), expecting ',' or ';' in E:\Program Files\xampp\htdocs\cis\w2\functs.php on line 10. If I insert the function internally, it works, so I know its something with how I am formatting the include page.
It's pretty obvious via the syntax highlighting what is wrong here:
echo '</head>";
//-----------^
This line has the incorrect quote mark, thus you never terminate the string, and it keeps going.
Edit:
But that isn't the only problem. You also never close your function with a right curly bracket: }.
The main problem is that you have mismatched quotes on this line:
echo '</head>";
However, I have to say I'm confused as to why you have the HEREDOC. Surely you just need the if statement alone?
Related
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
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.
I have this piece of code:
if(isset($_POST['btnSubmit']) && $_POST['btnSubmit'])
{
require_once($_SERVER['DOCUMENT_ROOT'] . 'database.php');
$derpCard = $card;
$derpAccessGroup = $_POST['tbAccessGroup'];
$derpComments = $_POST['tbComments'];
if(isset($_POST['cbActivated']))
$derpActive = $_POST['cbActivated'];
else
$derpActive = "DEACTIVATED";
$x = editCard($derpCard,$derpAccessGroup, $derpComments, $derpActive);
if($x)
{
$_SESSION['editcard'] = $derpCard;
$_SESSION['editgroup'] = $derpAccessGroup;
$_SESSION['editcomments'] = $derpComments;
$_SESSION['editstatus'] = $derpActive;
echo "<script>";
echo "alert(\"Done!\");";
echo "</script>";
}
echo "<script>location.reload(true);</script>";
}
Basically, editCard runs an SQL "UPDATE ... where..." to edit the content within the db. If this is sucessful, I want it to display an alert telling the user it's been updated, as well as refresh the page.
Both the alert and reload code do not run, and i've been trying any and all alternatives! If someone has any idea as to simply refresh the page (thats the minimum i need!) It would be greatly appreciated!
I have to apologize if this answer is too short but the question is too broad or is missing more info. I noticed that one of your lines is wrong.
require_once($_SERVER['DOCUMENT_ROOT'] . 'database.php');
should be:
require_once($_SERVER['DOCUMENT_ROOT'] . '/database.php');
There should be / in it since $_SERVER['DOCUMENT_ROOT'] returns something like this:
"C:/xampp/htdocs"
So if you are to concatenate that with "database.php", you'll be having
"C:/xampp/htdocsdatabase.php" instead of "C:/xampp/htdocs/database.php"
In any case, you should try using firebug or similar browser add-on to help you debug those javascript errors(if there are any).
I hope this helps.
Try to format the script echo like this:
echo "\n<script>\n<!--\n";
echo "alert(\"Done!\");";
echo "\n-->\n</script>\n";
and
echo "\n<script>\n<!--\nlocation.reload(true);\n-->\n</script>\n";
Note the new lines added.
You appear to be missing the type attribute for script.
If you want to specify javascript, you need to include the type.
echo "<script type=\"text/javascript\">";
echo "alert(\"Done!\")";
echo "</script>";
Same goes with the other line
echo "<script type=\"text/javascript\">location.reload(true);</script>";
If the above does not help in the slightest, the problem could be with your logic statements, or that your javascript may just not be outputting what you want.
There are tools to help you figure out these issues, such as the apache logs and firebug plugin
EDIT: Forgot missing semicolon
This seems like it should be easy but I can't for the life of me get this to work, I'm checking a variable in a query string, if it returns a Yes it redirects to a new page. If it returns a no I want it to display an error message above the form.
My issue is with displaying the error message, it redirects when var=Yes but when it gives me var=no I can't get it to display the error message. If I replace $errormsg with header(..); it works so I know it's not my if statement.
if (isset($_GET['var'])) {
$var = $_GET['var'];
$errormsg = '';
if ($var == 'Yes') {
header( 'Location: http://www.google.com' ); exit;
}
else if ($var == 'no') {
$errormsg = 'This is an error message.';
}
};
And this is the error message above the form:
<div class="errormsg"><?php echo $errormsg; ?></div>
My PHP ability is limited and I can't figure out what I'm doing wrong, any help will be appreciated.
Thanks!
My guess is the $var is not returning what you are expecting (possibly a "No" instead of a "no" as mjayt suggested in the comments.
First step would be to debug, and determine what $var is actually returning. Try simple print statements and go from there.
Try to echo $errormsg directly under the if block without any HTML. See if your text is returned.
Think you might remove that semi colon from that last curly brace also
I am running through a jQuery Ajax tutorial here:
http://www.charlieperrins.com/2011/03/ajax-jquery-101/
Everything works perfectly but I have a question about this piece of code:
<?php if ($_POST['user']) : ?>
<?php
$user_id = $_POST['user'];
if (isset($db_data[$user_id])) {
$data = $db_data[$user_id];
} else {
echo 'Sorry, no user data matched your request - please try again';
die;
}
?>
I am most concerned with the very first line. What does that line do? I am trying to keep all the code in 1 set of php tags but I don't know how to do that. If I knew what the first line does, I might be able to figure it out. Any help is appreciated. I am trying to reverse engineer this to fit it into my app but can't do it without knowing what that top line does.
Thanks.
All this does is continues the if block until endif.
There is no endif, so nothing in this script runs unless there is data in $_POST['user'] that doesn't evaluate to false.
I would write this a bit differently:
<?php
if (isset($_POST['user'])) {
$user_id = $_POST['user'];
if (isset($db_data[$user_id])) {
$data = $db_data[$user_id];
} else {
echo 'Sorry, no user data matched your request - please try again';
die;
}
}
?>
The first line tests if the $_POST array has a key user, and that key contains a "truthy" (non-empty, among other things) value, indicating that a form was posted to this script. If no form data was posted, the rest of the script won't execute, such as if someone browsed directly to this PHP script without using the expected form to post to it. It is a technique often used when a form posts back to the same PHP script. Upon first arriving at the script, the $_POST will be empty. When the form is posted back to the same script, different actions can be taken when it contains values.
There need only be one <?php tag:
<?php
if ($_POST['user']) {
$user_id = $_POST['user'];
if (isset($db_data[$user_id])) {
$data = $db_data[$user_id];
} else {
echo 'Sorry, no user data matched your request - please try again';
die;
}
}
?>
This is Alternative syntax for control structures
<?php if ($_POST['user']) : ?> means if $_POST['user'] evaluates to true, execute the following code.
It can be compressed down to this:
<?php if ($_POST['user']) :
$user_id = $_POST['user'];
....
Also,
if ($_POST['user']) :
should be
if (isset($_POST['user']) && !empty(trim($_POST['user']))) :
That makes sure that $_POST['user'] has been set (generally $_POST contains variables from a form), and that it is not empty even with white-space removed.
See
Alternative syntax for control structures
$_POST
empty
trim
The if ($_POST['user']) line is saying this:
If the variable $_POST['user'] exists and is set to a non-false value.
The above condition fails if $_POST['user'] is 0, false, or '' (empty string).
It also isn't safely checking that value.
You are better off using:
if (isset($_POST['user'])) && $_POST['user'] != '')
This way no warning is output when PHP has display_errors and notices turned on.