Uploading files to a folder that is above the current folder - php

$result = mysql_query("SELECT * FROM media WHERE path = '$target'");
if($row = mysql_num_rows($result)==1)
{
echo"<br />Sorry, there is already a file with that name on the server.<br />Please press back on your browser and save the file under a different name.";
}else{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
mysql_query("INSERT INTO media (id, related_page_id, type, title, copy, path, position, assets, time) VALUES ('', '$cat','$type','$name','','$target','$position','$id','$today')");
header("Location: edit.php?category=$cat");
exit();
echo $name;
}
else {
echo $today;
echo "<br />";
echo "Sorry, there was a problem uploading your file. Please press back on your browser and try again.";
}
}
The above code used to work. Now it will not let me upload files to ../uploads/ but it works fine if i upload to uploads/.
Does anyone have any suggestions as to what i'm doing wrong? Thanks
EDIT
$target = "../uploads/";

I know it sounds silly but are the permissions for the folder set up correctly?

Related

Image upload to mysql

My site is able to upload a file but I don't understand how to get the path to the file for the database query. When someone uploads an image, the path to the image should get directly inserted into the users table in the userpic field. How can I achieve this?
<?PHP
if(isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'],'files/'.$_FILES['file']['name']);
session_start();
$username = $_SESSION['user'];
$userpic = ???? // <-- what am i supposed to call here to put the path to my image file
include ("connect.php");
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$userpic);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "no files";
}
?>
If you store files using the name provided by the client when the file is uploaded, you will potentially overwrite images (e.g. if two users upload me.png) - it would be much better to use the username to store the images, and then you don't even need the mysql table to connect users to their pics..
<?php
session_start();
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$newpath = 'files/'.$username;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
In this code we use the username from the session, and check its not blank.
We then use this to store the image in your files folder.
Note this ignores a number of security issues:
Including ../ in your username which would cause the file to be saved outside of the files directory.
This may not be an issue if you have already validated the username, another solution would be to create a hash of the username and using this instead: $newpath = 'files/'.md5($username);
Not checking for errors, or verifying the file is indeed an image.
http://php.net/manual/en/features.file-upload.errors.php
PHP image upload security check list
How are these images going to be used after this?
If the files directory is within your htdocs, the contents will be available for all - it would probably be better to store it outside of your htdocs
e.g. $newpath = '/var/myappdata/userimages/'.md5($username);
You could then create another file userimage.php which reads the file:
<?php
session_start();
$username = $_SESSION['user'];
$path = '/var/myappdata/userimages/'.md5($username);
readfile($path);
This allows you to do additional checks e.g. that the user is allowed to see the image.
There is still a huge amount that could be covered here, hopefully this gives you enough to move forward, but do please read more about file upload security before putting this into production.
Your original question
If you did want to store information about the image in your database you could do something like this:
<?php
session_start();
include ("connect.php");
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$filename = basename($_FILES['file']['name']);
$newpath = 'files/'.$filename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$filename);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
As I said though - you will run into conflicts if two users upload the same file.
You aren't going to want to store the entire URL in the database. You just need the path to where it is on the server. That is the part where you are moving the tmp file to a new location. In your case it would be the following.
$userpic = 'files/'.$_FILES['file']['name'];

upload succeeding but picture is not there

I have a php page that is supposed to store the uploaded image to my server. When I run this, I get the "Upload successful" message, but the picture has not been uploaded.
What could it be?
update: can people please leave a comment as to why they down vote my question. I'm new here and I dont know why this question got down voted. thanks
<?
if(!empty($_FILES['uploaded_file'])) {
if ($_FILES['uploaded_file']['error'] > 0 )
echo "Error: " . $_FILES['uploaded_file']['error'] . "<br />";
else{
// Add the original filename to target path.
$target_path = 'MemberPics\\user'.$userid.'.jpg' ;
$success = move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path);
if(!$success) {
echo "There was an error uploading the file, please try again!";
}else {
echo "Upload successful, please go back to your home page";
}
}
}
?>
I believe the problem you are running into is that you are saving the image in an incorrect location (An invalid one from the looks of your link syntax).
Either of these should work:
$target_path = 'MemberPics/user'.$userid.'.jpg' ;
or
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], "MemberPics/user" . $_FILES["uploaded_file"]["name"]);

How do I assign a chmod value of 0777 at the point it the file is uploaded (PHP)?

My system features a conversation area which writes to and draws from a .txt file. I am obviously able to set the permissions through my FTP client but I'm looking to apply the writable functionailty to all files that are uploaded through my system within the PHP. I'll add that security is not an issue.
<?php
$adminID = $_GET['adminID'];
$name = stripslashes(trim($_POST['name']));
$area = stripslashes(trim($_POST['area']));
mysql_query("INSERT INTO chat_rooms (id, name, area, adminID) VALUES ('', '$name', '$area', '$adminID')");
$image = ($_FILES['image_url']['name']);
$empty = '';
if ($image == $empty)
{
echo 'NO IMAGE';
}else
{
$target = "room/test/";
$target = $target .basename($_FILES['image_url']['name']);
$target2 = basename($_FILES['image_url']['name']);
$image_url = ($_FILES['image_url']['name']);
$adminarea = 'admin-index.php';
mysql_query("UPDATE chat_rooms set file='$image_url' WHERE name = '$name'");
if(move_uploaded_file($_FILES['image_url']['tmp_name'], $target))
{
echo "";
echo "Your room has been created using the file " . basename( $_FILES['image_url']['name']) ." <br /> <br /> Click here to return to the admin area";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
}
?>
I apologise for the layout and general syntax of my code
Just call chmod('thefile.txt', 0777) on the file after it has been uploaded.
http://php.net/manual/en/function.chmod.php
chmod:
chmod('/path/to/file.txt', 0777);

Upload files not working, whats wrong with this code?

This is the PHP code used for the upload:
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
} else { echo "Error"; }
When I test the script, it says "The file has been uploaded successfully." but when I check the FTP server, it hasn't really...
Also, if you need to know, here's the HTML codes:
Form tag:
<form name="profilestyle" action="account.php?action=profiletheme" method="post" enctype="multipart/form-data">
Input tag:
<input type="file" name="bgimage" />
Extra Information:
Yes, I remembered the CHMod the uploads directory
Odd, the code looks fine as far as I can see.
Can you use file_exists() to check whether the file exists, but maybe is not visible to your FTP user?
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file '$upload' has been uploaded successfully.";
if (file_exists($upload)) echo "And it exists! It is ".filesize($upload)." bytes big.";
else echo "But it doesn't exist.";
} else { echo "Error"; }
You also need to check $_FILES['bgimage']['error'] to make sure it is equal to UPLOAD_ERR_OK and is not an error code.
Please try the following test code
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
sprintf('<pre>Debug: moving file from %s to %s</pre>',
$_FILES['bgimage']['tmp_name'],
$upload
);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
sprintf('<pre>Debug: realpath=%s, filesize=%d</pre>',
realpath($upload),
filesize($upload)
);
}
else {
echo "Error";
}
and esp. keep an eye on the realpath=xyz output.

PHP File Validation using If statements uploads

Hi I am quite new to php but i have been following some tutorials but they don't seem to work so I have tried to adapt them.
I have tested this code and it works to a point but theres something else I can't get my head around, the php file is not uploading (fine) but the details are still being writen to the datbase although the $ok is spose to be set to 0 (not fine). It might be easier if explain what is ment to happen here:
-The User can upload gif or jpeg files. Details added to the db.
-The User can upload no file as a default will be used. Details added to the db.
-The User should not be able to upload any other file. No record should be on the db, user should have to try again.
My Code so far:
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=0;
//This gets all the other information from the form
$name= mysql_real_escape_string ($_POST['nameMember']);
$bandMember= mysql_real_escape_string ($_POST['bandMember']);
$pic= mysql_real_escape_string ($_FILES['photo']['name']);
$about= mysql_real_escape_string ($_POST['aboutMember']);
$bands= mysql_real_escape_string ($_POST['otherBands']);
$uploaded_size=$_FILES['photo']['file_size'];
if ($uploaded_size > 350000)
{
echo "Your file is too large, 35Kb is the largest file you can upload.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
if ($uploaded_type =="image/gif")
{
echo "GIf<br>";$ok=1;
}
if (empty($pic)){
echo "You haven't uploaded a photo, a default will be used instead.<br/>";$ok=1;}
if ($ok==0)
{
Echo "Sorry your file was not uploaded, please try again with the correct format.";
}
//If everything is ok we try to upload it
else
{
// Connects to your Database
mysql_connect("localhost", "*******", "******") or die(mysql_error()) ;
mysql_select_db("project") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO dbProfile (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br/>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
else {
//Gives and error if its not
echo "<p>If you have uploaded a picture there may have been a problem uploading your file.</p>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
}
?>
Cheers in advance. CHL
The error probably is this if statement:
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
Because every time you upload an image that does not have a content type that equals "image/jpeg", $ok evaluates to 1, so everything gets written to the database.
But also notice, that just checking the MIME type like this can get you into trouble, since the user is able to fake the MIME type of a file.
You could use Imagick to get the correct image MIME type, for example. See more details here: http://de2.php.net/manual/en/function.imagick-identifyimage.php
Edit: Just noticed, that $uploaded_type does not get initialized anywhere in your script. As I said, you can do a rough estimation of the MIME type by using $_FILES['photo']['type'].

Categories