Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I have a simple image uploading website I'm creating for a little project. It's all working just great, except for the file path column in the database.
For some reason it will sometimes include the variables i'm telling it to, and sometimes not.
$user = $_SESSION['user'];
//file properties
$fileName = $_FILES["uploadedImage"]["name"];
$fileType = $_FILES["uploadedImage"]["type"];
$fileSize = $_FILES["uploadedImage"]["size"];
$fileTempName = $_FILES["uploadedImage"]["tmp_name"];
$error = $_FILES["uploadedImage"]["error"];
$random = substr(md5(microtime()),rand(0,26),16); //create random characters to avoid name duplication.
$path = "uploads/" . $_SESSION['userName'] . $random . $fileName;
The path always contains "uploads/" but only sometimes would contain the session user name, random, and only rarely the filename, even on the same files. I'm echoing out these variables before I submit the form, and they are all correct before submitting the form and uploading to the database. All other columns are correctly filled when I submit the form.
if ( isset( $_POST['formSubmit'] )) {
//prevent SQL injections and invalid inputs
$title = trim($_POST['title']);
$title = strip_tags($title);
$title = htmlspecialchars($title);
$title = mysqli_real_escape_string($db, $title);
$description = trim($_POST['description']);
$description = strip_tags($description);
$description = htmlspecialchars($description);
$description = mysqli_real_escape_string($db, $description);
if (empty($title) || strlen($title) < 1) {
$titleError = "Title required.";
$formError = true;
}
if ($formError) {
$errorMessage = "Please fill out the upload form properly.";
} else {
$query = mysqli_query($db, "INSERT INTO IMAGE(imageID,userID,title,description,path)
VALUES('','$user','$title','$description','$path')");
Here's the form itself:
<form method="POST" action="<?php $_SERVER['PHP_SELF'] ?>">
<div class="row">
<div class="col-sm-12">
<span class="errorText"><?php echo $errorMessage; ?></span>
<br><br>
</div>
</div>
<div class="row">
<div class='col-sm-1'><!--spacer--></div>
<div class="col-sm-2">
<label for="title">Title:</label>
</div>
<div class="col-sm-6">
<input type="text" id="title" name="title" placeholder="Enter your image title here..." >
</div>
<div class="col-sm-2"><span class="errorText"><?php echo $titleError; ?></span></div>
<div class='col-sm-1'><!--spacer--></div>
</div>
<br>
<div class="row">
<div class='col-sm-1'><!--spacer--></div>
<div class="col-sm-2">
<label for="description">Description:</label>
</div>
<div class="col-sm-6">
<input type="text" id="description" name="description" placeholder="Describe your image here...">
</div>
<div class="col-sm-2"><span class="errorText"><?php echo $descriptionError; ?></span></div>
<div class='col-sm-1'><!--spacer--></div>
</div>
<br>
<br>
<input type="submit" value="Submit" name = "formSubmit" id="formSubmit" class="btn">
<br>
<br>
</form>
The form is missing enctype="multipart/form-data" attribute.
<form method="POST" enctype="multipart/form-data">
Also, even if this is unrelated to the question, I strongly recommend you to use MySQLi prepared statement. It help you avoid SQL injection without the need to manually escaping parameters.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I try to write HTML to file, everything is working fine but im not able to insert string based on user input into it - can you please tell me what am i doing wrong here ?
<?php
if(isset($_POST['submit'])) {
$file = 'content.html';
$title = $_POST ['title'];
$content = '<li class="level-2"> <a class="level-2a" href="#">';
$content .= echo $title;
$content .= '
Lorem</a>
<div class="contentlevel2">
<span class="contentlilevel-2">
<!--ONEPAGECMS-START-';
$content .= echo $title;
$content .='
-->
Lorem Ipsum Doran....
<!--ONEPAGECMS-END-->
</span>
</div>
</li>';
file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
}
?>
<div class="container">
<div class="col-sm-6">
<h1 class="text-center">Create new project</h1>
<form action="project.php" method="post">
<div class="form-group">
<label for="title">Project title</label>
<input type="text" name="title" class="form-control">
</div>
<input class="btn btn-primary" type="submit" name="submit" value="Create project">
</form>
</div>
$content .= echo $title;
should just be
$content .= $title;
your creating a string, echo outputs to 'screen'
also: $title = $_POST ['title']; no space between T and [ (it will work it's just a little odd)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I created a HTML form which should submit the inputted text into a .txt file with PHP, but it only creates a blank line and I don't know what the issue is.
Help is greatly appreciated!
<form class="form-inline validate" name="form1" method="post" action="signup.php" target="_blank" novalidate>
<div class="row no-gutter">
<div class="col-sm-9">
<input type="email" value="" name="mail" class="form-control" placeholder="Subscribe to our newsletter" required>
</div>
<div class="col-sm-3">
<input type="submit" value="SUBSCRIBE" name="Submit">
</div>
</div>
</form>
<?php
$username = $_POST['user'];
//the data
$data = "$email\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
//close the file
fclose($fh);
print "User Submitted";
?>
If you want to get mail change your php code to
<?php
if(isset($_POST['Submit'])){
$email = $_POST['mail'];
//the data
$data = "$email\n";
//open the file and choose the mode
$fh = fopen("users.txt", "a+");
fwrite($fh, $data);
//close the file
fclose($fh);
print "User Submitted";
}
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My website has a form that fires every time the website is accessed. It's still in testing phases so I get over 100 BLANK emails a day just from refreshing the page (and yes, all of the inputs are required). The tricky part is that I have a jquery script included. The script fires when you hit the submit button: it then refreshes the page and scrolls down (using a hashtag) to below my form with a message that basically says "thanks for emailing me!"
My code is posted below, but what I need to know is why I keep getting these blank emails even when the input fields are required! I am still very very new to php and jquery.
<?php
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
$sent = mail($to, $subject, $message) ;
if($sent) {
echo "";
}else{
echo "";
}
?>
<form data-abide name="input" action="index.php#hashtag" method="Post" id="theForm">
<div class="row">
<div class="small-10">
<div class="row">
<div class="small-12 columns name-field">
<input type="text" name="name" required id="right-label" placeholder="Name">
<small class="error">Name is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns email-field">
<input type="email" name="email" required id="right-label" placeholder="E-mail Address">
<small class="error">An email address is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="text" name="subject" required id="right-label" placeholder="Subject">
<small class="error">A subject is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<textarea name="message" placeholder="Your Message Here" rows="4" required></textarea>
<small class="error">A message is required.</small> </div>
</div>
</div>
</div>
<br/>
<button type="submit" name="submit" value="submit">Submit</button>
<button type="reset">Reset</button>
</form>
<br/>
<div class="success_message">
<h3>Thank you for your message!</h3>
<p>Your email has been sent successfully and I appreciate you getting in touch with me. I will be sending a reply soon.</p>
</div>
<script>
$(document).ready(function() {
if(window.location.hash == '#hashtag') {
$('.success_message').show();
$("html, body").animate({ scrollTop: $('#theForm').offset().top }, 1000);
}
});</script>
You never bothered fencing off your code to check if a form submission was actually performed, so the code will fire EVERY time the page is loaded. You'd want something at least like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... handle form ...
}
They're required on the browser side, but you have no server-side validation. Older browsers that don't respect HTML5's required attribute, bots, etc. will happily submit all day long.
At its simplest, just check that there's data in each field:
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
if($subject && $name && $email && $text) {
$sent = mail($to, $subject, $message) ;
...
You'd want to do more validation (like making sure $email is a valid format) but this'll at least prevent blank ones. Of note: your form is vulnerable to header injection. Using a proper library like SwiftMailer will make coding email easier as well as protecting you from malicious spambots somewhat.
As Marc B notes, by including the mailing code on the same page as the form, you're firing it whenever someone accesses that page. Typically, your POST handling should be in a different file/route.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've been here many times. I cannot get info to post to database. Can someone explain to me what im doing wrong so I can resolve the issue?
I've ran the code on a local host with E_All and E_strict and the only thing that comes up is undefined variables. Not the ones that are supposed to be posting but the username/pass/db name ones.
First is the Form I am using and the second is the php.
<form method="post" action="hg.php">
<div id="box">
<font size="1px">
Winner must be 18 years or older and have a valid email address. Drawings will be held 12/31/2013. If for any reason either winners do not claim prize within 30 days, that winner will be null and void and we will draw again on 01/31/14 for that winners prize choices. If no winner claims their prize within 30 days from 01/31/14, all drawings and winners will be
forfeit except for the already claimed prizes if any.
</font></div>
<div class="clear"> </div>
<div id="box">
<label for="textfield" style="margin-top:15px;">First Name</label>
<input id="textfield" type="text" name="first" />
</div>
<div id="box">
<label for="textfield" style="margin-top:15px;">Last Name</label>
<input id="textfield" type="text" name="last" />
</div>
<div class="clear"> </div>
<div id="box">
<label for="textfield">Phone</label>
<input id="textfield" type="text" size="13" maxlength="13" name="contact" />
</div>
<div id="box">
<label for="textfield" style="margin-left:15px;">Email</label>
<input id="textfield" type="text" name="email" style="margin-left:15px;"/>
</div>
<div class="clear"> </div>
<div id="box">
<label for="textfield">Date of Birth</label>
<input id="textfield" type="text" name="dob" />
</div>
<div class="clear"> </div>
<div id="box"><input type="submit" value="Register" id="submit"></div>
</form>
the php
<!DOCTYPE html>
<?php
$first = $_POST['first'];
$last= $_POST['last'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$host = 'localhost';
$db_name= 'rebeler_email';
$db_username = 'rebeler_email';
$db_password = 'callaway87';
if(isset($_POST['submit'])) {
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name, $db_username, $db_password);
$statement = $pdo->prepare('
INSERT INTO `email`(
`email`,
`first`,
`last`,
`contact`,
`dob`
) VALUES (
:email,
:first,
:last,
:contact,
:dob
)
');
$result->execute('array(
`email`=>$_POST[`email`],
`first`=>$_POST[`first`],
`last`=>$_POST[`last`],
`contact`=>$_POST[`contact`],
`dob`=>$_POST[`dob`]
)'); $email_id = $pdo->lastInsertId();
if (!result || !$customer_id) {
var_dump($pdo->errorInfo());
die('something went wrong'); // do something better to handle errors!
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<style type="text/css">
#hgtitle{
height: 50px;
width: 300px;
}
</style>
</head>
<body>
<img src="images/hgtitle.jpg" id="hgtitle">
<div id="box">
Thank you for registering.
</div>
</body>
</html>
Note the highlighted variables:
$statement = $pdo->prepare(' etc... ');
^^^^^^^^^^^
v.s.
$result->execute(array( etc... ));
^^^^^^^
If you had proper error handling in your code, including having error_reporting and display_errors turned on, you'd have seen the "calling a method of a non-object" error that the second line would produce.
These settings should NEVER be off on your development server, because they only serve to hide errors you should be seeing/fixing right away.
I'm a bit of a noob myself, but i'm not sure why you are using the POST globals on the variables for your database.
I'd just set them like this:
$host = localhost;
$db_name= rebeler_email;
$db_username = rebeler_email;
$db_password = callaway87;
Because you're not getting them from the form
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am currently creating a system where a user can upload both information a corresponding picture to a db. However, when I call the move_upload_file() function, it is not liking my syntax when specifying the new destination.
The line of code I am referring to looks like this:
if(move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']")){
And the error I'm getting is
Parse error: syntax error, unexpected '")){'
(T_CONSTANT_ENCAPSED_STRING), expecting '}' in
/Applications/XAMPP/xamppfiles/htdocs/serverside/phptut/addbyform.php
on line 27
I am also using Sublime Text 2 and ['upload'] highlights in bright pink.
For further context this is my entire script thus far:
<?php
printForm();
//when "submit" tie together values and variables
if($_POST['submit']=="Submit"){
$email = cleanData($_POST['email']);
$first = cleanData($_POST['first']);
$last = cleanData($_POST['last']);
$status = cleanData($_POST['status']);
//$image = cleanData($_POST['image']);
//echo "Data cleaned";
addData($email, $first, $last, $status);
}
else{
//printForm();
}
function checkUpload(){
//check for uploaded files
if(isset($_FILES['upload'])){ //upload refers to form element "upload"
$allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/GIF');
if(in_array($_FILES['upload']['type'], $allowed)){//if upload if in the allowed file types
echo "uploading files...";
//move the file over
if(move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']")){
//moveuf method moves to tmp folder then moves to final location
echo "<p>The file has been uploaded 'dude'</p>";
$image="{$_FILES['upload']['name']}";
print "$image";
}//end of moving DAT IMG :3
else{
echo '<p>Please upload a JPEG, GIF or PNG image.<p>';
if($FILES['upload']['error'] > 0){
}
}
}
}
}
//cleans information
function cleanData($data){
if(!$status){ //everything except for status take out spaces
$data = trim($data);
}
$data = stripslashes($data);//no slashes
$data = htmlspecialchars($data);//no special characters
$data = strip_tags($data);//no html tags
return $data;
}
//inserts data into db
function addData($email, $first, $last, $status){
//echo "Ready to add data";
include("dbinfo.php");//access db
$image = checkUpload();
$sql = "INSERT INTO contacts VALUES(null, '$email', '$first', '$last', '$status', '$image')";
//null because of ID aka primary key automatically incremented:3
$result = mysql_query($sql) or die(mysql_error());
//takes sql arugment for query OR if it can't you get a BUMMER DUDE
echo <<<HERE
<b>The following has been added:</b>
<ul>
<li>E-mail: $email</li>
<li>First: $first</li>
<li>Last: $last</li>
<li>Status: $status</li>
<li>Image File:<br/> <img src="images/$image" /></li>
</ul>
HERE;
}
function printForm(){
$pageTitle ="Add a Contact";
include("header.php");
echo <<<EOD
<b>Add a Contact</b>
<form method = "POST" enctype="multipart/form-data">
<div>
<label for="email">Email*:</label>
<input type="text" name="email" id="email" required="required">
</div>
<div>
<label for="first">First Name*:</label>
<input type="text" name="first" id="first" required="required">
</div>
<div>
<label for="last">Last Name*:</label>
<input type="text" name="last" id="last" required="required">
</div>
<div>
<label for="status">Status*:</label>
<input type="text" name="status" id="status" required="required">
</div>
<div>
<label for="image">Image*:</label>
<input type="file" name="upload" size="30" id="upload" required="required"><br/>
<small>Must be less than 512kb. Only JPG, GIF, and PNG files</small>
</div>
<div id="mySubmit">
<input type="submit" name="submit" value="Submit">
</div>
</form>
EOD;
}
include("footer.php");
?>
Would anyone be able to let me know what I am doing wrong?
Thanks.
You missed one bracket !
if(move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']}")){
The one after ['name'] ...