the interface of uploading recipeThis is my code to upload recipes(new.php), once the submit button is clicked, it will be uploaded to mysql. I have tried checking if any mysql codes were outdated by changing them to mysqli. Cause this project is a bit old. So on other pages I have changed many mysql to mysqli.
<form method="post" action="new.php" enctype="multipart/form-data" class="form3">
***I'm suspecting that the mistake is from here. As all the other parts of the code seem to be okay to me.***
if (isset($_POST['submit'])){
$title = $_POST['title'];
$date = date('Y.m.d');
$author = $_POST['author'];
$desc = $_POST['desc'];
$image_name = $_FILES ['image'] ['name'];
$image_type = $_FILES ['image']['type'];
$image_size = $_FILES ['image']['size'];
$image_tmp = $_FILES ['image']['tmp_name'];
if($title =='' or $author =='' or $desc ==''){
echo"<script>alert('Some Field/fields is/are Empty')</script>";
exit();
}
if($image_type=="image/jpeg" or $image_type=="image/png" or $image_type=="image/gif"){
if($image_size<=50000){
move_uploaded_file($image_tmp,"uploads/$image_name");
}
else{
echo"<script>alert('Image is Larger, Only 50kb size is allowed')</script>";
}
}
else{
echo"<script>alert('Image Type is Invalid')</script>";
}
$query = "insert into new_recipe(post_title,post_date,post_author,post_image,post_desc
) values('$title','$date','$author','$image_name','
$desc')";
if (mysqli_query($con,$query)){
echo "<center><h1>Recipe Has Been Submitted!</h1></center>";
}
}
**Once all the details have been typed. When I click on submit , it doesn't give me any error/s. There were some previous recipes uploaded before I face these errors, and I can see them perfectly under the view.php page.**
?>
<?php } ?>
Related
On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code
developerUpload.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
echo '<br><h3 style="color:red;">File(s) were already submitted! Please re-name file or select a different file...</h3>';
}
if(isset($_COOKIE['username'])){
if($_SERVER['REQUEST_METHOD'] =="POST"){
$price = addslashes(trim($_POST['price']));
$description = addslashes(trim($_POST['description']));
if(!empty($price) && !empty($description)){
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
echo '<br>'.$userid;
$pack_id = rand();
//Check file 1
if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){
$file1 = null;
}else{
$target1 = "devFiles/";
$target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
$file1 = addslashes(trim($_FILES['file1']['tmp_name']));
}
//Check file 2
if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){
$file2 = null;
}else{
$target2 = "devFiles/";
$target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
$file2 = addslashes(trim($_FILES['file2']['tmp_name']));
}
//Check file 3
if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){
$file3 = null;
}else{
$target3 = "devFiles/";
$target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
$file3 = addslashes(trim($_FILES['file3']['tmp_name']));
}
//Check file 4
if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){
$file4 = null;
}else{
$target4 = "devFiles/";
$target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
$file4 = addslashes(trim($_FILES['file4']['tmp_name']));
}
//Check file 5
if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){
$file5 = null;
}else{
$target5 = "devFiles/";
$target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
$file5 = addslashes(trim($_FILES['file5']['tmp_name']));
}
//Check video
if($_FILES['video']['error'] !== UPLOAD_ERR_OK){
$video = null;
$videoName = null;
}else{
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
$video = addslashes(trim($_FILES['video']['tmp_name']));
$videoName = addslashes(trim($_FILES['video']['name']));
}
if(file_exists($target_file1)
or file_exists($target_file2)
or file_exists($target_file3)
or file_exists($target_file4)
or file_exists($target_file5)
or file_exists($target_file)){
header("Location: developerUpload.php?invalid");
exit;
}
if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
&& move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
&& move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
&& move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
&& move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
&& move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
header("Location: submission_successful.php?");
die();
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
}
}
}else {
header("Location: developerLogin.php");
}
?>
submission_successful.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
header("Location: developerUpload.php?invalid");
}
if(isset($_COOKIE['username'])){
echo '<br><h1 style="color:red; text_align:center;">Thank You for Submitting!</h1>';
}else{
header("Location: developerLogin.php");
}
?>
I was searching around for days and finally found something. IF you use a HTML command it will remove any input the user put when the user goes back. Because my problem was when the user goes back after be redirected, their information was still there but if you use
<form method="post" enctype="multipart/form-data" autocomplete="off">
it removes everything so it kinda helps. The user will still be allowed to go back but at least now they can't resubmit the data.
Not sure whether you can check if a value exists twice in the database (thus preventing multiple submissions), but you could block users from submitting the form too frequently. Create a timestamp that gets saved upon first submission, and if the second resubmission's timestamp is not too far(big) from the first one, you could try sth like (you are submitting too frequently), or you could use ajax, or this https://es.m.wikipedia.org/wiki/Post/Redirect/Get
Use a session variable like this
$_SESSION["post_id"] = "";
if($_POST) {
if($_POST["post_id"] != $_SESSION["post_id"]) {
$_SESSION["post_id"] = $_POST["post_id"];
// do database submission here
}
}
This sets a session variable and if they resubmit the form it won't post the data twice.
Hi Guys i got a Problem i upload an image to Upload Folder upload is working fine but he dont submit the value into mysql database and i really dont know where the failure ist here ist the whole code.
Unique Value is id from the user and the field for the image name is company_logo.
My dashboard code:
The Form:
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
JQuery Code
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').on('change', function() {
$("#preview").html('');
$("#preview").html('<div class="spinner"></div>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
And Finally The ajaximage.php
<?php
session_start();
ob_start();
$valid_user_id = trim($_SESSION["VALID_USER_ID"]);
if(isset($_SESSION["VALID_USER_ID"]) && !empty($valid_user_id))
{
include "database_connection.php"; //Include the database connection script
//Check the logged in user information from the database
$check_user_details = mysql_query("select * from `signup_and_login_table` where `email` = '".mysql_real_escape_string($_SESSION["VALID_USER_ID"])."'");
//Get the logged in user info from the database
$get_user_details = mysql_fetch_array($check_user_details);
//Pass all the logged in user info to variables to easily display them when needed
$user_id = strip_tags($get_user_details['id']);
$firstname = strip_tags($get_user_details['firstname']);
$lastname = strip_tags($get_user_details['lastname']);
$company = strip_tags($get_user_details['company']);
$company_logo = strip_tags($get_user_details['company_logo']);
$email = strip_tags($get_user_details['email']);
$passwd = strip_tags($get_user_details['password']);
// User Id for Image Upload
$session_id = strip_tags($get_user_details['id']);
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($db,"UPDATE signup_and_login_table SET company_logo='$actual_image_name' WHERE id='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
else
{
//Send every user who tries to access this page directly without valid session to the login page.
//The login page is the door that every user needs to pass to this page
header("location: login.html");
}
?>
Use the following sql query:
INSERT INTO signup_and_login_table (company_logo, id) VALUES ('$actual_image_name', '$session_id')
You've made instead a UPDATE Query, which only updates already EXISTING rows.
Kind regards!
Try this query
mysqli_query($db,"UPDATE signup_and_login_table SET company_logo='$actual_image_name' WHERE id=".$session_id);
I try to make a form to include image upload. let say I have table participant which I would like to insert to:
INSERT INTO `participant`(`Matric`, `Name`, `IC`, `Address`, `Tel`, `Phone`,
`Email`, `Phone_Ref`, `Institute`, `Course`, `Pic_Participant`, `Exp_Work`)
VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7],
[value-8],[value-9],[value-10],[value-11],[value-12])
What I want to do is to insert data and upload an image. Its attribute which is Pic_Participant.
I search about upload using ajax Ajax Image Upload and Resize with jQuery and PHP . Then I think the flow, fill the form then upload image in same page, then after upload image the data for image send to db, but the form does not submit yet. How can I get attribute from table image to add in table participant?
Please help me. I'm new about this.
EDIT
i try this code but get an error: Undefined variable
<?php
session_start();
include 'dbconnect.php';
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "upload/";
//ERROR START HERE
$Matric = $_POST['Matric'];
$Name = $_POST['Name'];
$IC = $_POST['IC'];
$Address = $_POST['Address'];
$Tel = $_POST['Tel'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Phone_Ref = $_POST['Phone_Ref'];
$Institute = $_POST['Institute'];
$Course = $_POST['Course'];
/* $fname = $_POST['fname'];
$lname = $_POST['lname']; */
$image = $_FILES['image'];
$Exp_Work =$_POST['Exp_Work'];
//ERROR END HERE
$Matric = mysql_real_escape_string($Matric);
$Name = mysql_real_escape_string($Name);
$IC = mysql_real_escape_string($IC);
$Address = mysql_real_escape_string($Address);
$Tel = mysql_real_escape_string($Tel);
$Phone = mysql_real_escape_string($Phone);
$Email = mysql_real_escape_string($Email);
$Phone_Ref = mysql_real_escape_string($Phone_Ref);
/* $Total_sales = addslashes($_POST['Total_sales']);
$Date = addslashes($_POST['Date']); */
/* $Cer_name = mysql_real_escape_string($Cer_name); */
$Institute = mysql_real_escape_string($Institute);
$Course = mysql_real_escape_string($Course);
/* $Cat_name = addslashes($_POST['Cat_name']);
$Product_name = addslashes($_POST['Product_name']); */
/* $fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname); */
$image['name'] = mysql_real_escape_string($image['name']);
$Exp_Work = mysql_real_escape_string($Exp_Work);
$TARGET_PATH .= $image['name'];
if ( $Matric == "" ||$Name == "" ||$IC == "" ||$Address == "" ||$Tel == "" ||$Phone == "" ||$Email == "" ||$Phone_Ref == "" || $Institute == "" || $Course == ""|| $image['name'] == ""|| $Exp_Work == "" )
{
$_SESSION['error'] = "All fields are required";
echo "All fields are required";
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
echo"You must upload a jpeg, gif, or bmp";
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
echo"A file with same name exists already";
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into participant (Matric, Name, IC, Address, Tel, Phone, Email, Phone_Ref, Institute, Course, image, Exp_Work) values ('$Matric','$Name','$IC','$Address','$Tel','$Phone','$Email','$Phone_Ref','$Institute', '$Course','" . $image['name'] . "','$Exp_Work')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
echo"Imgage uploaded successfully";
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: fail.php");
exit;
}
?>
As I read your question, you want to upload the image already using the tutorial / code you found and then submit the form separately when the image already has been uploaded.
To know where you can find your image after the file upload, you have two options:
Have the image upload return the file path when the upload is complete and include that variable in your form (as a hidden input for example);
Store the image path in a session variable so that when you submit the data fields, you can access that variable to get the information of the image.
Edit: You need to check the documentation of the Form Plugin for more details, but you can return something from your upload php script. You could for example echo the file name and then you would have it available in your success function:
function afterSuccess(return_value) {
console.log(return_value); // here you have what was echoed out by php
$('#UploadForm').resetForm(); // reset form
$('#SubmitButton').removeAttr('disabled'); //enable submit button
}
If I got it correctly what you want is to insert image into (probably MYSQL) database.
You could achieve this by using base64_encode() of image binary data and insert resulting plaintext in database.
$image = 'path/to/image/image.png';
$imagefordbs = base64_encode($image);
/*now your image is ready to be stored in database*/
However, this method has downsides since base64_encode() takes up about 33% more then original memory, some time to process input binary, and there is dedicated datatype for this kind of requirements in mysql - BLOB.
This is suppose to be pretty straight forward and is driving me mad!
I'm trying to upload a file in PHP and writing the file to MySQL as a blob.
Problem is that the site throws a "Undefined index" all the time when I'm trying to use the
$_FILES['file']['tmp_name'] property.
Here is my code :
<head>
<title>Upload Worksheet</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000" />
File :
<input type="file" name"file" id="file"><input type="submit" value="Upload">
</form>
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
?>
</body>
This is what the error message looks like :
I haven't even gotten to the database side, as I can't get past this stage.
I'm a PHP noob, so any help would be greatly appreciated!
You recieve that error message because the form is not sent, yet. When you hit the upload button, the form is sent to your server and PHP populates the $_POST and $_FILES array with data. However, the arrays are empty until that point. It is therefore good practice to check whether or not your data is set, like so:
if (isset ($_POST['upload']))
{
// upload logic here
if(!isset($_FILES['file']) || ($_FILES['file']['tmp_name'] == ''))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
This assumes you have a submit button named "upload".
The Above answer is perfect because you should check the for post values in order to run any code on those values but you can also try the following
<?php
//connect to db
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("autoedi") or die(mysql_error());
//file properties
if(isset($_POST))
{
if(array_key_exists('file',$_FILES))
{
$file = $_FILES['file']['tmp_name'];
if(!isset($file))
echo "Please choose a file.";
else {
$uploadfile = addslashes(file_get_contents( $_FILES['file']['name']));
$uploadfilename = addslashes($_FILES['file']['tmp_name']);
}
}
?>
When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.