PHP does not upload file on localhost - php

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.

Related

Unable to update database row in PHP with $_POST variable

I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?

Storing multiple images in MySQL database with PHP

I am new to PHP.
I am trying to add multiple images with text to a database and I'm stuck. If I select one, it gets stored. If I select multiple, it's left as blank in the database.
I need help to resolve this. Plus, I am confused: is one table for images in db ok? I mean, is there a special datatype or way to have multiple images on the same entry in a database?
Here's my code:
<html>
<body>
<form class="container" enctype ='multipart/form-data' action="add.php" method="post">
<label><b> Name: </b></label><br><br>
<input type="text" name="name"><br><br>
<label><b> Type: </b></label><br><br>
<input type="text" name="type"><br><br>
<label><b> Detail: </b></label><br><br>
<input type="text" name="detail"><br><br>
<label><b> Area: </b></label><br><br>
<input type="text" name="area"><br><br>
Select image to upload:
<input type="file" name="filename" size='10000' multiple>
<input type="submit" value="Upload Image">
</form>
<?php
// error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password, $db_database);
if (!$db_server) die("unable to connect to mysqli:" . mysqli_error());
mysqli_select_db($db_server, "dbase1") or die("db not selected" . mysqli_error());
$name = $_POST["name"];
$type = $_POST["type"];
$detail = $_POST["detail"];
$area = $_POST["area"];
if($_FILES)
{
$namee = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $namee);
echo "uploaded image'$namee'<br><img src ='$namee'>";
}
$source= "pictures/".$namee;
$sql = "INSERT INTO adprop (name, type, text,area,filename) VALUES ('$name','$type','$detail','$area','$source')";
$db = $db_server->query($sql);
?>
</body>
<html>
Thanks in advance for your help!
For example if you want save multiple image paths in a field, you can add them to db as below:
/image_folder/image_name1.jpg,/image_folder/image_name2.jpg
And use split and for loop to print them dynamically in user interface.

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

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')")
}

Retrieve data from database and display in text fields.

Please help me. I written a code but it is not working well.
I want to retrieve data from database and display text fields.
My Code is:
<DOCTYPE html>
<html>
<head><title>Practice</title></head>
<body align="center">
<?php
$con=mysqli_connect("localhost","root","","address_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<form action="1.php" method="post">
Name <br><input type="text" name="name" value="<?php echo $_GET['n']; ?>"><br>
Address 1<br><input type="text" name="address_1" value=""><br>
Address 2<br><input type="text" name="address_2" value=""><br>
Address 3<br><input type="text" name="address_3" value=""><br><br><br>
<input type="submit" name="reset" value="Clear">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="retrieve" value="Retrieve">
</form>
<?php
if (isset($_POST['submit']))
{
$name=$_POST['name'];
$address_1=$_POST['address_1'];
$address_2=$_POST['address_2'];
$address_3=$_POST['address_3'];
if(($name=='')||($address_1=="")||($address_2=="")||($address_3==""))
{
echo "<script>alert('Please fill all fields')</script>";
exit();
}
else
{
mysqli_query($con,"INSERT INTO address_tbl (name,address_1,address_2,address_3)
VALUES ('$name','$address_1','$address_2','$address_3')");
echo "<script>alert('Your record successfull inserted into database...')</script>";
exit();
}
}
if (isset($_POST['retrieve']))
{
$result = mysqli_query($con,"SELECT * FROM address_tbl");
while($row = mysqli_fetch_array($result))
{
$name=$row['name'];echo "<br>";echo "<br>";
$add1=$row['address_1'];echo "<br>";echo "<br>";
$add2=$row['address_2'];echo "<br>";echo "<br>";
$add3=$row['address_3'];echo "<br>";echo "<br>";
echo "<script type='text/javascript'>
window.open('1.php?n=$name','_self'); </script>";
}
}
?>
</body>
</html>
Please help me. give me any hint that I can solve my problem. Thanks
try this ,
mysqli_query($con,"INSERT INTO `1address_tbl` (`name`,`address_1`,`address_2`,`address_3`)
VALUES ('$name','$address_1','$address_2','$address_3')");
it should work fine now. it needs to include ( ` ) around the table names and column name to make sql work correctly. you left them out,
you replace this with yours.
First of all you should have your php in a seperate file called index.php with just php code then create a page called index.html.php in that page use a foreach loop to output data from the database its the most common and practical way of doing what your trying to do .

my php script enters blank info into mysql db!

When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across
I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php
<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];
mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");
$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";
mysql_query($query) or die ('Error updating DB');
echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";
?>
Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.
this is the signup form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Candidate Registration</title>
</head>
<body>
<form medthod="post" action="update.php">
Real Name:<br />
<input type="text" name="realname" size="50" /><br />
Age:<br />
<input type="text" name="age" size="10" /><br />
Country:<br />
<input type="text" name="country" size="20" /><br />
In Game Name:<br />
<input type="text" name="gamename" size="30" /><br />
In Game Level:<br />
<input type="text" name="gamelevel" size="10" /><br />
In Game Item Level:<br />
<input type="text" name="itemlevel" size="10" /><br />
Class Played:<br />
<input type="text" name="class" size="30" /><br />
How long have you played wow?:<br />
<input type="text" name="played" size="10" /><br />
Please enter a brief statement of why you want to join:<br />
<input type="text" name="support" size="5000" /><br />
<br />
<input type="submit" value="Update DB" />
</form>
</body>
</html>
this is the update.php form
<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];
mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");
$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";
mysql_query($query) or die ('Error updating DB');
echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";
?>
I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)
Is your form method set to POST? - unless you have explicitly added this the variables will be within the $_GET superglobal so your variables would be like this:
$realname = $_GET['realname'];
If it is set to POST - please do a var_dump($_POST) at the top of your script and see if any variables are making it to your script.
Something else that i've seen before is caused when people are redirecting in a .htaccess from domain.com to www.domain.com and they post a script explicity to domain.com/script.php and the script then redirects to www.domain.com/script.php and this empties the POST.
EDIT
You have spelt method wrong in your form tag - if you update this then it should work as your misspelling will be causing the variables to be sent as GET vars.
You can fix your security issues in a basic way like this:
$realname = mysql_real_escape_string($_POST['realname']);
$age = mysql_real_escape_string($_POST['age']);
$country = mysql_real_escape_string($_POST['country']);
$gamename = mysql_real_escape_string($_POST['gamename']);
$gamelevel = mysql_real_escape_string($_POST['gamelevel']);
$itemlevel = mysql_real_escape_string($_POST['itemlevel']);
$class = mysql_real_escape_string($_POST['class']);
$played = mysql_real_escape_string($_POST['played']);
$support = mysql_real_escape_string($_POST['support']);
Whoa, slow down. You've not even escaped this data!
$realname = mysql_real_escape_string($_POST['realname']);
Or to escape it all:
$_POST = array_map('mysql_real_escape_string', $_POST);
Note the second solution isn't entirely reliable. Can produce some strange results. It is generally better to run these inputs through a function/class for validation and cleansing.
On your ghost issue, try this and note response after form submit (put right at top):
var_dump($_POST);
exit;
You spelled method attribute wrong in your query, that is why it isn't working.

Categories