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'
Related
I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.
Thanks for the support really appreciated.
I am newbie in PHP, and i heard that i can find my solution from those PHP expert who are here in Stackoverflow.
I have bought this script a while ago and now the producer stopped offering support.
Avatar upload form
http://i.stack.imgur.com/YO7PD.jpg
My Question
The script have ability to upload profile for every user but it doesn't resize the image.
If a user upload a 2 mb image so the script use 2 mb image in all over the website which makes my website to run slower.
I want that the script should resize the image to
([width=100px and height=auto] and
[width=19px and height=auto])
so i use a lighter image in size (like ~150 kb and ~55kb) and let my site run faster.
This is the avatar.php file that process the uploading
<?php
// declare variables
$msg = '';
$f_avatar_image = '';
// ------------------------------------------------------------
// UPLOAD AVATAR
// ------------------------------------------------------------
if(isset($_POST['btnUploadAvatar']) && !empty($_FILES['fileUpload']['name']))
{
// create variables
$avatar_directory = AVATAR_FILE_DIRECTORY;
$file_name = $_FILES['fileUpload']['name'];
$file_type = $_FILES['fileUpload']['type'];
$file_size = $_FILES['fileUpload']['size'];
$file_size_limit = AVATAR_FILE_SIZE;
$calc_kilobites = 1024;
$file_size_kb = round($file_size / $calc_kilobites, 2);
$temp_file_name = $_FILES['fileUpload']['tmp_name'];
$upload_error = $_FILES['fileUpload']['error'];
// create unique file name
$unique_file_name = $user_name.'-'.$file_name;
$avatar_img_url = AVATAR_IMAGE_URL.$user_name.'-'.$file_name;
// if upload error display error message
if($upload_error > 0)
{
echo 'ERROR:' . $upload_error;
}
// if no upload error - check for file types
if($upload_error == 0 &&
$file_type == 'image/gif' ||
$file_type == 'image/jpeg' ||
$file_type == 'image/png' )
{
// if file size is within limits
if($file_size <= $file_size_limit)
{
// move uploaded file to assigned directory
if(move_uploaded_file($temp_file_name, $avatar_directory . $unique_file_name))
{
// get user id
$get_user_id = mysqli_query($conn, "SELECT UserId FROM users WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
// if user id exist
if(mysqli_num_rows($get_user_id) == 1 )
{
$row = mysqli_fetch_array($get_user_id);
$user_id = $row['UserId'];
// check if user profile already exist
$check_user_profile = mysqli_query($conn, "SELECT UserId FROM profiles WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
// if user profile exist - update
if(mysqli_num_rows($check_user_profile) == 1 )
{
// update profiles
$update_profile = mysqli_query($conn, "UPDATE profiles SET AvatarImage = '$avatar_img_url' WHERE UserName = '$user_name'") or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
echo 'Upload Success! <br/>';
echo 'File Name: '.$file_name.'<br/>';
echo 'File Type: '.$file_type.'<br/>';
echo 'File Size: '.$file_size_kb.' Kb <br/>';
$msg = $profile_update_success;
}
else
{
$msg = $profile_update_failed;
}
}
else
{
// create profile
$insert_profile = mysqli_query($conn, "INSERT INTO profiles(UserId,UserName,AvatarImage) VALUES($user_id,'$user_name','$avatar_img_url')") or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
echo 'Upload Success! <br/>';
echo 'File Name: '.$file_name.'<br/>';
echo 'File Type: '.$file_type.'<br/>';
echo 'File Size: '.$file_size_kb.' Kb <br/>';
$msg = $profile_update_success;
}
else
{
$msg = $profile_create_failed;
}
}
}
else
{
// user id not found
$msg = $profile_update_failed2;
}
}
else
{
$msg = $avatar_upload_failed;
}
}
else
{
$msg = $avatar_file_too_large;
}
}
else
{
$msg = $avatar_wrong_file_type;
}
}
elseif(isset($_POST['btnUploadAvatar']) && empty($_FILES['fileUpload']['name']))
{
$msg = $avatar_empty;
}
// ------------------------------------------------------------
// DISPLAY AVATAR ON PAGE LOAD
// ------------------------------------------------------------
if($user_name)
{
// get user id
$get_avatar_image = mysqli_query($conn, "SELECT AvatarImage FROM profiles WHERE UserName = '$user_name' Limit 1") or die($dataaccess_error);
if(mysqli_num_rows($get_avatar_image) == 1)
{
$row = mysqli_fetch_array($get_avatar_image);
if($row['AvatarImage'] != 'NULL' && $row['AvatarImage'] != '')
{
$f_avatar_image = $row['AvatarImage'];
}
else
{
$f_avatar_image = AVATAR_IMAGE_URL.DEFAULT_AVATAR_IMAGE;
}
}
else
{
$f_avatar_image = AVATAR_IMAGE_URL.DEFAULT_AVATAR_IMAGE;
}
}
?>
This is the avatar.html.php file form
<?php require_once(ROOT_PATH.'user/modules/accordion/avatar.php'); ?>
<div class="profileWrap">
<form name="frmAvatar" method="post" action="" enctype="multipart/form-data" class="htmlForm">
<div class="infoBanner2">
<p>REQUIREMENTS: File Size: <?php echo AVATAR_FILE_SIZE / 1024 ?> kb max. File Type: gif, jpg, png</p>
</div>
<!-- error msgs -->
<ul>
<?php echo $msg; ?>
</ul>
<p><input name="selectFile" type="image" src="<?php echo $f_avatar_image; ?>" class="img"></p>
<p><label for="fileUpload">Avatar Image:</label><input name="fileUpload" type="file" id="fileUpload" maxlength="255" ></p>
<input name="btnUploadAvatar" type="submit" value="Upload" class="gvbtn btn" onclick="return confirm('Are You READY to UPLOAD?');"/>
</form>
</div>
The avatar.php file is linked to a configuration file (web.config.php) file
// ------------------------------------------------------------
// 16. AVATAR IMAGE FILE
// ------------------------------------------------------------
define('AVATAR_FILE_SIZE', 2097152); // 50 Kb max. -> 1 kilobyte = 1024 bytes
define('AVATAR_FILE_DIRECTORY', ROOT_PATH.'user/upload/avatars/'); // upload directory
define('AVATAR_IMAGE_URL', SITE_URL.'user/upload/avatars/'); // default avatar url
define('DEFAULT_AVATAR_IMAGE', 'default-avatar.png'); // default avatar image
If you needed to ask anything i am ready to answer.
Let me thank the one who answer it.
Take a look at this lib and doc
https://github.com/Nimrod007/PHP_image_resize
As you can see in the below PHP code, I am going to get the value for a combobox from a database table. It shows all the columns of the table without any problem, but when I want to pass the value of combobox back to a table, it always passes the value 1. Why?
<?php
$leccom = mysql_query("select Lec_ID, Lec_Name from lecturer") or die(mysql_error());
while ($result = mysql_fetch_array($leccom)) {
$name = $result[Lec_Name];
$id_leccom = $result[Lec_ID];
echo "<option value='$id_leccom'> $name</option>";
}
?>
Next file:
<?php
mysql_select_db('lms', mysql_connect('localhost', 'root', '')) or die(mysql_error());
// Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
// Sanitize the POST values
$filedesc = clean($_POST['pdesc']);
$fname = clean($_POST['Pre_Name']);
$com = clean($_post[$id_Leccom]);
echo $_post['comselection'];
// $subject= clean($_POST['upname']);
// upload random name/number
$rd2 = mt_rand(1000, 9999) . "_File";
// Check that we have a file
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
// Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"))
{
// Determine the path to which we want to save this file
// $newname = dirname(__FILE__).'/upload/'.$filename;
$newname = "uploads/" . $rd2 . "-" . $filename;
// Check if the file with the same name is already exists on the server
// Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)))
{
// successful upload
// echo "It's done! The file has been saved as: ".$newname;
// echo "$filedesc,$newname,$fname,$comlec";
mysql_query("INSERT INTO `lms`.`presentation` (`Pre_Name` ,`Path` ,`PLec_ID` ,`pdatein` ,`pdesc`) values ('$fname','$newname','1',NOW(),'$filedesc')") or die("failed");
// mysql_query("INSERT INTO presentation (pdesc,path,pdatein,Pre_Name,plec_id) VALUES ('$filedesc','$newname',NOW(),'$fname','$comlec')") or die("query failed");
// mysql_query("INSERT INTO presentation ('pdesc','path','Pre_Name','PLec_ID') values ('$filedesc','$newname','$fname','$comlec')") ;
header("location: fileupload.php");
}
}
}
?>
$name = $result['Lec_Name'];
$id_leccom = $result['Lec_ID'];
and
echo "<option value='".$id_leccom."'>$name</option>";
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.
(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.