Uploaded files appear as Array in database and userid isn't saving - php

Wondering if you can help?
I am currently working on a script that allows an admin to upload a file to the server. When the file uploads it takes information from the form and stores it in the database, to later allow users who have permissions to download it.
I have managed to make the form:
Select File To Upload
<div style="width:100%; margin:5px;">
<form action="uploadclientfile.php" method="post" enctype="multipart/form-data" name="upload" style="margin:5px;">
<label> File</label><br /><br />
<input name="uploaded_file" type="file" class="input-xlarge" required/>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" /><br /><br />
<label>Select Users Who Can Download The File</label><br /><br />
<select name="users[]" multiple="multiple" style="width:300px">
<?php
$useruploadids = mysql_query("SELECT member_id, firstname, lastname FROM members");
while ($row = mysql_fetch_assoc($useruploadids)) {
$user_id = $row['userid'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
?>
<option value=""<?php echo $user_id ?>"><?php echo $firstname ?><?php echo $lastname ?></option>
<?php } ?>
<input name="Upload" type="submit" value="Upload" class="btn" />
</form>
So this will create a multiselect box with all users from the database to select more than one if required. It calls their userid first name and last name. But it doesn't display the user id. Which is fine.
The next file is the uploading file, the issue I am encountering is in the database. It isn't recording the userids selected and the filename is always coming up as array. Although it does save the file location correctly.
Any idea what is wrong?
<?php
$target = "clientfiles/";
$target = $target . basename( $_FILES['uploaded_file']['name']);
$userid=$_POST['users[]'];
$file=($_FILES['uploaded_file']);
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("database") or die(mysql_error()) ;
mysql_query("INSERT INTO `cfiles` VALUES ('$userid', '$file', '$target')") ;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
Any clues?
Thank you for reading

Given that your allowing the user to select multiple userids with the form notation [] the following $userid=$_POST['users[]']; will be an array. Given $userid is an array when you storing it as a string the value Array() will be stored instead of the actual user_id value. If you database table field user_id is of type INT then string value of Array() can't even be stored it will result in 0.
If you goal is to store multiple values, converting into multiple records you should iterate through the $user_id array and store them as follows
foreach ($userid as $id) {
mysql_query("INSERT INTO `cfiles` VALUES ('$id', '$file', '$target')")
}

Related

PHP does not upload file on localhost

I am reading "Head first PHP book" and stumbled at chapter 5 where file upload is implmented. I did it on XAMPP on windows 7. The path to the file is the following:
htdocs-->chapter5-->form.php
Here is my simplified version of the original code.
<html>
<head>
<title>Guitar Wars - Add Your High Score</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<head>
<body>
<?php
if (isset($_POST['submit']))
{
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot=$_FILES['screenshot']['name'];
if (!empty($name) && !empty($score) && !empty($screenshot))
{
// Connect to the database
$dbc = mysqli_connect('localhost', 'root', '') or die("could not connect to the database");
mysqli_select_db($dbc, "store") or die("could not choose the database");
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
// Write the data to the database
$query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or mysqli_errno();//die ("could not create record");
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
else
{
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
<hr />
<h2>Guitar Wars - Add Your High Score</h2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" />
<br />
<label for="screenshot">Screenshot:</label> <input type="file" id="screenshot" name="screenshot"> <hr/>
<input type="submit" value="Add" name="submit" />
</form>
</body>
The whole idea is the following. User enters his name and score and selects file for upload via self-submitting html form:
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" />
<br />
<label for="screenshot">Screenshot:</label> <input type="file" id="screenshot" name="screenshot"> <hr/>
<input type="submit" value="Add" name="submit" />
</form>
then the data is processed by php script in the same file:
<?php
if (isset($_POST['submit']))
{
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot=$_FILES['screenshot']['name'];
if (!empty($name) && !empty($score) && !empty($screenshot))
{
// Connect to the database
$dbc = mysqli_connect('localhost', 'root', '') or die("could not connect to the database");
mysqli_select_db($dbc, "store") or die("could not choose the database");
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
// Write the data to the database
$query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or mysqli_errno();//die ("could not create record");
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
else
{
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
When i try to submit the form for processig the message is
problem uploading
which suggests that move_uploaded file failed. What i did are the following:
Chagged permission of the entire htdocs folder - did not work.
Created image folder within the chapter5 directory and changed its permission it did not work. I.e. created directory image as
htdocs-->chapter5-->image
and changed permissions of the directory. then I called move_uploaded_file as
move_uploaded_file($_FILES['screenshot']['tmp_name'],
'/image/.$screenshot') or die("problem uploading");
this approach did not work
Created image directory in the htdocs directory and tried the following call
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
every time i have
probem uploading
text written on the page after form submission. I looked at file_upload record in the php.ini file everyhting seem fine:
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir="C:\xampp1\tmp"
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=2
I also changed the permmision of 'C:\xampp1\tmp'
Nothing worked. Can anybody suggest what am i doing wrong?
First things first, turn on error reporting so you can see the actual error/warning that is happening - How do I get PHP errors to display?
I ran your code and it works if the destination directory actually exists. One approach to ensuring that it exists is to create the directory on the fly.
Not sure if this is the right location for you, but using ./image/ will create the image in the directory where your script is executing. You can play around with $destinationDirectory until you get your desired location and it should continue to work.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
...
if (!empty($name) && !empty($score) && !empty($screenshot)) {
$destinationDirectory = './image/';
// Check if the destination is a directory. If not, create it.
if (!is_dir($destinationDirectory) && !mkdir($destinationDirectory)) {
die("Error creating folder $destinationDirectory");
}
$finalPath = $destinationDirectory . $screenshot;
if (!move_uploaded_file($_FILES['screenshot']['tmp_name'], $finalPath)) {
die("problem uploading");
}
...
'/image/.$screenshot' likely should be '/image/'.$screenshot
#waterloomatt, yes, this is just typo
You should edit your question with the real code then otherwise, it will throw people off.
And final note - $query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
This code is fully susceptiable to SQL injection because you're passing user supplied data directly to your database. Look into prepared statements - https://phpdelusions.net/pdo#prepared
The solution was pretty obvious. I created simple form.html file and separate form.php form handler. When 2 are separate then everything works fine. When the form is self-submitting it gave me error messages. Looks like this is related to form submission.

Image not uploading to database

I have created a php script with a form that it should insert some data into database, it actually add the text and the ID but it does not add the file.
the database looks like this:
Database name: highmob_comenzi
table name: players
in table we got 3 rows:
ID (auto_increment)
name (the name that we insert from the form)
schite (where the files should be uploaded) Type: blob Colation: none , all none
this is the script what I have tried so far
<?php
include('connect-db.php');
?>
<?php
function renderForm($name, $schita, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="hidden" name="name" value="<?php echo $name; ?>"/>
<input type="file" id="schita" name="schita" >
<button type="submit" name="submit">Add Data</button>
</form>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$schita = mysql_real_escape_string(htmlspecialchars($_POST['schita']));
if ($name == '')
{
$error = 'Error !!';
renderForm($name, $schita, $error);
}
else
{
mysql_query("INSERT players SET name='$name', schita='$schita'")
or die(mysql_error());
header("Location: mobila.php");
}
}
else
{
renderForm('','','','','');
}
?>
This script creates a page for each ID when we insert data in the form
Like pagename.php?id=4
I want when i fill the form after he create the page when i open the page to see the uploaded file only on that page,
any idea why its not working?
Get the request file using $_FILES, also you need to confirm your mysql field (schita) is a blob type
You need to correct insert query. You are missing 'into' keyword. Change query to:
mysql_query("INSERT into players SET name='$name', schita='$schita'");
You need to convert image to base64 and then save it to Database.
// Select file type
$target_file = basename($_FILES["file"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['schita']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
// Insert record
$query = "INSERT into players(schita) values('".$image."')";
mysqli_query($con,$query);
I have managed to upload the file using this script
<?php
$dbh = new PDO("mysql:host=localhost;dbname=highmob_comenzi", "highmob", "PW");
if(isset($_POST['btns'])){
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh->prepare("UPDATE players SET data='$myfile', name='$name', mime='$type' WHERE id='$id'");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$type);
$stmt->bindParam(3,$data);
$stmt->execute();
}
?>
<!-- form -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile"/>
<button name="btns"> Incarca Schita </button>
</form>
<!-- display data -->
<?php
$stat = $dbh->prepare("select * from players");
$stat->execute();
while($row = $stat->fetch()){
echo "<a target='_blank' href='viewschita.php?id=".$row['id']."'>".$row['name']."</a>";
}
?>
The problem is i got no idea how to make a link to the file, any idea how?

Dynamic insert into with multiple values

This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";

Multiple form sign up not working

I have a sign up process which involves two forms being submitted. The problem is with the first form not being submitted. Also, I need a way to relate the two forms as information from both is inserted into the same table row, I think this can be done by taking the previous table row id.
It is supposed to work like this: First a user must search for an item in the search bar. Matches are then displayed with radio buttons next to each one and a submit button at the bottom. When submitted, the form data (which is the result of the search that they checked with the radio) goes into the database table 'users'. The 'users' table contains a row for id, username, password and radio.
The radio option is submitted into radio. This also creates an id, which is auto incremented. That is the first form. Once the radio option is picked and the data is in a table row, the user must fill out the second form which asks for an email and a password, which is submitted into the same row that the radio option is in.
When I go through this process, the email (referred to as username in table) and password appear in the table along with the id, but the radio is always blank. Not sure why the radio option is not being submitted. Also not sure if i need a way to relate the forms. I am a beginner at this so, please try to make answers understandable. Thanks in advance, heres the code:
<?php
//This code runs if the form has been submitted
if (isset($_POST['submit'])) {
//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {
die('You did not complete all of the required fields');
}
// checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
//if the name exists it gives an error
if ($check2 != 0) {
die('The email '.$_POST['username'].' is already in use.');
}
// this makes sure both passwords entered match
if ($_POST['pass'] != $_POST['pass2']) {
die('Your passwords did not match. ');
}
// here we encrypt the password and add slashes if needed
$_POST['pass'] = md5($_POST['pass']);
if (!get_magic_quotes_gpc()) {
$_POST['pass'] = addslashes($_POST['pass']);
$_POST['username'] = addslashes($_POST['username']);
}
// now we insert it into the database
$insert = "INSERT INTO users (username, password, radio)
VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['radio']."')";
$add_member = mysql_query($insert);
?>
<h2><font color="red">Registered</font></h2>
<p>Thank you, you have registered - you may now login</a>.</p>
<?php
}
else
{
?>
<font color = #000000><h1>Sign Up</h1></font>
<?php
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim ($_POST['keyword']);
// Select statement
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('That query returned no results');
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
while($result_arr = mysql_fetch_array( $result ))
{
?>
// Radio button
<input type="radio" name="radio">
<?php
echo $result_arr['cause_name'];
echo " ";
echo "<br>";
}
?>
<input type="submit" name="radio_submit" value="Select Item">
</form>
<?php
$anymatches=mysql_num_rows($result);
if ($anymatches == 0)
{
echo "We don't seem to have that cause. You may add a cause by filling out a short <a href='add.php'>form</a>.<br><br>";
}
}
?>
<!--Sign Up Form-->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="sign_up_form">
<input type="text" name="keyword" placeholder="Search" onFocus="this.select();" onMouseUp="return false;">
<input type="submit" name="search" value="Search">
<br />
<br />
<input type="email" name="username" maxlength="250" placeholder="Your email" onFocus="this.select();" onMouseUp="return false;">
<input type="password" name="pass" maxlength="50" placeholder="Password" onFocus="this.select();" onMouseUp="return false;">
<input type="password" name="pass2" maxlength="50" placeholder="Re-type Password" onFocus="this.select();" onMouseUp="return false;">
<br />
<input type="submit" name="submit" value="Sign Up">
</form>
<?php
}
?>
Modify your code like this
<input type="radio" name="radio" value="<?php echo $result_arr['cause_name']; ?>" >
and then submit it you should get the value
update the below query as well
<?php
echo $insert = "INSERT INTO users (username, password, radio) VALUES ('$_POST[username]', '$_POST[pass]', '$_REQUEST[radio]')";
$add_member = mysql_query($insert);
?>
change the below code
//This code runs if the form has been submitted
if (isset($_POST['radio_submit'])) {
/////
<?php
if (isset($_REQUEST['submit']))
{
$radio = $_REQUEST['radio'];
$insert = mysql_query("INSERT INTO users (radio) VALUE ('$radio')");
if (!$insert)
{
echo mysql_error();
}
}
?>
<form action="" method="get">
<input type="radio" name="radio" value="red">red
<input type="radio" name="radio" value="blue">blue
<input type="submit" name="submit" />
</form>

MySQL php create individual named page

I am learning to create my own database and so far I have "thanks to tutorials and stackoverflow" to create a register page.
Once registered, they enter username and password and it opens the upload page.
Its to upload house details
On the upload page they enter City: Price: Decription: Bedrooms: Bathrooms: Photo:
So far, once they input the data it displays on the index page, I have done pagination, re-sized the uploaded image, and all ok.
My next step is on the index page each entry for it to open to a new window displaying their data.
The thing is that makes it hard for me to find the code, is that I want the user to input a name for their details page when uploading the house details.
And for it not to end in .php or .html just www.mysite.com/the-desired-name
my code so far might be using bad code but it works fine, and its helping me achieve what I want till I have the experience to perfect it all.
my code is upload page
<form enctype="multipart/form-data" action="add.php" method="POST">
City: <input type="text" name="city"><br>
Price: <input type="text" name = "price"><br>
Decription: <input type="text" name ="description"><br>
Bedrooms: <input type="text" name="bed"><br>
Bathrooms: <input type="text" name="bath"><br>
Your desired link name MYSITE.COM/ <input type="text" name="link"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Add">
</form>
And then it uploads via
<?php
//This is the directory where images will be saved
$target = "upload/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$city=$_POST['city'];
$price=$_POST['price'];
$description=$_POST['description'];
$bed=$_POST['bed'];
$bath=$_POST['bath'];
$link=$_POST['link'];
$pic=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("host", "username", "password") or die(mysql_error()) ;
mysql_select_db("mydatabase") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$city', '$price', '$description', '$bed', '$bath', '$link', '$pic')") ;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
require_once 'SimpleImage.php';
$image = new SimpleImage();
$image->load($target);
$image->resize(50,50);
$image->save($target);
//Tells you if its all ok
echo "<script>window.location = 'http://www.mysite.com'</script>";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
and then it displays on the index page
<?php
// Connects to your Database
mysql_connect("host", "username", "password") or die(mysql_error()) ;
mysql_select_db("mydatabase") or die(mysql_error()) ;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 2;
$data = mysql_query("SELECT * FROM employees ORDER BY bath ASC LIMIT $start_from, 2") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<?php
//Outputs the image and other data
echo "<img src=http://www.mysite.com/upload/".$info['photo'] . " /><br />";
echo "<b>City:</b> ".$info['city'] . " ";
echo "<b>Price:</b> ".$info['price'] . " ";
echo "<b>Bed:</b> ".$info['bed'] . " ";
echo "<b>Bath:</b> ".$info['bath'] . " ";
echo "<b>Extra:</b> ".$info['description'] . " ";
echo "<b>Link:</b> <u>www.mysite.com/</u> ".$info['link'] . " <br /><br /></a>";
}?>
<?php
$data = mysql_query("SELECT COUNT(photo) FROM employees") or die(mysql_error());
$info = mysql_fetch_row($data);
$total_records = $info[0];
$total_pages = ceil($total_records / 2);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
?>
for it not to end in .php or .html just www.mysite.com/the-desired-name
Assuming you are on Apache, have a look at mod_rewrite. You can use that to turn requests like the one you stated into internal requests to /showpage.php/the-desired-name. Inside that showpage.php script, you can access the-desired-name via the $_SERVER['PATH_INFO'] variable. Or, if that does not work, via some other variable which phpinfo() will tell you.

Categories