On my website, I allow users to submit files and they are sent to the database and a file directory, devFiles, I created. It sends to the database fine, but when i send it to the directory, it never sends and i get my error message i created to see if it sends or not. I believe the problem is with the
if(is_file($dir.'/'.$file_name)==false){
//code...
}
but i tried change the condition but it didn't work. So what i want to do is, send the file that was submitted to the file directory on hand that was created. Here is my code
PHP
$query = "INSERT INTO pack_screenshots(pack_id, file_name, file_tmp)VALUES(:packid, :file_name, :file_tmp)";
$stmtFileUpload = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));
try{
$stmtFileUpload->bindParam(':packid', $packid, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
if(!move_uploaded_file($file_tmp,$dir.'/'.$file_name)){
die("File didn't send!");
}
}else{
$_SESSION['invalid'] = true;
header("Location: developer_invalid.php");
exit;
}
$stmtFileUpload->execute();
$_SESSION['thankyou'] = true;
header("Location: developerUpload_thankyou.php");
exit;
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
PHP Documentation bool move_uploaded_file ( string $filename , string $destination )
You did :
move_uploaded_file($file_tmp,$dir.'/'.$file_name)
move_uploaded_file is expecting $file_tmp to be a path to the tmp file but you used
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
so $file_tmp is no longer the path but the content it self
So to solve the upload problem just use the tmp file path instead.
if(!move_uploaded_file($_FILES['file']['tmp_name'][$key],$dir.'/'.$file_name)){
Also, you should remove addslashes() on the file name because it could create unexpected results. Instead, you can sanitize the filename using something like this:
$file_name = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['file']['name'][$key]));
You should also consider adding a random number to the file name so users don't overwrite other users files that have the same name: me.png could be common for an avatar for example. Would be safer to save as
$filename = strtotime("now")."_me.png";
One last thing, using is_file() can also cause problems in certain cases
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
use file_exists() instead
Related
I allow users to submit files into the database on my website. But every time a file is submitted, i get these error messages
( ! ) Warning: file_get_contents() expects parameter 1 to be a valid path, array given in C:\wamp64\www\MT\developerUpload.php on line 8
( ! ) Warning: trim() expects parameter 1 to be string, array given in C:\wamp64\www\MT\developerUpload.php on line 9
But I was told that "file_get_contents" is the way you send the file contents to the database. Without the "file_get_contents" it sends perfectly but with it, it gives me those error messages and I am not sure why. So what i want to do is, submit the file using the "file_get_contents" so later on i can display the content on the users page. Here is my code
PHP
$query = "INSERT INTO pack_screenshots(pack_id, file_name, file_tmp)VALUES(:packid, :file_name, :file_tmp)";
$stmtFileUpload = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_tmp = file_get_contents($_FILES['file']['tmp_name']);
$file_name = addslashes(trim($_FILES['file']['name']));
try{
$stmtFileUpload->bindParam(':packid', $packid, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$stmtFileUpload->execute();
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$dir.'/'.$file_name);
}else{
$_SESSION['invalid'] = true;
header("Location: developer_invalid.php");
exit;
}
$_SESSION['thankyou'] = true;
header("Location: developerUpload_thankyou.php");
exit;
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
Your problem is you have no keys associated with the 2 lines giving you an error (and probably elsewhere in your code), therefore they are arrays (as you are not selecting a specific key).
You need to associate the keys to the $_FILES array.
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));
Since you are using multiple uploads so you have to assign keys to them before proceed.
file_get_contents() and trim() accepts string here you pass array in it without assigning key.
Try this:
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));
I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'
I've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.
I've tested this myself and it works, with the attachments arriving in gmail as expected.
However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.
The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):
controller
$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
'image/jpeg',
'image/jpg',
'image/png',
'application/pdf'
))
->setAllowRenameFiles(true)
->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp
if (!is_dir($path))
{
mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);
$result = $helper->sendMail($_FILES['filename']['name']);
if ($result)
{
$uploadSuccess = true;
/** Remove the temp file */
unlink($path . DS . $_FILES['filename']['name']);
}
helper
/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!$copyTo)
{
return false;
}
$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
$attachement,
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$file_incremented_id . '.' . $extension // Set order number as file name
);
try
{
$mail->send($copyTo);
return true;
}
catch (Exception $e)
{
return false;
}
Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?
So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.
I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini
what i want to do is to upload image to the server using php
this is my code
<?php
try {
$name = isset($_POST['variable2']);
$file = rand(1000,100000)."-".isset($_FILES['file']['name']);
$file_name = isset($_FILES['file1']['name']);
$file_loc = isset($_FILES['file1']['tmp_name']);
$file_size = isset($_FILES['file1']['size']);
$file_type = isset($_FILES['file1']['type']);
$folder="uploads123/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
echo "good";
}else{
echo "error";
}
} catch (PDOException $pe) {
die("Error occurred:" . $pe->getMessage());
}
?>
these are my problems
why is it that the output it just the "error" from the if statement? it doesn't give details about the error even if i'm using try and catch.
even if i give a wrong foldername(the directory where the image to be uploaded) it just give me output like "error" from the if statement.
it doesn't give error that the folder doesn't exist on the server.
thank you.
Your html form is like that?
<form action="target.php" enctype="multipart/form-data">
<!-- Content -->
</form>
Does folder exists? check privilegies on server for folder
Good way before move file:
$upload_dir = '/uploads123';
if(!is_dir($upload_dir)){
mkdir($upload_dir, 0777); // you may set your access rule
}
Then you can try move file to this dir
EDIT: Try changing PDOException to Exception
isset() returns a boolean (true or false)
$file_loc will not be a valid file location, but is a boolean:
$file_loc = isset($_FILES['file1']['tmp_name']); // $file_loc = true
move_uploaded_file wil fail as it has no valid file to move and returns false. Your code will echo "error" as a result of move_uploaded_file returning false.
There is no Exception thrown, let alone a PDOException.
I want to upload images to mysql server using php.
I have created html and sql connectivity but the image upload shows error.
I cant upload the image, it shows error of valid image i.e. you must upload jpeg,bmp,gif; and read/write in directory.
Can any1 help me solving this problem
the php file is
<?php
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
// Check to see if the type of file uploaded is a valid image type
function valid($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
//echo $file['type'];
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH = "image/";
$TARGET_PATH = $TARGET_PATH . basename( $_FILES['image']['name']);
$pimage = $_FILES['image']['name'];
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!valid($pimage))
{
$_SESSION['ERRMSG_ARR'] = array('You must upload a jpeg, gif, or bmp');
header("Location: admin.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['ERRMSG_ARR'] = array('A file with that name already exists');
header("Location: admin.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($_FILES['image']['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (p_category, p_name, p_quantity, p_desc, p_image) values ('$pcategory', '$pname','$pquantity','pdesc', '" . $pimage['name'] . "')";
$result = mysql_query($sql);
//Check whether the query was successful or not
if($result) {
$_SESSION['ERRMSG_ARR'] = array('Product added');;
$_SESSION['MSG_FLAG'] = 0;
session_write_close();
header("location: admin.php");
exit();
}else {
die("Query failed: ".mysql_error());
}
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['ERRMSG_ARR'] = array('Could not upload file. Check read/write persmissions on the directory');
header("Location: admin.php");
exit;
}
?>
I think
$pimage = $_FILES['image']['name'];
should be
$pimage = $_FILES['image'];
You probably missed this because your code is quite inconsistent - sometimes you use $pimage, while elsewhere you reference the $_FILES array directly. This makes it harder to maintain should the file field's name change. You could also type hint the valid() function to make PHP complain if $file isn't an array:
function valid(array $file) { ... }
What level of error reporting do you have set? It would highlight errors like trying to access undefined array keys.
See you are passing the image type in the line if (!valid($pimage))
But in the valid() function you are again trying to get the type of image $file['type'].
What George said should also work, but since you are making variables for the image type $ptype and name $pimage, you can use them itself.
So the changes should be $file['type'] becomes $file and $file['type'] & in the insert query $pimage['name'] becomes $pimage
I'm sure this solves it, Bahua ;)