<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE = "HTML">
<html>
<head>
<meta charset = "UTF-8">
</head>
<body>
<p1><h1>Guitar Wars - High Scores</h1></p1>
<hr />
<p2> The screenshot must be an image file no greater than 2MB in size.</p2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="2100000" />
<label for="name">Name: </label>
<input type="text" id="name" name="name" /><br />
<label for="score">Score: </label>
<input type="text" id="score" name="score" /><br />
<label for "screenshot">Screen shot: </label>
<input type="file" id="screenshot" name="screenshot" />
<hr />
<input type="submit" name="submit" value="Add" /><br />
</form>
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot = $_FILES['screenshot']['name'];
$screenshot_type = $_FILES['screenshot']['type'];
$screenshot_size = $_FILES['screenshot']['size'];
require_once('appvars.php');
if (isset($_POST['submit'])){
// Level 1
if ((!empty($name) && !empty($score)) {
// Level 2
$db = mysqli_connect('localhost','****','****','guitarwars') or die('cannot connect to server');
$query = "INSERT INTO scoreboard (date, name, score, screenshot) VALUES (NOW(),'$name', '$score', '$screenshot')";
$result = mysqli_query($db,$query) or die (mysqli_error($db));
echo $name.', your score has been added successfully!<br><br>';
if (($_FILES['screenshot']['error'] == 0) && ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/png')) && (($screenshot_size > 0) && ($screenshot_size <= GW_MAXSIZE)))){
// Level 3
echo "File name: ".$screenshot."<br>";
echo "Type: " . $screenshot_type . "<br>";
echo "Type: " . $screenshot_size . " bytes<br>";
$target = GW_UPLOADPATH.$screenshot;
$move = move_uploaded_file($_FILES['screenshot']['tmp_name'], $target);
}
else {
// Level 3
echo '<p class = "error">Adding score failed, you can upload only image file under 2MB in size.'.$_FILES['screenshot']['error'].'</p>';
}
}
else {
// Level 2
echo '<p class = "error">Adding score failed, you must fill all the fields.</p>';
}
mysqli_close($db);
}<--- this is the last bracket
?>
<p>Go to the scoreboard!</p>
</body>
</html>
My text-editor(coda) sounds beep(alert) when I move cursor over the last bracket'}'. However I can't figure out what's wrong with that bracket.
And I added codes for displaying errors which neither works.
Thank you in advance.
Your problem is in this line:
if ((!empty($name) && !empty($score)) {
You have a ( to many.
It should be:
if (!empty($name) && !empty($score)) {
if ((!empty($name) && !empty($score)) {
You have too few ) here, which is causing the {...} around it (your "Level 1" braces) to overlap the () parentheses.
Related
I want to clear or hide the HTML text (HTML form) when the PHP code is executed.
I just want to show if (isset($_POST['submit'])) {}.
The following is my code called in index.php.
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<div class="formku">
<legend><b>Input Score (0 - 4)</b></legend>
<form action="" method="post">
<legend><span class="number">1</span>N1 : </legend>
<input required type="text" name="n1" />
S1 :
<input required type="text" name="s1" /> <br/>
<legend><span class="number">2</span>N2 : </legend>
<input required type="text" name="n2" />
S2 :
<input required type="text" name="s2" /> <br/>
<input type="submit" name="submit" value="Count"/>
</form>
<hr>
<?php
if (isset($_POST['submit'])) {
$vn1 = $_POST['n1'];
$vn2 = $_POST['n2'];
echo '<h2>Result</h2>';
echo 'Final score N1 = ' . $vn1 * $vs1 . '<br>';
echo 'Final score N2 = ' . $vn2 * $vs2 . '<br>';
$tn = ($vn1 * $vs1) + ($vn2 * $vs2);
$ts = $vs1 + $vs2;
$ip = $tn / $ts;
echo 'IP Value: ' . $ip;
echo '<br>';
echo 'You got: ';
if ($ip >= 4)
echo 'A';
else if ($ip >= 3)
echo 'B';
else if ($ip >= 2)
echo 'C';
else if ($ip >= 1)
echo 'D';
else
echo 'E';
}
?>
</div>
</body>
</html>
Just use else condition:
<?php
if (isset($_POST['submit'])) {
//show the message of submit
$vn1 = $_POST['n1'];
$vn2 = $_POST['n2'];
....
} else {
//show the form data
?>
<form ...>
</form>
<?php } ?>
Inside the if statement you can echo the following:
<script type="text/javascript">
document.getElementsByClassName('formku')[0].display = "none";
</script>
I'm busy studying a book on php and they have an exercise on deleting records from a database. The issue I am having is deleting the image that is associated with the database entry. I have a defined constant of:
define(GW_UPLOADPATH, 'images/')
in a file called appvars.php. Here is the remove.php
<?php
require_once 'authorize.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require_once 'appvars.php';
require_once 'connectionvars.php';
if(isset($_GET['id']) && isset($_GET['name']) && isset($_GET['score']) && isset($_GET['date'])
&& isset($_GET['screenshot'])){
$id = $_GET['id'];
$name = $_GET['name'];
$score = $_GET['score'];
$date = $_GET['date'];
$screenshot = $_GET['screenshot'];
} else if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['score']) && isset($_POST['date'])){
$id = $_POST['id'];
$name = $_POST['name'];
$score = $_POST['score'];
$date = $_POST['date'];
} else {
echo 'No record selected';
}
if(isset($_POST['submit'])){
if(($_POST['confirm'] == 'Yes') && is_file(GW_UPLOADPATH.$screenshot)){
unlink(trim(GW_UPLOADPATH.$screenshot));
$query = "DELETE from guitarwars where id = $id limit 1";
mysqli_query($dbc, $query);
mysqli_close($dbc);
echo '<p class="error">The score of ' . $score . ' for' . $name . ' was successfully deleted</p>';
} else {
echo '<p class="error">Error removing record</p>';
}
}
else if(isset ($id) && isset($name) && isset($date) && isset($score) && isset($screenshot)){
echo '<p>Are you sure you want to delete the following high score?</p>';
echo '<p>Name: ' . $name . '<br />Date: ' . $date . '<br />Score: ' . $score . '<br />'
. 'PATH:' . GW_UPLOADPATH.$screenshot. '</p>' ;
echo '<form method="POST" action="remove.php">';
echo '<input type="radio" name="confirm" value="Yes" />Yes<br />';
echo '<input type="radio" name="confirm" value="No" checked="checked" />No<br />';
echo '<input type="submit" name="submit" value="Submit">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo '<input type="hidden" name="name" value="' . $name . '">';
echo '<input type="hidden" name="date" value="' . $date . '">';
echo '<input type="hidden" name="score" value="' . $score . '">';
echo '</form>';
}
echo '<p>Back to Admin page</p>';
?>
</body>
</html>
the database removes the entry 100% but i get an error that image is a directory. if you view the html it reports the path as images/imageName.gif
The is_file() I added to try figure out what is going on and as a result I now get my assigned error message "Error removing record". So what I think, its not seeing my imageName.gif as a file. not sure how else to remove the file, the book pacifically uses unlink.
Any guidance is greatly appreciated
ADDED: addscore.php
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guitar Wars - Add Your High Score</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h2>Guitar Wars - Add Your High Score</h2>
<?php
require_once 'appvars.php';
require_once 'connectionvars.php';
if (isset($_POST['submit'])) {
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot = $_FILES['screenshot']['name'];
$screenshot_type = $_FILES['screenshot']['type'];
$screenshot_size = $_FILES['screenshot']['size'];
if (!empty($name) && !empty($score) && !empty($screenshot)) {
if((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/pjpeg')
|| ($screenshot_type == 'image/png')) && (($screenshot_size > 0) && ($screenshot_size <= GW_MAXUPLOADSIZE))){
$target = GW_UPLOADPATH.$screenshot;
if(move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)){
// Write the data to the database
$query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or die('Error inserting data: ' . mysqli_error($dbc));
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '<br />';
echo '<img src="' . GW_UPLOADPATH.$screenshot . '" alt="screenshot image" /></p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
} else {
echo '<p class="error">Please ensure image file is corrent format and less than ' . (GW_MAXUPLOADSIZE / 1024) .
'Kb</p>';
}
#unlink($_FILES['screenshot']['tmp_name']);
}
else {
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
<hr />
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768"/>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" /><br />
<label for="screenshot">Screen Shot:</label>
<input type="file" id="screenshot" name="screenshot" />
<hr />
<input type="submit" value="Add" name="submit" />
</form>
</body>
</html>
I think the issue is that $screenshot is undefined...
Simplifying the code a bit, you have:
if(isset($_GET['screenshot'])) {
$screenshot = $_GET['screenshot'];
} else if(isset($POST['id')) {
}
if(isset($_POST['submit'])){
if(($_POST['confirm'] == 'Yes') && is_file(GW_UPLOADPATH.$screenshot)){
So... assuming you aren't doing something really weird, a request will either be a GET request, or a POST request. You only set $screenshot if it's a GET request, but you are checking is_file only on a POST request. So you are checking is_file("images/") and it is (correctly) telling you it is a directory.
Try this:
else if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['score']) && isset($_POST['date']) && isset($_POST['screenshot'])){
$id = $_POST['id'];
$name = $_POST['name'];
$score = $_POST['score'];
$date = $_POST['date'];
$screenshot = $_POST['screenshot']; //<-- add this line
}
...
echo '<form method="POST" action="remove.php">';
echo '<input type="radio" name="confirm" value="Yes" />Yes<br />';
echo '<input type="radio" name="confirm" value="No" checked="checked" />No<br />';
echo '<input type="hidden" name="screenshot" value="$screenshot" />'; //<-- add this line
I have a problem with preserving the values written inside a textfield, if an error occurs. I have 4 textfields, and if 1 is blank it needs to show a new form, with a error message and the input in the textfield from the previous file.
I guess it's the last part of my assignment_2.php where it's wrong.
assignment_1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="sendit.php" method="get">
<input type="text" name="name" placeholder="name"/>
<br>
<input type="text" name="adress" placeholder="adress"/>
<br>
<input type="text" name="city" placeholder="city"/>
<br>
<input type="text" name="zip" placeholder="zip"/>
<br>
<input type="submit" />
</form>
<br>
</body>
</html>
sendit.php
<?php
$name = $_GET['name'];
$adress = $_GET['adress'];
$city = $_GET['city'];
$zip = $_GET['zip'];
if (!isset($_GET['name']) || $_GET['name'] == '') {
header("Location: assignment_2.php?errmsg=1");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&name=$name");
}
if (!isset($_GET['adress'])|| $_GET['adress'] == '') {
header("Location: assignment_2.php?errmsg=2&adress=$adress");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&adress=$adress");
}
if (!isset($_GET['city'])|| $_GET['city'] == '') {
header("Location: assignment_2.php?errmsg=3&city=$city");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&city=$city");
}
if (!isset($_GET['zip'])|| $_GET['zip'] == '') {
header("Location: assignment_2.php?errmsg=4&zip=$zip");
exit;
}
else {
header("Location: assignment_2.php?errmsg=4&zip=$zip");
}
echo $name . "<br>" . $adress . "<br>" . $city . "<br>" . $zip
?>
assigment_2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// 1.0 Create a contactform containing name, address, city, zipcode
// Send it to a form handler
// If any of the form fields are not filled out, return to this page and
// display an error containing information on how to prevent the error
// 1.1 Preserve the input for the user
?>
<?php
if (isset($_GET['errmsg'])) {
$err = $_GET['errmsg'];
switch ($err) {
case 1:
$err_msg = 'Missing navn';
break;
case 2:
$err_msg = 'Missing adress';
break;
case 3:
$err_msg = 'Missing city';
break;
case 4:
$err_msg = 'missing zip';
break;
default:
$err_msg = 'I just dont like you';
break;
}
echo '<div class="error">' . $err_msg . '</div>';
}
?>
<form action="sendit.php" method="get">
<input type="text" name="name" placeholder="name" <?php
if (isset($_GET['name'])) echo 'value="' .$_GET['name'] .'"';
?> />
<br>
<input type="text" name="adress" placeholder="adress" <?php
if (isset($_GET['adress'])) echo 'value="' .$_GET['adress'] .'"';
?>/>
<br>
<input type="text" name="city" placeholder="city" <?php
if (isset($_GET['city'])) echo 'value="' .$_GET['city'] .'"';
?>/>
<br>
<input type="text" name="zip" placeholder="zip" <?php
if (isset($_GET['zip'])) echo 'value="' .$_GET['zip'] .'"';
?>/>
<br>
<input type="submit" />
</form>
</body>
</html>
I will probably handle first client side validation, so the form will not submit until all inputs get fill, then I will do some server side validation and sanitization. BTW you don't need to have assigment2.
Keep things simple!
For starters, try working on only one file, and put your errors into an array.
Then try shortening your code, and to never "copy & paste" code.
On modern sites, developpers use frameworks to validate forms,
Keep playing with this one until it works like you want, and have a look at Symfony or Zend Framework form validation.
<?php
$errors = array();
if (isset($_GET['submitted'])) {
if (!isset($_GET['name']) || $_GET['name'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['adress']) || $_GET['adress'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['city']) || $_GET['city'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['zip']) || $_GET['zip'] == '')
$errors[] = 'Missing navn'
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
if (count($errors) !== 0)
echo '<div class="error">' . implode("<br>", $errors) . '</div>';
?>
<form action="" method="get">
<input type="hidden" name="submitted" value="1" />
<input type="text" name="name" placeholder="name" value="<?php echo isset($_GET['name']) ? $_GET['name'] : '' ?>" />
<br>
<input type="text" name="adress" placeholder="adress" value="<?php echo isset($_GET['adress']) ? $_GET['adress'] : '' ?>" />
<br>
<input type="text" name="city" placeholder="city" value="<?php echo isset($_GET['city']) ? $_GET['city'] : '' ?>" />
<br>
<input type="text" name="zip" placeholder="zip" value="<?php echo isset($_GET['zip']) ? $_GET['zip'] : '' ?>" />
<br>
<input type="submit" />
</form>
<br>
</body>
</html>
I am trying to update a record in a database. The code is meant to allow users to update an entry on a website with the option to edit the image as well. When I was initially testing this code it worked with no issues. When they selected an image it would update the image, and when they did not select an image it would not include the image in the updating. When I moved this code to the page that it needs to be on it is no longer working. It is always reading it as if the user has not selected an image to upload. The only thing that has changed between the test code and this code is the names in the database, and the addition of mysql_real_escape_string() for the variables $title and $description.
Here is the PHP code that is not working for me:
<?php
require_once ("connect.php");
if (isset($_POST['description'])) {
$id = $_GET['id'];
$title = $_POST['title'];
$description = $_POST['description'];
$title = mysql_real_escape_string($title);
$description = mysql_real_escape_string($description);
$target = "../images/contests/";
$target = $target.basename( $_FILES['image']['name']);
$ok=1;
if($_FILES['image']['name'] == "") {
$query = "UPDATE tbl_contests SET contests_title='$title', contests_description='$description' WHERE contests_id='$id'";
$result = mysql_query ($query);
if ($result) {
header ("Location: contests.php?=noimage");
exit ();
} else {
header ("Location: contests.php?=error");
exit ();
}
} else {
if ($ok==0){
header("Location: contests.php?=error");
} else {
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
echo "<p>Your upload was sucessful.</p>";
$query = "UPDATE tbl_contests SET contests_title='$title', contests_description='$description', contests_image='$target' WHERE contests_id='$id'";
$result = mysql_query ($query);
if ($result) {
header ("Location: contests.php?=image");
exit ();
} else {
header ("Location: contests.php?=error");
exit ();
}
}
}
}
}
?>
Here is the form pertaining to the above code:
<?php
$postnum = $_GET['id'];
$query = "SELECT * FROM tbl_contests WHERE contests_id=".$postnum;
$result= mysql_query($query);
$row = mysql_fetch_array($result);
$path = "../images/contests/";
?>
<form action="update-past.php?id=<?php print $row[contests_id]; ?>" method="post" id="updatepast">
<br /><label>Title:</label> <p><input type="text" name="title" id="title" class="input" value="<?php print $row[contests_title]; ?>" /></p>
<?php if ($row['contests_image'] == !null) { ?>
<p><img src="<?php print $path.$row['contests_image']; ?>" width="425" height="500" /></p>
<br /><label>Edit Image: (Optional)</label> <p><input name="image" type="file" id="image" class="file" size="50" /></p>
<?php } else { ?>
<br /><br /><br /><br /><label>Add Image: (Optional)</label> <p><input name="image" type="file" id="image" class="file" size="50" /></p>
<?php } ?>
<br /><br /><br /><br /><br /><label>Description:</label><p><textarea name="description" cols="85" id="description" class="contentinput" rows="10"><?php print $row[contests_description]; ?></textarea></p>
<p><input type="submit" name="submit" id="button" value="Edit" /></p>
</form>
Try adding this to the form: enctype="multipart/form-data"
Here's some reading on form content types: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
I have the following code for submitting a form - it doesn't do much at the moment but what I am looking to achieve is this:
The textbox docTitle is a required field.
If the yourName textbox has text in it and the docTitle textbox is left blank, when submitted the required field message appears and the yourName textbox retains it's value.
I'm struggling with the part where the form retains the previous values after submitting.
Here's the code:
<?php
if(isset($_POST['submit'])) {
if(empty($docTitle)) {
} else {
if ((($_FILES["file"]["type"] == "application/pdf")) && ($_FILES["file"]["size"] < 2000000) && ($_POST["docTitle"] > "")) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"];
if (file_exists("upload/pdf/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'],
"upload/pdf/" . $_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
}
}
?>
<form name="uploadAPdf" id="uploadAPdf" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
<label for="text">Name: </label> <input type="text" name="yourName" id="yourName" /><br />
<label for="text">Document: </label> <input type="text" name="docTitle" id="docTitle" />
<?php if(isset($_POST['submit']) && empty($docTitle)) {
echo " Document title must be filled in...";
echo "<script type='text/javascript'>document.uploadAPdf.docTitle.focus();</script>";
} ?>
<br />
<label for="file">Select PDF to upload: </label> <input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
Isn't this what you want:
<?php
function postValue($name, $alt = '') {
return isset($_POST[$name]) ? $_POST[$name] : $alt;
}
?>
<label for="text">Name: </label> <input type="text" name="yourName" id="yourName" value="<?=htmlspecialchars(postValue('yourName'))?>" /><br />
<label for="text">Document: </label> <input type="text" name="docTitle" id="docTitle" value="<?=htmlspecialchars(postValue('yourName'))?>" />
That's (sort of) how most Forms work...
Maybe I'm missing something =)
edit
This is a function I used to use when I didn't use a PHP framework:
<?php
function ifsetor($var, $alt = '') {
return isset($var) ? $var : $alt;
}
?>
which would be used like this:
<?php
$selectedOptions = ifsetor($_POST['options'], array());
?>
edit
Unrelated: you might want to put your form elements in a wrapper (instead of separating them with a <br>) like this:
<div class="form-element"><label>...</label><input .... /></div>
change your html input(s) code to:
<input type="text" name="docTitle" id="docTitle" value="<?php echo htmlspecialchars($_POST['docTitle']; ?>" />