OK, so here's my code. (I'll sanitize it later. Don't worry about it.)
gallery_upload_new.php
// Check if user wants to upload to existing or new album
if (isset($_POST['album'])) {
if ($_POST['album'] == '') {
$_POST['album'] = $_POST['new_album'];
}
}
// Populate album dropdown menu
$albums = $database->query("SELECT DISTINCT(album) FROM images")->fetchAll(PDO::FETCH_COLUMN);
// Load the 'upload new photo' interface if user's not uploading it already
if (!isset($_FILES['image_link']) || !isset($_POST['caption']) || $_POST['caption'] == '') {
//var_dump($_FILES);
//var_dump($_POST);
include('views/gallery_upload_new.php');
// Otherwise store the image file, register it into database, and put the user back in the list of photos
} else {
$new_image = new Image($_POST['caption'], $_POST['album']);
$new_image->register($_FILES['image_link']['tmp_name'], $_FILES['image_link']['name']);
header('location: gallery_management.php');
}
?>
views/gallery_upload_new.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $site_title; ?></title>
<?php include('views/header.php'); //Just the global CSS and JavaScript ?>
</head>
<body>
<?php include('views/nav_menu.php'); //Site navigation panel ?>
<div id="content">
<h1>Upload new photo</h1>
<form enctype="multipart/form-data" action="gallery_upload_new.php" method="post">
<p>
<strong>Upload to album: </strong>
<select name="album">
<?php
foreach($albums as $album_name) {
echo "<option value='$album_name'>$album_name</option>";
}
?>
<option id="selectNewAlbum" value="" selected>New album</option> <input type="text" placeholder="New album name" name="new_album" id="newAlbumName">
</select>
</p>
<p><strong>Photo caption</strong> <input type="text" name="caption"></p>
<p><strong>Photo file: </strong><input type="file" required name="image_link"></p>
<input type="submit" value="Unggah">
</form>
</div>
</body>
</html>
Here's the weird part: without those two var_dump's up there, the else block won't execute. I've made sure the indexes in the $_POST and $_FILES are correct. Yet without those dummy dumps, this thing won't work. It'd just load the views/gallery_upload_new.php no matter what.
It doesn't even matter if they're commented out or not. They just need to be there.
What did I do wrong? Did I made a syntax error somewhere?
Related
I have a form which has email as field name. What I am trying to do is if the email is it no equal to $emailToCheck is not equal to $_POST['email'], it should throw an error first time. The second time if the user enters wrong email id again it should always redirect to "error.htm" even if the page refreshes.
It doesn't work the form always shows even if the email id is entered wrong twice.
<?php
if (!empty($_POST['email'])) {
$email="website#test.com";
if($email!=$_POST['email'])
{
$count="1";
}
if($count=="2"){
header("Location: /error.htm");
exit(0);
}
}
if($count!="2"){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul >
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
<?
}
?>
You have two issues here:
1. You are defining $count as a string, and never incrementing it. If you look over your code, $count is getting specifically set to 1 every time there is a mismatch. How is supposed to ever get to 2?
2. Furthermore, data here is stateless. How is the script supposed to know what $count was set to on the previous call? You need to also set $count as a session variable so that the script will know what its previous value.
You should try updating your code to something similar to this:
// Check if `email` passed in POST request:
if ($_POST['email']) {
$email = "website#test.com"; //Manually define expected email address.
// Check if provided email does *not* match the expected email:
if ($email !== $_POST['email']) {
// Record the mismatch attempt in session and increment:
if (!($_SESSION['incorrectEmailCount'])) {
// If this is the first mismatch, define the session variable, and set to 1.
$_SESSION['incorrectEmailCount'] = 1;
} else {
// Session variable already set due to previous mismatch. Increment it.
$_SESSION['incorrectEmailCount']++;
}
}
// If user entered incorrect email more than once:
if ($_SESSION['incorrectEmailCount'] > 1) {
// Redirect to error page and stop execution.
header("Location: /error.htm");
exit(0);
}
}
Once the form is submitted, the page reloads, resetting the counter. In order to actually count, you need to provide that value in the form and pass it along to the PHP when the form is submitted.
<?php
// Try to get the amount of attempts from the POSTed data
$count = isset($_POST['count']) ? $_POST['count'] : 0;
if (isset($_POST['email'])) {
$email = "website#test.com";
if ($email != $_POST['email']) {
$count++;
}
if ($count == 2) {
header("Location: /error.htm");
}
}
if ($count <= 2):
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<!-- Let the POST data know this is the x attempt -->
<input type="hidden" name="count" value="<?php echo $count; ?>">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
<?php endif; ?>
Also, your coding style is far from consistent. Try to work on that!
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
<?php
$name;
$college;
if(empty($_POST["name"])){
$nameerr="NAME IS REQUIRED";
}
else{
$name=$_POST["name"];
}
$course=$_POST["course"];
if(empty($_POST["college"])){
$collegeerr="NAME OF COLLEGE IS REQUIRED";
}else{
$college=$_POST["college"];
}
$email=$_POST["email"];
$abc=mysqli_connect('localhost','root','','generalinfo') or die('ERROR:COULD NOT CONNECT TO DATABASE');
$query="INSERT INTO studentinfo VALUES ('$name','$course','$college','$email')";
$final=mysqli_query($abc,$query) or die('ERROR ENTERING THE DATA IN DATABASE');
mysqli_close($abc);
echo'THANKYOU FOR SUBMITTING THE FORM';
?>
<div id="b">
<form action="" method="post">
<label for="name"><div id="a">name</div></label>
<input type="text" name="name"></br>
<div id="c"><?php echo $nameerr; ?></div>
<label for="course"><div id="a">course</div></label>
<input type="text" name="course"></br>
<label for="email"><div id="a">email</div></label>
<input type="text" name="email"></br>
<label for="college"><div id="a">college</div></label>
<input type="text" name="college"></br>
<div id="d"><?php echo $collegeerr; ?></div>
<input type="submit" value="submit" name="sub"></br>
</form>
</div>
</body>
</html>
After i press the submit button nothing happens..no error message comes up if i don't fill out the name or college field..also the filled the out information is not recieved in the database ...any kind of help will be appreciated ..thanks in advance
you should add an action
<form action="form.php" method="post">
And then include the form.php in you website's folder.
i think the issue your having rather than the action="" if it is all on the same page is that your query isn't saying where you want each value to go
$query="INSERT INTO studentinfo (name, course, college, email) VALUES ('$name','$course','$college','$email')";
try changing your query to that but make sure the field names are correct i just guessed using your variables
You should first check that the $_POST is empty or not.Then you should save the data.So, use thid code:
<?php
$collegeerr = $nameerr = '';
if(isset($_POST) && !empty($_POST)) {
$name = '';
$college = '';
if(empty($_POST["name"])){
$nameerr="NAME IS REQUIRED";
}
else{
$name=$_POST["name"];
}
$course=$_POST["course"];
if(empty($_POST["college"])){
$collegeerr="NAME OF COLLEGE IS REQUIRED";
}else{
$college=$_POST["college"];
}
$email=$_POST["email"];
$abc=mysqli_connect('localhost','root','','generalinfo') or die('ERROR:COULD NOT CONNECT TO DATABASE');
$query="INSERT INTO studentinfo(name, course, college, email) VALUES ('$name','$course','$college','$email')";
$final=mysqli_query($abc,$query) or die('ERROR ENTERING THE DATA IN DATABASE');
mysqli_close($abc);
echo'THANKYOU FOR SUBMITTING THE FORM';
}
?>
There are lot of issues with this code.
you can do the following things to get it resolved
1. Wrap the post specific code inside a condition
You are executing the post handling code block even when the page is not posted. the code for handling post action has to be wrapped under an if condition which checks if the POST array is empy or not
2. Show the error variables only when they are set
Error vraibales used in side the form like $nameerr and $collegeerr are not set when the page is not posted. So you have to show them only when they are set. wrap them under a if(isset()) condition.
3. Remove unwanted lines which serve no purpose
As barmer says in the comments, lines like $name;$college; are of no use. They doesnt serve the purpose of variable declarations. You can remove them.
4. Turn error_reporting on
You are not seeing these errors because you might have turned your error reporting off in php.ini. Its better to turn it on as it helps a lot in debugging the code. You can do this by going to php.ini and setting display_errors property on.
code
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style1.css">
</head>
<body>
<?php
if(!empty($_POST)) {
if(empty($_POST["name"])){
$nameerr="NAME IS REQUIRED";
}
else{
$name=$_POST["name"];
}
$course=$_POST["course"];
if(empty($_POST["college"])){
$collegeerr="NAME OF COLLEGE IS REQUIRED";
}else{
$college=$_POST["college"];
}
if(!isset($nameerr) && !isset($collegeerr)){
$email=$_POST["email"];
$abc=mysqli_connect('localhost','root','','test') or die('ERROR:COULD NOT CONNECT TO DATABASE');
$query="INSERT INTO studentinfo VALUES ('$name','$course','$college','$email')";
$final=mysqli_query($abc,$query) or die('ERROR ENTERING THE DATA IN DATABASE');
mysqli_close($abc);
echo 'THANKYOU FOR SUBMITTING THE FORM';
}
}
?>
<div id="b">
<form action="" method="post">
<label for="name"><div id="a">name</div></label>
<input type="text" name="name"></br>
<div id="c"><?php if(isset($nameerr)) echo $nameerr; ?></div>
<label for="course"><div id="a">course</div></label>
<input type="text" name="course"></br>
<label for="email"><div id="a">email</div></label>
<input type="text" name="email"></br>
<label for="college"><div id="a">college</div></label>
<input type="text" name="college"></br>
<div id="d"><?php if(isset($collegeerr)) echo $collegeerr; ?></div>
<input type="submit" value="submit" name="sub"></br>
</form>
</div>
</body>
</html>
I am currently learning the most basic PHP ever. I have 5 files.
index.php:
<html>
<head>
<title>Budget Calcule</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Put in your: - </h2>
<form action="functions.php" method="post">
<h3>Income</h3>
<label>Salary: <input name="salary" type="text" /></label><br />
<h3>Outgoings</h3>
<label>Living: <input name="living" type="text" /></label><br />
<label>Insurance: <input name="insurance" type="text" /></label><br />
<label>Communication: <input name="communication" type="text" /></label><br />
<label>Loan: <input name="loan" type="text" /></label><br />
<label>Food & Drink: <input name="foodAndDrink" type="text" /></label><br />
<label>Entertaintment / Shopping: <input name="entertainmentOrShopping" type="text" /></label><br />
<label>Transport: <input name="transport" type="text" /></label><br />
<label>Other: <input name="other" type="text" /></label><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
this is my functions.php:
<?php
include('variables.php');
if(!($_POST['Submit'])){
if(isset($_POST['salary'])){
header('Location: output.php');
return $_POST['lon'];
}else{
echo "All fields are required";
}
}
?>
this is my variables.php:
<?php
$salary= $_POST['salary'];
$living= $_POST['living'];
$insurance= $_POST['insurance'];
$communication = $_POST['communication'];
$loan = $_POST['loan'];
$food = $_POST['food'];
$entertaintmentOrShopping = $_POST['entertaintmentOrShopping'];
$transport = $_POST['transport'];
$other= $_POST['other'];
?>
this is my output.php file:
<?php
include('outputFunction.php');
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
and last but not least, this is my outputFunction.php file:
<?php
include('variables.php');
function myText(){
echo "Your salary per month is: " . $_POST['salary'];
}
?>
Now you're thinking "why have he split up his code in different files?" Well first of all, I split the variables from functions.php because I wanted outputFunctions.php to get the variables from variables.php so i could echo my `$_POST['salary']; . The function myText(); outputs the text just fine, but it doesnt output the $_POST['salary'];.
I do not know why it doesnt work, I just wonder if you could be my extra eyes and see if I've done some mistake.
PS! Don't down vote my question just because you think it's stupid. I am having problem with this issue and been working on it for hours without advancing anywhere.
A few things:
You don't need to include a variables.php file. The variables you're accessing are global and you're just creating duplicates that aren't being used. They also go away after the page changes since you're re-declaring them each page load.
You are also trying to call a variable that doesn't exist when you reference $_POST['lon'] instead of 'loan'.
And finally to actually answer your question:
Your myText() function is referencing a variable that is not there anymore.
You need to merge functions.php and outputFunction.php and output.php into one file so the variables aren't lost and all the processing is done without opening a new file each time. I can see your original concept for separated files but an output file is going to be the file to process the input data from the form.
Now in your newly merged output.php, you should have something resembling this:
<html>
<head>
<title>Output</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
echo "Your salary per month is: " . $_POST['salary'];
}
} else {
echo "All fields required.";
}
?>
</body>
</html>
This means only two files - your form page and this page.
A few more tips:
If you want to check if the form was submitted, it has look something like this:
if(isset($_POST['Submit'])){ ... }
Also, you should add a name="" attribute to your submit-Button:
<input type="submit" name="Submit" value="Submit" />
And what is the variables.php for? You don't use any of those variables.
When you redirect the user via header() the data that is stored in the $_POST array gets lost.
You could directly redirect to ouput.php
<form action="output.php" method="post">
And do something like this:
<?php
include('outputFunction.php');
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
<?php
} else {
echo "All field required";
}
}
?>
By the way you can always check what your $_POST contains with print_r($_POST);
This can be very useful for debugging.
I am writing an intranet site in HTML, and what online users to be able to add in their own infomation (such as skype name) so that I dont have to go through and add it all myself for the 1000 people at the company, and also so that when new starters come in, they can add their own infomation themselves.
I currently have a 'Users' page with a link in it to another page where there is a form code in it looking like this:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label>Please type in a message
<input type="text" name="msg" id="msg" />
</label>
<label>and your name
<input type="text" name="name" id="name" />
</label>
<p>
<label>Submit
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</p>
</form>
<?php
$msg = $_POST["msg"];
$name = $_POST["name"];
$posts = file_get_contents("users.html");
$posts = "$msg - $name\n" . $posts;
file_put_contents("users.html", $posts);
echo $posts;
?>
I want the infomation users put into this form to be automatically put onto a list on the 'users.html' page, visible to everyone. I had hoped the above code would achieve this, but I cant get it to work.
Also, how would I specify whereabouts in the 'users.html' page the infomation is put? I want it to be amongst the:
<div id="content">
<div class="content_item">
..coding, so that it loads into a list inside the webpage.
Many Thanks in advance :)
Don't try to edit users.html with each submission. That way lies madness.
Store the submitted data in a database. Use the PDO library to do this.
Have the page that displays that data pull it from the database on demand.
Although the use of database would be better and files tend to grow rather large with time, am answering your actual question as per your posted code.
To show the values that were written from a form (seperate from below), you could set up a page with this inside it:
<div id="content">
<?php echo file_get_contents("users.html"); ?>
<div class="content_item">
And the seperate page form would be like the following (tested)
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title Here</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label>Please type in a message
<input type="text" name="msg" id="msg" />
</label>
<label>and your name
<input type="text" name="name" id="name" />
</label>
<p>
<label>Submit
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</p>
</form>
</body>
</html>
<?php
if(isset($_POST['submit']) && empty($_POST['msg']) && empty($_POST['name']) ) {
die("All fields need to be filled, please try again.");
}
if(isset($_POST['submit'])) {
$msg = $_POST["msg"];
$name = $_POST["name"];
$posts = $msg . "-" . $name;
$file = "users.html";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $posts . "\n<br>") or die("Couldn't write values to file!");
fclose($fp);
}
echo $posts;
echo "<hr>Previous messages<hr>";
$file = "users.html";
if (file_exists($file)) {
$fp = file_get_contents($file, "r") or die("Couldn't open $file for writing!");
echo $fp;
exit;
}
else {
echo "The file is empty";
}
?>
I have a php script for a number-guessing game and an html script for a congratulation page. If the guess is correct, the game will end and the congratulation page will open. In the php, I have a variable $prize=1000-100 * $_POST['tries'], such that if the first guess is right, the player will win $1000; if the player has a second guess, the prize will be $100 less, and so on. This variable is saved in a hidden field in the php as $_POST['prize']. I hope the final prize can be printed in the congratulation page, but it didn’t work as I expected. Did I do anything wrong in the html? Thanks guys, Maria.
guess.php:
<?php
if(isset($_POST['number'])) {
$num = $_POST['number'];
} else {
$num = rand(1,10);
}
if(isset($_POST['prize'])) {
$prize =1000-100 * $_POST['tries'];
} else {
$prize = 900;
}
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;
if (!isset($_POST['guess'])) {
$message="Welcome to the Guessing Game!";
} elseif (!is_numeric($_POST['guess'])) {
$message="You need to type in a number.";
} elseif ($_POST['guess']==$num) {
header("Location: Congrats.html");
exit;
} elseif ($_POST['guess']>$num) {
$message="Try a smaller number";
} else {
$message="Try a bigger number";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number: </strong><?php echo $tries; ?></p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" />
<input type="hidden" name="tries" value="<?php echo $tries; ?>"/><br/>
<input type="hidden" name="number" value="<?php echo $num; ?>"/><br/>
<input type="hidden" name="prize" value="<?php echo $prize; ?>"/>
</p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
congrats.html:
<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_POST['prize']; ?> dollars!
</body>
</header>
</html>
it looks like your script will work, but you'll need to change congrats.html to congrats.php because html is static and php is dynamic. Also you might want to use sessions because anyone can inspect-element and change the value.
You just need to pass the value to the congrats page, using either GET request or a session. I'd recommend using a session so people cannot alter the prize value.
Just amend this part here:
} elseif ($_POST['guess']==$num) {
$_SESSION['prize'] = $_POST['prize'];
header("Location: Congrats.php");
exit;
}
Then (you need to change the congrats page to a php page to use the session btw to enable php)
Congrats.php
<! DOCTYPE html>
<html>
<header>
<title>Congratulation!</title>
<body>Congratulation!<br/>
You Won <?php echo $_SESSION['prize']; ?> dollars!
</body>
</header>
</html>
PS: Session will also require session_start() at the top of both documents.