(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:
First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?
Here is my code:
<?php
if ($_POST['form'] == "Submit") {
$err = array();
$filed = addslashes($_FILES['file']['tmp_name']);
$img_named = addslashes($_FILES['file']['name']);
$img_type = addslashes($_FILES['file']['type']);
#$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));
function getExtension($str)
{
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$extension = getExtension($img_named);
$extension = strtolower($extension);
$image_named_uniq = uniqid() . '.' . $extension;
$upload_path_dis = 'user/manage/discussionimg/';
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else {
$uname = $_SESSION['uname']; //session username
if (empty($sub) && empty($msg) && empty($filed))
$err[] = "All field required";
else {
if (empty($sub))
$err[] = "Subject Requried";
if (empty($msg))
$err[] = "Message Requried";
if (empty($filed))
$err[] = "SORRY, you have to be upload a image";
}
}
if (!empty($err)) {
foreach ($err as $er) {
echo "<font color=red>$er</font><br/>";
}
}
else {
$sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
if (!$sql)
echo "Can't submit your discussion" . mysql_error();
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
die('File Not Uploading');
} else {
echo "Discussion was submitted";
}
}
}
?>
Many Thanks for your help!!
Kanta.
Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"]; ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert. You have to do few controls. However these things depend on your data.
a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.
Related
I have code to validate my form before trying to upload anything.
I think I have nested the if statements incorrectly and that's why its not working properly.
I have put my PHP and HTML form code in a fiddle for anyone who is willing to have a look: https://jsfiddle.net/1htqcyun/
Here is a snippet of the PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//if the year is left empty then show error, if not then test_input
if (empty($_POST["year"])) {
$yearErr = "*enter a year";
} else {
$year = test_input($_POST["year"]);
}
//if the description is left empty then show error
if (empty($_POST["description"])) {
$descriptionErr = "*enter a description";
} else {
$description = test_input($_POST["description"]);
}
// If the date has not been selected in the drop down, and the select is left at "Please Select" value = 0
if(isset($_POST['dateID']) && $_POST['dateID'] == '0'){
$decadeErr = "*select a decade";
}
else {
$dateID = test_input($_POST["dateID"]);
}
FYI - using jsFiddle for a PHP example is not helpful. Try http://phpfiddle.org/
I think the issue is in calling the $_FILE variable too soon, on line 10 of your code:
$target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
If you're running the script the first time, this would fail. I would change this to:
if(!empty($_POST)){
if(!empty($_FILES["file_upload"])){
$target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["uploaded"]["tmp_name"]);
}
$year = $description = $dateID = "";
$yearErr = $descriptionErr = $decadeErr = "";
// continue the rest of your $_POST handling...
}
This way if nothing is posted, as would be the case on it's first run, the script does not try to handle items that have not yet been posted.
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
I'm new to PHP. I added in the isset command, and the form is working with the database but every time I bring up this page it automatically submits a blank record to my database. How can I make it so that it only runs through the PHP commands if an input is entered and a user hits submit?
<?php
$handle = isset($_POST['handle']);
$address = isset($_POST['address']);
$code = isset($_POST['code']);
$rrr=mysqli_connect("localhost","knock_knock","whosthere","1");
if (mysqli_connect_errno()) {
echo "Connection to DB failed" . mysqli_connect_error();
}
$handle2 = mysqli_real_escape_string($rrr, $handle);
$address2 = mysqli_real_escape_string($rrr, $address);
$code2 = mysqli_real_escape_string($rrr, $code);
if(empty($handle)){
echo "Handle can not be empty";
}
$sql="INSERT INTO players (Handle, Address, Code)
VALUES ('$handle2', '$address2', '$code2')";
if (!mysqli_query($rrr,$sql)) {
die ('Error: ' . mysqli_error($rrr));
}
echo "Record added";
mysqli_close($rrr);
?>
$handle = isset($_POST['handle']);
$address = isset($_POST['address']);
$code = isset($_POST['code']);
the above code will store true in all the variables if the are set.it should be -
$handle = isset($_POST['handle']) ? $_POST['handle'] : false;
$address = isset($_POST['address']) ? $_POST['address'] : false;
$code = isset($_POST['code']) ? $_POST['code'] : false;
and all code that is supposed to be executed after the form submit should be placed in -
if (isset($_POST['submit'])) {
//code to be executed
}
submit or whatever the field is for submit button. and then the checks should be added for empty values.
you have to stop the execution or redirect.
if(empty($handle)){
header('location:page.php?msg=yourmessage');
exit;
}
or
if(empty($handle)){
echo "Handle can not be empty";
exit;
}
Put a simple if condition at the top
$handle =$_POST['handle'];
if(empty(isset($handle)) || $handle=='')
{
echo "Handle can not be empty";
}
else
{
//Your stuff
}
I've been struggling to have a text form field required. So when some one doesn't fill his name he will receive an error like 'No title filled!'
I got this now but it doesn't work that well cause when I submit it insert into the db.
if(isset($_POST['submit'])) {
$update = "UPDATE post SET `title`='$_POST[title]', `pic`='$_POST[pic]', `youtube`='$_POST[youtube]' WHERE id = $_POST[id]";
$db->query($update) or die($db->error);
if($_POST['title'] == "") {
$error = "Title is required!";
}
if ($_POST['pic'] == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
echo '<p>Your post has been updated!</p>';
}
}
You need to stop your code from being executed if an error is found, not just echo the error. All your other code that submits the data to the database should ONLY be executed if there is no error. Try something like this:
Edit: Upon seeing the update to your code, this is what you need to do:
if(isset($_POST['submit'])) {
if(!isset($_POST['title']) || trim($_POST['title']) == "") {
$error = "Title is required!";
}
if (!isset($_POST['pic']) || trim($_POST['pic']) == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
$update = "UPDATE post SET `title`='" . mysql_real_escape_string($_POST['title']) . "', `pic`='" . mysql_real_escape_string($_POST['pic']) ."', `youtube`='" . mysql_real_escape_string($_POST['youtube']) ."' WHERE id = " . mysql_real_escape_string($_POST['id']);
$db->query($update) or die($db->error);
echo '<p>Your post has been updated!</p>';
}
}
The problem is, your data was being submitted to the database no matter what happened after with the validation - by the time you checked for errors it was too late, as the SQL had already been executed.
If you do it the way shown above, it will only submit if the $error variable is not set, which is what you want.
I wouldn't just rely on
if($_POST['title'] == "")
because it will not work if someone enters a space into the text field. For one thing, a title shouldn't be too long? So you can set a max-length for it?
Also maybe run a few more checks such as:
I wouldn't just rely on
if(!isset($_POST['title'] || $_POST['title'] == "" || $_POST['title'] == " ")
{
// Error
}
else
{
// Database query
}
You want the else, otherwise it will always execute the database query, whether or not they haven't filled out the form properly.
I wonder whether someone may be able to help me please.
I've put together this form which, if you scroll to the bottom of the page, has multiple submission buttons. i.e 'Submit', 'Deleted selected image' and 'View Selected Image'.
I posted a query on this site yesterday here, about about how to go about dealing with multiple 'submission' buttons and received some great advice.
I've tried to implement the advice I was given, but I just can't seem to get this to work. As the guidance suggested, I've added a name to each button and tried to call that through the PHP script, but all that happens is the page refreshes as if submitting the whole page, rather, than for example, being able to view the selected file.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Please find my PHP code & Form script below
<?php
$db_host = 'host';
$db_user = 'username';
$db_pwd = 'password';
$database = 'databasename';
$table = 'images';
// use the same name as SQL table
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!isset($_POST["action"]))
{
// cleaning title field
$title = trim(sql_safe($_POST['title']));
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//print_r($_FILES);exit;
if($_FILES["photo"]["error"] >= 4) {
$msg = '<b>Error!</b> - You <b> must </b> select a file before clicking the <b> "Upload This Image" </b> button. Please try again.';
}
else
if (isset($_FILES['photo']))
{
list($width, $height, $imtype, $attr) = getimagesize($_FILES['photo']['tmp_name']);
if ($imtype == 3) // cheking image type
$ext="png"; // to use it later in HTTP headers
elseif ($imtype == 2)
$ext="jpeg";
elseif ($imtype == 1)
$ext="gif";
else
$msg = '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "gif", "jpeg" </b> or <b> "png" </b>. Please try again.';
if($_FILES["photo"]["size"]/1150000 >= 1) {
$msg = '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
}
if (!isset($msg)) // If there was no error
{
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO {$table}
SET ext='$ext', title='$title',
data='$data'");
$msg = '<b> Success! </b> - Your image has been uploaded';
}
}
elseif (isset($_GET['title'])) // isset(..title) needed
$msg = 'Error: file not loaded';// to make sure we've using
// upload form, not form
// for deletion
if (isset($_POST['deleteimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
if (isset($_POST['viewimage'])) // If used selected some photo to delete
{ // in 'uploaded images form';
$imageid = intval($_POST['view']);
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid");
if(mysql_num_rows($result) == 1)
{
$image = $row['myimage'];
header("Content-type: image/gif"); // or whatever
print $image;
exit;
}
}
}
else
{
$imageid = intval($_POST['del']);
if ($_POST["action"] == "view")
{
$result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
FROM {$table}
WHERE imageid=$imageid LIMIT 1");
if (mysql_num_rows($result) == 0)
die('no image');
list($ext, $imagetime, $data) = mysql_fetch_row($result);
$send_304 = false;
if (php_sapi_name() == 'apache') {
// if our web server is apache
// we get check HTTP
// If-Modified-Since header
// and do not send image
// if there is a cached version
$ar = apache_request_headers();
if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
($ar['If-Modified-Since'] != '') && // not empty
(strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
$send_304 = true; // imagetime
}
if ($send_304)
{
// Sending 304 response to browser
// "Browser, your cached version of image is OK
// we're not sending anything new to you"
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);
exit(); // bye-bye
}
// outputing HTTP headers
header('Content-Length: '.strlen($data));
header("Content-type: image/{$ext}");
// outputing image
echo $data;
exit();
}
else if ($_POST["action"] == "delete")
{
$imageid = intval($_POST['del']);
mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
$msg = 'The image which you selected has now been deleted!';
}
}
}
?>
<form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
<div align="left">
<!-- This form is used for image deletion -->
<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
echo '<ul><li>You have no images loaded</li></ul>';
else
{
echo '<ul>';
while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
{
// outputing list
echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
echo " <small>{$title}</small>  ";
echo "<small>{$imagetime}</small></li>";
}
echo '</ul>';
echo '<input type="submit" value="Delete Selected Image" onclick="document.getElementById(\'action\').value=\'delete\'" />';
echo '<input type="submit" value="View Selected Image" onclick="document.getElementById(\'action\').value=\'view\'" />';
}
?>
<input type="hidden" name="action" id="action" />
</div>
</form>
Many thanks and kind regards
Where you're checking the $_POST action, you need to do this:
if ($_POST["viewimage"] == "View Selected Image") { // Do stuff }
if ($_POST["deleteimage"] == "Delete Selected Image") { // Do stuff }
Basically, you need to check $_POST['name'] == 'value'