I have a problem with uploading path in my sql database. Not displaying all path.
This is the php code:
$rd2 = mt_rand(1000, 9999) . "_File";
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"));
$newname = "uploads/" . $rd2 . "_" . $filename;
if (!file_exists($newname));
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)));
$query = "insert into files (file_id,floc,subid,fname,fdesc,tcid)
values ($newstd,'$newname',
'".htmlspecialchars($_REQUEST['subid'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fname'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fdesc'], ENT_QUOTES)."',
'".$_SESSION['tcid']."')";
if (!#executeQuery($query)) {
if (mysql_errno () == 1062) //duplicate value
$_GLOBALS['message'] = "Given Subject Name voilates some constraints,
please try with some other name.";
else
$_GLOBALS['message'] = mysql_error ();
}
else
$_GLOBALS['message'] = "Successfully New Subject is Created.";
}
closedb();
The code is working and shows like this in database: http://i.stack.imgur.com/Z5jmb.png
It suppose to display uploads/2654_File_filename.docx
And the file is not uploaded.
The form is in a table:
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
</tr>
I used this:http://www.w3schools.com/php/php_file_upload.asp but same no working
I'm using xampp 5.6.8 and php.ini and file_uploads directive is set to On.
EDIT - newstd is:
$result = executeQuery("select max(file_id) as fid from files");
$r = mysql_fetch_array($result);
if (is_null($r['fid']))
$newstd = 1;
else
$newstd=$r['fid'] + 1;
$result = executeQuery("select fname as fid from files where
fname='" . htmlspecialchars($_REQUEST['fname'], ENT_QUOTES) . "'
and tcid=" . $_SESSION['tcid'] . ";");
// $_GLOBALS['message']=$newstd;
if (empty($_REQUEST['fname']) || empty($_REQUEST['fdesc'])) {
$_GLOBALS['message'] = "Some of the required Fields are Empty";
} else if (mysql_num_rows($result) > 0) {
$_GLOBALS['message'] = "Sorry Subject Already Exists.";
} else {
}
$rd2 = mt_rand(1000, 9999) . "_File";
...
...
EDIT: I forgot to mention that when i dont use a path he upload it in database.
I had a "global" form and i putted enctype="multipart/form-data" in it and it worked with saving the path in table.
Before was in form below and dont recognise it.
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
But still no uploading files...
Can you check if the file is not too large and exceeds the limitations of these two configurations:
post_max_size
upload_max_filesize
You can see the values from a file with:
<?php
phpinfo();
?>
Edit:
Another suggestion is to put the body brackets of the if's because the single line execution if the statement is valid, cant be trusted. I think the problem can be the :
if (!file_exists($newname));
Also the way you insert into the DB you take the name from the $_REQUEST and not the new name and where do you store the path ?
Related
I have two problems:
Name cannot be updated
Profile picture is deleted (the exist one) even though I did not upload a new one. I have no problem in uploading image though.
Below is the code
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
echo "<img src='" . $imageup . "' />";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = "UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'";
$success = mysql_query($query1);//is mysql query working?
if($success){
$oldprofilepicture = $staff['StaffProfilePicture'];
if(file_exists($oldprofilepicture)){
unlink($oldprofilepicture);//delete now
}
header('location:staff_profile.php');
}
}
Below is the line where a new name is entered.
<tr>
<td width="170">Full Name:</td>
<td><input type="text" name="new_name" size="30" value="<?php echo $staffname ?>" /></td>
</tr>
Regarding the image, create a hidden input field with the same value as from the database, e.g.:
<input type="hidden" value="/path/to/img.ext" name="old-image" />
Before this line:
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
Add:
$imageup = $_POST['old-image'];
Of course you need to do validation on the $_POST data. I've left it out of the above example.
This will set the default value for the image as the saved version. If you upload a new image, then that will override $imageup with the name path details :)
Regarding the name not changing, I cannot see where the value for $staffId is being set?
Ok guys this might seem like such a newbie issue but I've got looping issues that I just can't seem to work around. I'm simply trying to upload multiple images on my first project site.
When I posted this test php page up, it uploads all the files that I requested of it fine
; with all images that I wish to upload being uploaded at the directory intended.
<?php
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
?>
However when I tried including my parser, though it goes into the correct directory, only the first file gets uploaded
<?php
if(isset($_POST['property_name'])){
$property_name = mysql_real_escape_string($_POST['property_name']);
$district = mysql_real_escape_string($_POST['district']);
$address = mysql_real_escape_string($_POST['address']);
$property_type = mysql_real_escape_string($_POST['property_type']);
$sql = mysql_query("SELECT id FROM mydb WHERE property_name='$property_name' LIMIT 1");
$propertyMatch = mysql_num_rows($sql);
if($propertyMatch > 0)
{
echo 'Sorry, you tried to place a duplicate "Property Name" into the system, click here';
exit();
}
$sql = mysql_query("INSERT INTO mydb (property_name, district, address, property_type) VALUES ('$property_name','$ district','$address','$property_type')")or die (mysql_error());
if (!file_exists("property_images/$property_name"))
{
mkdir("property_images/$property_name");
}
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
}
?>
The count code works fine so I think its either these {} buggers or I need to get my eyes fixed. Any help would be uber appreciated.
you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at http://www.php.net/manual/en/features.file-upload.multiple.php
hope this will sure help you.
I'm trying to upload two file in one submit button using the following code:
<label>Logo Image *</label>
<input type="file" name="ufile[]"/>
<label>Banner Image *</label>
<input type="file" name="ufile[]"/>
PHP
$logo = $_FILES['ufile']['name'][0];
$block_img = $_FILES['ufile']['name'][1];
if ($_FILES['ufile']['name']["error"] > 0) {
echo "error<br>";
}
else {
if (file_exists("small-image/" . $_FILES['ufile']['name'][0])){
echo $_FILES['ufile']['name'][1] . "File already exists in server. ";
}
else {
move_uploaded_file($_FILES['ufile']['name'][0], "small-image/" . $_FILES['ufile']['name'][0]);
move_uploaded_file($_FILES['ufile']['name'][1], "small-image/" . $_FILES['ufile']['name'][1]);
}
}
$sql_query = "UPDATE header_img SET logo_img = '$logo', block_img = '$block_img' WHERE banner_id = 1";
My database is updating correctly but the file is not uploaded. Yes there is a 777 directory call 'small-image'.
Any idea?
Thanks.
When you use move_uploaded_file, you want to use $_FILES['ufile']['tmp_name'], that's where the file is currently located.
move_uploaded_file($_FILES['ufile']['tmp_name'][0], "small-image/" . $_FILES['ufile']['name'][0]);
move_uploaded_file($_FILES['ufile']['tmp_name'][1], "small-image/" . $_FILES['ufile']['name'][1]);
Check the example in the docs: http://php.net/manual/en/function.move-uploaded-file.php
I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out.
This is my upload function:
function upload(){
global $imagefolder, $id;
global $tbl_units;
include "globalizePOSTGET.php";
// $uid = uuid();
$minsize = 5000; // 5kb
$maxsize = 3000000; // 3mb
$ext = explode('.',basename($_FILES['userfile']['name']));
$ext = $ext[count($ext)-1];
$ext = strtolower($ext);
if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
echo "<script> alert('Image is not a png or jpeg format'); </script>";
return false;
}
$imagename = $_POST['id']."_img".$_FILES['img'].".$ext";
$imagename2 = "X_".$imagename;
$uploadfile = $imagefolder . $imagename;
$uploadfile2 = $imagefolder . $imagename2;
$uploadthumb = $imagefolder . "tn_" . $imagename;
if (file_exists($uploadfile)) unlink($uploadfile);
if (file_exists($uploadthumb)) unlink($uploadthumb);
if (file_exists($uploadfile)) {
echo "<script> alert('Image already exists!'); </script>";
}
else
{
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
// check the file is less than the maximum file size
if($_FILES['userfile']['size'] < $maxsize) {
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion
$size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info..
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) {
$Image = #imagecreatefromjpeg($uploadfile2);
if ($Image) {
$img_height = imagesy($Image);
$img_width = imagesx($Image);
imagedestroy($Image);
}
if ($img_height > $img_width) { // portrait
$tempMultiplier = 150 / $img_height;
$tempMultiplierFull = 600 / $img_height;
} else {
$tempMultiplier = 150 / $img_width;
$tempMultiplierFull = 600 / $img_width;
}
$imageHeight = $img_height * $tempMultiplier;
$imageWidth = $img_width * $tempMultiplier;
$fullimageHeight = $img_height * $tempMultiplierFull;
$fullimageWidth = $img_width * $tempMultiplierFull;
createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight);
if($_FILES['userfile']['size'] > $minsize) {
createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight);
if (file_exists($uploadfile2)) unlink($uploadfile2);
} else {
rename($uploadfile2, $uploadfile);
}
$sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
echo $sql;
if(!mysql_query($sql)) {
echo "<script> alert('Unable to upload file'); </script>";
} else {
?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php
}
}
} else {
// if the file is not less than the maximum allowed, print an error
$file_n = basename($_FILES['userfile']['name']);
$file_s = $_FILES['userfile']['size'];
?>
<script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script>
<?php
}
}
}
}
I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:UPDATE member_units SET photo = "_img.jpg" WHERE id = `
Someone please help me! I am very inexperienced in PHP and I have no idea what to do here.
Here is the form that is doing the uploading:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="hidden" name="_submit_check" value="1" />
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="img" value="<?php echo $img; ?>" />
Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;">
<input type="submit" value="Submit" onClick="return validate();">
<input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';">
</form>
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement...
UPDATE member_units SET photo = "_img.jpg" WHERE id = `
This corresponds to...
UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id'];
We can see by comparison that it is clear that $_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $_POST['id'], while $imagename gives a short _img.jpg file name.
Tracking back you can then see that $imagename comes from...
$_POST['id']."_img".$_FILES['img'].".$ext";
This is where your photo = "_img.jpg" comes from. Again, $_FILES['img'] and $_POST['id']
The fact that you're reaching the echo statement means that something is uploading, but it is through the $_FILES['userfile'] array, with all of it's associated variables, for example $_FILES['userfile']['name'] which would give you the filename of the image being uploaded.
What you need to ask yourself next is where you are expecting $_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1_imgLolCat.jpg then your variable will need to look more like
$imagename = $_POST['id']."_img".$_FILES['userfile']['name'];
However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from...
$imagename = $_POST['id']."_img".$_POST['img'].".$ext";
...if a HTML field exists with the name "img"!
Finally take a look at your SQL statement...
SET photo".$_FILES['img']." = \"" . $imagename . "\"
And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $_POST['img'] in there.
Word of warning, you need...NEED to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take
SET photo".$_POST['img']
and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ?
Be careful, your script can be the target of an SQL injection : you use a user input ($_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];