Upload file to mySQL Database. Help with code - php

Okay so I am running into issues inserting a file into my database as a blob. I am able to upload the file to a folder on my database but I now want to insert the file into my database as a blob. I know this isnt generally ok to do but I WANT TO DO IT. Anyways I was wondering if anyone had any PHP code to insert a file into a blob table? I've tried using this to no avail maybe I am just not writing the SQL statement right?
<?php
$target = "./";
$target = $target . basename( $_FILES['uploadedfile']['name']);
$file=($_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
}else{
echo "There was an error uploading the file, please try again!";
}
mysql_connect("localhost","root","");
mysql_select_db("ivrsupport");
$sql=mysql_query("insert into CUSTOMER (AUDIO_FILE)values
('$file') where PHONE_NUMBER = ('15555215554')");
$r=mysql_query($sql);
if(!$r){
echo "Error in query: ".mysql_error();
}
mysql_close();
?>

I would avoid storing files in the database. That's what FileSystems are for and are much better at doing so. There are millions of posts out there in the blogosphere explaining why not to. Even for a small application I wouldn't do it. It just feels dirty. A blob in the database holds no metadata about the file itself where as a FS can be queried in many ways to gleem information like file size, modification times, permissions etc... My $0.02

You need to read the file into a variable and then insert it.. giving it the filename only wont do.
$fp = fopen($basename, 'r');
$content = fread($fp, filesize($basename));
fclose($fp);
$sql=mysql_query("insert into CUSTOMER (AUDIO_FILE)values
('$content') where PHONE_NUMBER = ('15555215554')");

$file simply contains the name of the file not it's contents.
Try the following:
<?php
$target = "./";
$target = $target . basename( $_FILES['uploadedfile']['name']);
$file=($_FILES['uploadedfile']['name']);
$fileContents = file_get_contents($file);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
}else{
echo "There was an error uploading the file, please try again!";
}
mysql_connect("localhost","root","");
mysql_select_db("ivrsupport");
$sql=mysql_query("insert into CUSTOMER (AUDIO_FILE)values
('$fileContents') where PHONE_NUMBER = ('15555215554')");
$r=mysql_query($sql);
if(!$r){
echo "Error in query: ".mysql_error();
}
mysql_close();

Related

PHP upload to specific folder

I am trying to do a php upload that will upload into a specific folder.
One would choose the file they wish to upload next to a dropdown box which is a folder list. This is because it organises files.
<?php
session_start();
if(!isset($_SESSION["USER"]["Admin"])){
header("Location: index.html?unath");
}
$folder = mysql_real_escape_string($_POST['loc']);
$target_path = "../../shared/docs/$folder";
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload2)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Currently the code uploads the file into the "docs" folder and not docs/folder. Instead it puts the folder name in front of the file. For example- if the folder is called "abc" and my file is called robs.docx it will upload it to the main Docs folder and call it abcrobs.docx
You have a missing slash
Replace this line:
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
with:
$upload2 = $target_path ."/". basename( $_FILES['uploadedfile']['name']);
OR:
Replace this line:
$target_path = "../../shared/docs/$folder";
with:
$target_path = "../../shared/docs/".$folder."/";
You do not need mysql_real_escape_string because there's no SQL involved here.
If no database connection is established, mysql_real_escape_string returns null. So you're probably throwing away the $_POST['loc'] value.
You should never ever use user supplied values for manipulating anything on the filesystem without really, really thorough inspection of what you're going to manipulate. See Security threats with uploads.
Use var_dump liberally to see what your values look like at various stages and do some debugging.
You are missing a slash after $target_path
Add a / on the end of your $target_path:
$target_path = "../../shared/docs/$folder/";
You should properly escape your variables:
$target_path = "../../shared/docs/". $folder ."/";

Error when moving uploaded files

I tried uploading a picture to a directory in my server with the code below. However, when i run it, I get this error:
Warning: move_uploaded_file(images/) [function.move-uploaded-file]: failed to open stream: Is a directory in /home/a2943534/public_html/add.php on line 24
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php7yEkDe' to 'images/' in /home/a2943534/public_html/add.php on line 24
What am I missing here, please?
<?php
include_once("connect.php");
?>
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['title']);
//This gets all the other information from the form
$title=$_POST['title'];
$name=$_POST['name'];
$describe=$_POST['describe'];
$pic=($_FILES['photo']['title']);
$url=$_POST['url'];
$country=$_POST['country'];
$endDate=$_POST['endDate'];
//Writes the information to the database
mysql_query("INSERT INTO `authors` VALUES ('$title', '$name', '$describe', '$pic', '$url', '$country', '$endDate')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
$result = "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
$result = "Sorry, there was a problem uploading your file.";
}
?>
<?php
// if the form has been submitted, display result
if (isset($result)) {
echo "<p><strong>$result</strong></p>";
}
?>
rather than writing
$target = $target . basename( $_FILES['photo']['title']);
you should write
$target = $target . basename( $_FILES['photo']['name']);
i think there is nothing like $_FILES['photo']['title']..
I think you make a mistake with
$target = $target . basename( $_FILES['photo']['title']);
Which should be
$target = $target . basename( $_FILES['photo']['name']);
This because title does not exists within the $_FILES['photo']
Also this error states it:
Unable to move '/tmp/php7yEkDe' to 'images/' in /home/a2943534/public_html/add.php on line 24
The to images/ does not contain your filename.
the error is obvious and self-explanatory.
the second parameter have to be a filename, not directory.
Apart from the SQL injection issue which seems to be present in every single PHP question that features MySQL here on SO, you should start debugging.
You're getting a pretty clear error on which line and what function call causes the error. Look the error up on Google, read the manual for the functions you're using.
Long story short: you should create two variables, print them before your function call, and figure out what's wrong.
<?php
$source = $_FILES['photo']['tmp_name'];
$target = "images/" . basename( $_FILES['photo']['title']);
echo "Moving '$source' to '$target'";
move_uploaded_file($source, $target);
You'll immediately see where the error occurs.

PHP file upload and passing diectory

Hi am sorry but I have difficulties solving the problem. What i want to do is to upload file and then pass the directory but its nbot working the way I expect. The upload goes to a server to a file called 'uploads' but I cannot pass the directory , cuz its what I need, in later decode function:
Here's the code for uploading file am using:
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
and then I want to pass directory to here just after $json = $api->decode ( ):it shld be between the brackets I put ($target_path . basename( $_FILES['uploadedfile']['name'])) but its not working and I dont know how to solve it. The case decode is supposed to get directory of the file which was just uploaded and then decode what is inside:
case "decode":
$json = $api->decode ($target_path . basename( $_FILES['uploadedfile'] ['name']));
$start='{"content":"';
$pos_start = strpos($json, $start);
$end='"}';
$pos_end = strpos($json, $end);
thanx for any advice, please help me out if you know how, thanx
The way you build your JSON looks flawed. Typically it's best to accumulate the data first, and do a json_encode as the very last step. This way your JSON is never accidentally mangled. It may still not be semantically valid but at least you can see why ;)
$data = array(
"content" => $target_path . basename( $_FILES['uploadedfile']['name'])
);
return json_encode($data);
I hope this helps:
$json = $api->decode ($target_path . basename( $_FILES['uploadedfile'] ['name']));
$o=json_decode($json);
echo $o->content;
if that doesn't work try:
$json = $api->decode ($target_path);
$o=json_decode($json);
echo $o->content;
Since you are using $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); above.

phpMailer sending attachment name, not attachment

Hi I have a file upload field with name="file1" and code in a phpmailer script:
if (isset($_FILES['file1']))
{
$file1_path = $_FILES['file1']['tmp_name'];
$file1_name = $_FILES['file1']['name'];
$file1_type = $_FILES['file1']['type'];
$file1_error = $_FILES['file1']['error'];
$mail->AddAttachment($file1_path);
}
And for some reason, it attached like php45we34 (each time diff, seems that its the temp name path, not the actual file)
Any help?
Strip spaces from your filename!
Blue hills.jpg should be Blue_hills.jpg
do
$fileName = str_replace(' ', '_', $fileName);
I suggest you to use function move_uploaded_file before adding attachment.
This is sample code that will move file from temporary location somewhere at your server
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
After that AddAttachment should work fine.
$mail->AddAttachment(basename($target_path . $_FILES['uploadedfile']['name']));
What you see is what should happen. You do not specify the attachment name, so phpMailer uses the name of the temporary file it's attaching.
If you want the file to have a different name, you have to specify it. The accepted answer works because it goes the other way round -- it changes the file name so that the file has the desired name.
The usual way to proceed would be to issue
$mail->AddAttachment($file1_path, $_FILES['file1']['name']);
to override the attachment name.

Error while uploading file in PHP

While uploading the file in php i am not able to upload all types of file, if any space is there in between file name that is not able to download. Please can anyone correct this code
here is my upload code
<?php
$target_path = "../mt/sites/default/files/ourfiles/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
$con = mysql_connect("localhost","mt","mt");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}else{
echo "Connected";
}
// Create table
mysql_select_db("mt", $con);
mysql_query("INSERT INTO mt_upload (FileName, FilePath)
VALUES ('".basename( $_FILES['uploadedfile']['name'])."', '".$target_path.basename( $_FILES['uploadedfile']['name'])."')");
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
make some check and validation on the file u upload
the script below can help u :
// 5MB maximum file size
$MAXIMUM_FILESIZE = 5 * 1024 * 1024;
// Valid file extensions (images, word, excel, powerpoint)
$rEFileTypes =
"/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|
ppt|pptx){1}$/i";
$dir_base = "/your/file/location/";
$isFile = is_uploaded_file($_FILES['Filedata']['tmp_name']);
if ($isFile) // do we have a file?
{// sanatize file name
// - remove extra spaces/convert to _,
// - remove non 0-9a-Z._- characters,
// - remove leading/trailing spaces
// check if under 5MB,
// check file extension for legal file types
$safe_filename = preg_replace(
array("/\s+/", "/[^-\.\w]+/"),
array("_", ""),
trim($_FILES['Filedata']['name']));
if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE &&
preg_match($rEFileTypes, strrchr($safe_filename, '.')))
{$isMove = move_uploaded_file (
$_FILES['Filedata']['tmp_name'],
$dir_base.$safe_filename);}
}
}
Not sure if this works, but try to change line 2 to this:
$target_path = $target_path . basename( urldecode ( $_FILES['uploadedfile']['name'] ) );

Categories