I made a dynamically changing HTML form where I can change the type of input of the form between a file upload or a drop down box that is populated from a remote database. The function that calls which input type to be displayed is in AJAX. When I submit the form using the drop down box, the form submits without any problems and performs the update to the database that I programmed it to do. However, when I try to submit the form while trying to upload the file, my error checking script (which are simple if... statements) tells me that it BOTH doesn't detect any file being uploaded and the file already exists on the database. However, when the "already exists on database" error appears, it doesn't return the name of the file that I'm trying to upload like I programmed it to do, so I suspect that my file isn't being submitted properly.
Can someone tell me what I did wrong?
Here's the script I have so far:
File 1: test.php
<html>
<body>
<head>
<script>
function getInput(value)
{
var xmlhttp;
if (value=="")
{
document.getElementById("display").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("display").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","grabtest.php?q="+value,true);
xmlhttp.send();
}
</script>
<?php
// connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
// if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
</head>
<form enctype="multipart/form-data" action="test2.php" method="POST">
<select id='SelectInput' onchange='getInput(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New File</option>
<option value='E'>Existing File</option>
</select>
<div id="display"></div><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($_POST)){
if ($_FILES["file"]["error"] == 0){
$target = 'PathName/TargetFolder/';
$target = $target . basename($FILES['file']['name']);
if (file_exists('PathName/TargetFolder/' . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists on server. ";
}
else{
$upload = $_FILES["file"]["name"];
$select = mysqli_query($con, "Select Files from DB_Table where Files = '$upload'");
if (mysqli_num_rows($select) > 0){
echo $_FILES["file"]["name"] . " already exists in database. ";
}
else{
//script for moving the uploaded file to the proper storage location on the server and adding it to the database
move_uploaded_file($_FILES["file"]["tmp_name"], $target . $_FILES["file"]["name"]);
echo "Stored in: " . $target . $_FILES["file"]["name"] . "<br>";
$insert="INSERT INTO DB_Table (Files) VALUES ('$upload')";
if (!mysqli_query($con,$insert)){
die('Error: ' . mysqli_error($con));
}
echo "Your data has been added to the database";
}
}
if ($_POST['recipe']=="" and !file_exists($_FILES['file']['tmp_name']) and !is_uploaded_file($_FILES['file']['tmp_name'])){
exit("Please select or add the file.");
}
}
mysqli_close($con);
?>
File 2: grabtest.php
<?php
//connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$q=$_GET["q"];
if ($q==""){
echo "";
}
elseif ($q=="N"){
echo "Select recipe to upload: <input type='file' name='newfile'>";
}
elseif ($q=="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from DB_Table");
echo 'Files: <select name = "Files">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Files"] . '</option>';
}
echo '</select><br>';
echo '</form>';
}
//after script is executed, close connection to database
//this improves security by ensuring the connection to the database does not remain open when there is no activity being done to change the data
mysqli_close($con);
?>
Related
I have asked this question before I made changes to my code and my image upload is not working at all I have checked username password, and Root they are all correct. my code will not show any errors I dont know what to do anymore can someone please help me? I have changed my connection for security reasons
<?php
$con = mysqli_connect("localhost", "torcdesi_jone45", "password", "torcdesi_amazing");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_image = 'INSERT INTO shirt_table (images3)
values( "' . $_FILES['file3']['name'] . '")';
?>
<?php
include("configur.php");
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file3"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file3"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("shirtimgs/" . $_FILES["file3"]["name"])) {
} else {
//move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file3"]["tmp_name"],"shirtimgs/" . $_FILES["file3"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into shirt_table";
if(mysqli_query($link, $query_image)) {
echo "Stored in: " . "shirtimgs/" . $_FILES["file3"]["name"];
} else {
echo'';
}
}
}
}
}
?>
As I stated in comments, your form is missing a proper enctype to handle files.
This I know, since I saw your other question that did not contain it in the form.
<form enctype="multipart/form-data" action="__URL__" method="POST">
As per the manual:
http://php.net/manual/en/features.file-upload.post-method.php
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I get a warning from my php file on the server not sure what is wrong. I am making an ajax call from my javascript function to the server and it just does not receive any response in xmlhttp.readyState == 4 && xmlhttp.status == 200.
I tried to make the same call to the php file/mysql database located on my local computer it works but it would not work for a remote host. Also, i have a similar php file on the server with just the select clause different and it works there not sure what is wrong here ?
.
Warning: Cannot modify header information - headers already sent by
(output started at
/home2/marshell/public_html/cfv/getuserpostbybusnumber.php:2) in
/home2/marshell/public_html/cfv/getuserpostbybusnumber.php on line 4
.
<?php
ob_start();
header("Access-Control-Allow-Origin: *");
$q = intval($_GET['q']);
$con=mysqli_connect("localhost","ma","Ad","mars","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cfv_viewbusupdate WHERE BusNumber = ".$q." ORDER BY DatePosted DESC");
while($row = mysqli_fetch_array($result))
{
echo "<P>";
echo "<B><font color=\"3300CC\">#" . $row['DatePosted'] . "</font></B> --";
echo "" . $row['username'] . " posted </br>";
echo "<B>Bus Number . </B>";
echo "<font color=\"CC0033\">" . $row['BusNumber'] . "</font></br><B> Going towards </B>";
echo "<font color=\"CC0033\">" . $row['Direction'] . "</font></br> <B>Stop Name: </B>";
echo "<font color=\"CC0033\">" . $row['StopNames'] ."</font></br><B> Time </B><font color=\"CC0033\">".$row['time']." </font></br><B> Status </B>";
echo "<font color=\"CC0033\">" . $row['Status'] . "</font> ";
echo "</br> <B> Comment's </B>: <font color=\"CC0033\">" . $row['comments'] . "</font>";
echo "</P>";
echo "<hr> ";
}
mysqli_close($con);
?>
.
function updateUserPost(str) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState < 4) {
showModal();
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// $('#select-choice-direction-foruserpost').html(xmlhttp.responseText).selectmenu( "refresh");
hideModal();
document.getElementById("result").innerHTML = xmlhttp.responseText;
//alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "http://www.xyz.uni.me/cfv/getuserpostbybusnumber.php?q="+str, true);
xmlhttp.send();
}
This issue happens when there is white space, Most of the time its before the <?php or <? tag, some time its in one of the include files, mostly at the end of file. make sure you dont have those spaces. Error message shown will point you to that location.
I think it has to do some thing with encoding. I have experienced this issue, while development environment is Windows based most of the time WAMP (Works fine), where as production environment is linux based (Issue occurs). People usually suggest using file encoding as "UTF-8 without BOM" Notepad++ have this option. Some time encoding is changed by FTP client, also check that settings.
I have noticed that WAMP instance has following configuration in php.ini file which ignores the header already send error by buffering the output.
output_buffering = On
if you change it to off on your local environment you might see the header already sent error.
output_buffering = Off
I've changed the code with the selection boxes to the below:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.frm.modelSelection.innerHTML=xmlhttp.responseText;
}
}
var makevalue=document.frm.makeSelection.value;
xmlhttp.open("GET","http://www.autodeal.co.za/newsite/model-selection?ajaxmake="+makevalue,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
?>
<form action="index.php?option=com_content&view=article&id=99" method="post" name="frm">
<select name="makeSelection" onchange="loadXMLDoc()">
<?php
//Loads the Makes from the database into a dropdown
$resultMake = odbc_exec($conn, "SELECT DISTINCT Make FROM Vehicle ORDER BY Make") or die (odbc_errormsg());
while ($rowMake = odbc_fetch_array($resultMake)) {
echo "<option value='$rowMake[Make]'>$rowMake[Make]</option>";
}
?>
</select><br />
<select name="modelSelection">
</select><br />
<select name="yearSelection">
<option>2004</option>
<option>2005</option>
<option>2006</option>
<option>2007</option>
<option>2008</option>
<option>2009</option>
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
</select><br />
<select name="priceSelection">
<option>< 5000</option>
<option>5000 - 20 000</option>
<option>20 000 - 50 000</option>
<option>50 000 - 100 000</option>
<option>100 000 - 200 000</option>
<option>200 000 - 300 000</option>
<option>300 000 - 400 000</option>
<option>400 000 - 500 000</option>
<option>50 000 - 1 000 000</option>
<option>> 1 000 000</option>
</select>
<input type="submit" name="submit" value="Go">
</form>
</body>
</html>
Hi,
I've updated the code to reflect the answers below, but now, when you make the first selection, the Model selection box remains empty.
modelSelection.php
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
//loads the models based on the makes selection into a dependant dropdown
if (isset($_REQUEST['ajaxmake'])) {
$resultModel = odbc_exec($conn, "SELECT Model FROM Vehicle WHERE Make = '".$_REQUEST['ajaxmake']."'") or die (odbc_errormsg());
while ($rowModel = odbc_fetch_array($resultModel)) {
echo "<option value='$rowModel[Model]'>$rowModel[Model]</option>";
die(); //I'm not sure where to put this because I assume this is the reason why this selection must be first
}
}
?>
As far as I can see, the problem is that you are loading the whole request response text inside a select button. I've looked at your request response and it is responding the whole page with the models loaded, so basically it is getting all options and loading them on the Model select box, because you are inserting the whole page on the model select box.
You have multiple options here:
You can create a page that only loads the Model options, so have a file which has only this part:
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
//loads the models based on the makes selection into a dependant dropdown
if (isset($_REQUEST['ajaxmake'])) {
$resultModel = odbc_exec($conn, "SELECT Model FROM Vehicle WHERE Make = '".$_REQUEST['ajaxmake']."'") or die (odbc_errormsg());
while ($rowModel = odbc_fetch_array($resultModel)) {
echo "<option value='$rowModel[Model]'>$rowModel[Model]</option>";
}
}
And change the page you are calling through ajax to point to that page:
xmlhttp.open("GET","newpage.php?ajaxmake="+ makevalue,true);
The other option, and the one I suggest you is to look into some javascript library, such as jQuery which has functions to easen your work.
If you include jQUery library, adding the select name as id="makeSelection" and id="modelSelection" you could write a javascript function like this:
jQuery(document).ready(function(){
jQuery("#makeSelection").change(function(){
jQuery("#modelSelection").load("?ajaxmake="+ makevalue + #modelSelection option");
});
});
BTW! Be aware that you may have a huge security problem in your sql queries, since people can attack you through the ajaxmake variable, and truncate/drop your tables or anything. I suggest you to sanitize and validate the data coming from your requests, specially if you post some sensitive data like your database tables on the internet!!! If you want to know more about SQL Injection (how this security issue is called): How can I prevent SQL injection in PHP?
I am not sure why you have html included in your ajax processing file. Usually you keep a .php file consisting only of php code and then you can be sure no html or script code are being included (which is currently happening in your page now).
For one, try to change your model dropdown code to:
<?php
//loads the models based on the makes selection into a dependant dropdown
if (isset($_REQUEST['ajaxmake'])) {
echo "<select name='modelSelection'>"; //select tag placed here
$resultModel = odbc_exec($conn, "SELECT Model FROM Vehicle WHERE Make = '".$_REQUEST['ajaxmake']."'") or die (odbc_errormsg());
while ($rowModel = odbc_fetch_array($resultModel)) {
echo "<option value='$rowModel[Model]'>$rowModel[Model]</option>";
}
echo "</select><br>";
die(); //<-- the die placed here will not execute the rest of
//the code and also all the options will be populated
}
?>
I'm developing a web page that should read and change the contents of specific files on the server.
These files will only have two values: 1 or 0. Reading/changing the contents will be made via combo boxes with OnChange. Basically the idea is to control appliances via General Purpose Input/Outputs (GPIO's). The electronics part is all done, I just need to finish the web programing part and got stuck on it.
I'm not experienced in programing at all, but with some snippets found here and there, I was able to implement part of it with AJAX/PHP.
So far, I'm able to read the values, but unable to change it even though I'm building the correct command with "escapeshellarg".
Also, I was expecting to have two interactive areas in the page but only the original is working.
Could anyone point me into the right direction? Any help/suggestion/comment will be welcomed.
pqp6.php
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinfo.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$file1="/var/www/file1";
$file2="/var/www/file2";
$output = shell_exec('cat '.escapeshellarg($file1));
if($output == 0)
{
echo "zero ; ";
$file1status = "off";
$file1oposite = "on";
$file1exec= "file1on";
}
else
{
echo "one ; ";
$file1status= "on";
$file1oposite= "off";
$file1exec= "file1off";
}
echo "output:$output ; file1status:$file1status ; file1oposite:$file1oposite ; file1exec:$file1exec <br><br>";
$output = shell_exec('cat '.escapeshellarg($file2));
if($output == 0)
{
echo "zero ; ";
$file2status = "off";
$file2oposite = "on";
$file2exec= "file2on";
}
else
{
echo "one ; ";
$file2status= "on";
$file2oposite= "off";
$file2exec= "file2off";
}
echo "output:$output ; file2status:$file2status ; file2oposite:$file2oposite ; file2exec:$file2exec <br><br>";
?>
<br>
<br>
FILE 1:
<form>
<select name="file1" onchange="showUser(this.value)">
<option value="1,<?=$file1status?>"><?=$file1status?></option>
<option value="1,<?=$file1oposite?>"><?=$file1oposite?></option>
</select>
</form>
<br>
<div id="txtHint"><b>File 1 information will be listed here.</b> </div>
<br>
<br>
FILE 2:
<form>
<select name="file2" onchange="showUser(this.value)">
<option value="2,<?=$file2status?>"><?=$file2status?></option>
<option value="2,<?=$file2oposite?>"><?=$file2oposite?></option>
</select>
</form>
<br>
<div id="txtHint"><b>File 2 information will be listed here.</b></div>
</body>
</html>
getinfo.php:
<?php
$q=$_GET["q"];
$q_stripped = explode(",", $q);
$file_n = $q_stripped[0];
$file_command = $q_stripped[1];
$path="/var/www/file";
if($file_command == "on")
{
$file_command = "1 > ";
}
else
{
$file_command = "0 > ";
}
$command= "/bin/echo $file_command$path$file_n";
$escaped_command = escapeshellarg($command);
echo "COMMAND: $escaped_command";
shell_exec($escaped_command);
echo "file_n=$file_n ; file_command=$file_command ; ";
?><?php
By applying the escapeshellcmd your > 0 or > 1 is turned into \\> 0 and \\> 1 I guess that is why it doesnt work. You are not using escapeshellcmd, you are using escapeshellarg.
You might want to check the file permissions also.
However, instead of using system calls, have you ever thought about using
file_exists, file_get_contents or file_put_contents .
With those functions and writable dirs/files, you can achieve exactly what you are doing, without making system calls. Plus, it would be more portable.
Slowly but surely, I'm going to get AJAX. I've got a form that uploads a text field and a file to a database. I had the query working in PHP earlier, but not the AJAX. Now the AJAX is working but not the PHP. And I know that some will find it objectionable to load an image to a BLOB, but the query itself works, so I'd like to focus on the problems I'm having getting my javascript to talk to my PHP. I've researched the issue like crazy and tried a lot of things, but the thing I've come away with is that uploading files is complex.
Questions
1. Correct me if I'm wrong, but if javascript and jquery implement a "POST" call, the passed parameters shouldn't show up in the page's URL? Because they are.
2. Why is my PHP file not parsing out the sent data and sending it on to the database? I can see in the URL and in Firebug (although I'm slowly learning Firebug as well) that data is being passed. I ran a test php file and I am connecting with the database with that file.
Thanks!
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script src="jquery.validate.js"></script>
<script src="jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#addForm').validate();
function addRecord() {
$("#aTable").hide('slow', function () { //this is not working
alert('Working on it.');
});
$("#tableText").hide('slow', function() {//this is not working
alert('Working on it.');
});
var output = document.getElementById("message");
var nAname = document.getElementById("aname");
var nAInfo = new FormData(document.forms.namedItem("addForm"));
nAInfo.append('aname', nAname);
$.ajax({
type: "POST",
url: "addPhoto.php",
data: nAInfo
});
});
</script>
</head>
<body>
<form id="addForm" name="addForm" onsubmit="addRecord()" enctype="multipart/form-data">
<label>Name: </label>
<input type="text" id="aname" name="aname" class=required/>
<br>
<br>
<label>Photo: </label>
<input type="file" id="aimage" name="aimage" class="required">
<br>
<br>
<input type="submit" value="ADD" />
<br>
</form>
<div id="message" name="message"></div>
<br>
<br>
<div id="image_display"></div>
</body>
</html>
PHP
<?php
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');
error_reporting(E_ALL);
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $_SERVER['REQUEST_METHOD'];
$aname = $_POST['aname'];
$errorinfo = $_FILES["aimage"]["error"];
$filename = $_FILES["aimage"]["name"];
$tmpfile = $_FILES["aimage"]["tmp_name"];
$filesize = $_FILES["aimage"]["size"];
$filetype = $_FILES["aimage"]["type"];
$fp = fopen($tmpfile, 'r');
$imgContent = fread($fp, filesize($tmpfile));
fclose($fp);
if (!($filetype == "image/jpeg" && $filesize > 0)) {
echo "Import of photo failed";
}
if ($filetype == "image/jpeg" && $filesize > 0 && $filesize < 1048576) {
if (!($stmt=$mysqli->prepare("INSERT INTO actor_info (aname, aimage_data) VALUES (?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ")" . $mysqli->error;
}
if (!$stmt->bind_param("ss", $aname, $imgContent)) {
echo "Binding parameters failed: (" . $stmt->errno .") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->close();
}
else {
echo "Image must be under 1 MB";
}
echo mysqli_error();
mysqli_close($mysqli);
?>
$("#aTable").hide('slow', function () { //this is not working
alert('Working on it.');
});
$("#tableText").hide('slow', function() {//this is not working
alert('Working on it.');
});
The above code is not working because you don't have any elements with id '#aTable' or '#tableText' in your html code.
Try print_r($_POST) to see whether all the values get to server or not.
Also using JQuery's Ajax function will make your code easier...below is a sample
$.ajax({
url : $domain + "/index/email/" + "?" + $arguments, //add your args here...
cache : false,
beforeSend : function (){
alert('sending....');
},
complete : function($response, $status){
if ($status != "error" && $status != "timeout") {
if($response.responseText == "200"){
alert('done');
} else {
alert($response.responseText);
}
}
},
error : function ($responseObj){
alert("Something went wrong while processing your request.\n\nError => "
+ $responseObj.responseText);
}
});