This code has no error, checked the console no errors, print_r($temp) gives proper result.
print_r($_FILES["file"]["tmp_name"]) gives proper result but the values are no stored in the
phpMyAdmin Db and in the uploaded_videos dir. The last line is also not printed on the screen
<?php
include("database_connection.php");
$allowedExtn = array("mp4","mov","avi","wmv","flv","mpeg");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$videoname = $_FILES["file"]["name"];
if((($_FILES["file"]["type"]=="video/mp4")
|| ($_FILES["file"]["type"]=="video/mov")
|| ($_FILES["file"]["type"]=="video/avi")
|| ($_FILES["file"]["type"]=="video/wmv")
|| ($_FILES["file"]["type"]=="video/flv")
|| ($_FILES["file"]["type"]=="video/mpeg"))
&& in_array($extension, $allowedExtn))
{
if($_FILES["files"]["error"]>0)
{
echo "Error in Uploading video ". $_FILES["file"]["name"];
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "uploaded_videos/" .
$_FILES["file"]["name"]);
$filepath = "uploaded_videos/" . $_FILES["file"]["name"];
$query = "INSERT INTO video_upload (username, video_name, video_ext,
video_url) VALUES ('Venkat', 'videoname','$extension','$filepath')";
mysql_query($query);
print_r($query);
mysql_close();
echo "Video " .$videoname . " saved.";
}
}
?>
Can anyone please tell me where is the short coming..??
If you are on linux and have access to the filesystem then check the permissions and ownership of the uploaded_videos directory (use ls -la or similar) if you need to change them then look up chmod and chown or use your cpanel? interface.
Make sure also that the directory exists where you think it does (in the same directory as the script you are running).
The first task to sort out is the writing to disk - I'd suggest commenting out the mysql for now.
Also try it with a small file that has a shortish filename with no funny characters or spaces first.
Turn on error reporting in your script error_reporting(E_ALL); ini_set('display_errors',true)
and check the return value of move_uploaded_file
if it is false with no errors then check the file
if it is false with errors then check the filesystem (and the errors)
First of all use MySQLI or PDO for your queries.
$insertQuery = " INSERT INTO `databaseName`.`tableName` (`username`,`video_name`,`video_ext`, `video_url`) VALUES ('Venkat','videoname','$extension','$filepath') ";
$insertQueryResult = $connector->query($insertQuery);
I think you should put the
$filepath = 'uploaded_videos/'.$_FILES['file']['name'];
below of the :
$videoname = $_FILES['file']['name'];
This is just a simple sample for using MySQLI. You can refer to THIS LINK
Related
I have a peace of code that stores profile images in the map "images/profiles" and stores the URL in the database. I want to define the name of the uploaded profile picture to be the $ID of the user. How can I do this?
include("../../core/init.inc.php");
$target = "../images/profiles/";
$target = $target . basename($_FILES['photo']['name']);
$pic = $_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename($_FILES['photo']['name']). " has been uploaded";
} else {
echo "ERROR";
}
mysql_query("UPDATE users SET image_url='includes/images/profiles/$pic' WHERE username = '".mysql_real_escape_string($_SESSION['username'])."'");
Now when someone uploads his profile picture (lets call it pf1.png) it saves it as "pf1.png". I want it to be saved like "$ID.png" (.png being a random extension). I want to accomplish this both for the move_upload_file function and updating the 'image_url' database column correctly.
According to the example in the documentation you can provide the filename in the destination of move_uploaded_file(). If that fails you can simply rename() the file after saving it.
try changing
$target = $target . basename($_FILES['photo']['name']);
to:
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$target = target . $_SESSION["ID"].".".$extension;
side note: You are not escaping $pic this makes your site vulnerable to sql-injection
I don't know how you saved the ID of the user, but to make it easy let's assume you stored the ID in a session.
Then simply change the $target.
$target = $target . $_SESSION['ID'];
Also change your query as follows:
$url = "includes/images/profiles/" . $_SESSION['ID'];
SET image_url="$url"
Note: I don't know why you got an image folder inside an includes folder, but I guess you made that choice for yourself.
you can get the last inserted id and make it as a name of your image/uploaded file
$qry = mysqli_query($dbconnection,"INSERT INTO statements here");
$last_id = mysqli_insert_id($dbconnection);
//$ext= you get the extension of the file uploaded
move_uploaded_file($tmpname,$target.$last_id.$ext);
now if you want it to be accomplished in updating also.
you can always get the ID of the data you want to fetch and make it as a basis in updating.
ex.
$id = $_GET['id'] || $id = $row['id']; //anything depends on how you want it to retrieve
then you can do the query and move_uploaded_file function
$qry = mysqli_query($dbconnection,"UPDATE tblname SET field='$anything' WHERE id = '$id'");
move_uploaded_file($tmpname,$target.$id.$ext);
of course $tmpname will be the basis on what file you have uploaded, $tmpname will be the file you want to move into your desired directory
I am trying to update images in my upload folder and mysql database the file uploads giving the file name 0.jpg instead of the normal persons id 13.jpg and does not update in mysql database, here is my snippet below what am i doing wrong?
$pic = mysql_real_escape_string(htmlspecialchars($_FILES['photo']['name']));
//This gets all the other information from the form
$pic=($_FILES['photo']['name']);
$file = $_FILES['photo']['name']; // Get the name of the file (including file extension).
$ext = substr($file, strpos($file,'.'), strlen($file)-1);
if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
die('The file extension you attempted to upload is not allowed.'); //not allowed
if(filesize($_FILES['photo']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
die ('The file you attempted to upload is too large, compress it below 50MB.');
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("office") or die(mysql_error()) ;
//Writes the information to the
$target = "images/" .mysql_insert_id() . $ext;
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
//Writes the file to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Instead of this
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
do something like thus
mysql_query ("INSERT INTO development (photo) VALUES ( '".$new_file_name."' )");
//first insert
$staff_id = mysql_insert_id() ;
// then get the id of the record you've just inserted
Firstly, you're using the mysql_* functions, which are deprecated as of 5.5.
Secondly, you need to look at the manual page for mysql_insert_id. Quote:
Retrieves the ID generated for an AUTO_INCREMENT column by the
previous query (usually INSERT).
This means that you can only call mysql_insert_id() AFTER you've inserted data into or updated your users/persons table. In your case, however, it seems as though you already have the ID of the person stored in the variable $staff_id, so you probably don't even need to use mysql_insert_id. Would this not work instead?
$target = "images/" . $staff_id . $ext;
I have the following script which takes some value from a form and appends to a text file each time new values are entered in the form:
$filename = "nic.txt"; #Must CHMOD to 666, set folder to 777
$text = "\n" . str_pad($fname, 30) . "" . str_pad($lname, 30) . "" . str_pad($tdate, 20) . "" . str_pad($ydept, 30) . "" . str_pad($percentage, 0) . "%";
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);
#echo ("File written");
}
else {
#echo ("File was not written");
}
The issue is, instead of writing to a txt file which isn't secured in storing data, how can I let's say append to a php file so user would need authentication before viewing the file on the web?
I would like some sort of authentication (password/username) in place so not everyone can see it. And with txt file I don't think it's possible.
My SQL writing to data file which I commented out until I find the best option is:
// Write to DB
//$conn = new mysqli('host', 'user', 'pass', 'db');
// check connection
//if (mysqli_connect_errno()) {
// exit('Connect failed: '. mysqli_connect_error());
//}
// store the values in an Array, escaping special characters for use in the SQL statement
//$adds['fname'] = $conn->real_escape_string($fname);
//$adds['lname'] = $conn->real_escape_string($lname);
//$adds['tdate'] = $conn->real_escape_string($tdate);
//$adds['ydept'] = $conn->real_escape_string($ydept);
//$adds['percentage'] = $conn->real_escape_string($percentage);
// sql query for INSERT INTO users
//$sql = "INSERT INTO keepScore ('fname', 'lname', 'tdate', 'ydept', 'percentage' ) VALUES ('". $adds['fname']. "', '". $adds['lname']. "', '". $adds['tdate']. "', '". $adds['ydept']. "', '". $adds['percentage']. "')";
// Performs the $sql query on the server to insert the values
//if ($conn->query($sql) === TRUE) {
// echo 'users entry saved successfully';
//}
//else {
// echo 'Error: '. $conn->error;
//}
//$conn->close();
Keep your text file out of the web server's document root, and use a PHP script to provide authentication/authorization when reading the file.
Take a look at readfile().
PHP files are text files. To achieve what you are asking for, just make $filename end in .php (making sure the data people add is just data and not executable code).
… but editing code programatically is not a great idea. Store your data somewhere outside the web root (possibly in a file, but a database is probably better) and then have your script retrieve it when auth/authz is passed).
A simple solution would be to create a directory with a .txt file in it, which is .htpasswd protected. This way a user needs to authenticate to view the contents, and you are not putting yourself at risk for an untold number of security vulnerabilities.
You can store the files with the .php extension and add header information to serve them as plain text instead of html. Then you can insert a php code at the beginning that will cause the user to authenticate themself.
So I've made this upload script and to make it more secure, I'm finding out the type of each file.
However, for some reason, the filetype is being echoed back to me!
For example:
image/jpeg; charset=binary Please upload only SWF files!
The echoed string looks same when the upload is successful.
The code:
<?php session_start();
defined('IN_SCRIPT') ? NULL : define('IN_SCRIPT', NULL);
require_once 'inc/db_connect.php';
require_once 'styles/import.php';
$style = new style_class(NULL);
if(!isset($_FILES['file']['tmp_name']) || empty($_FILES['file']['tmp_name'])) die($style->upload_no_parameter());
$filetype = system('file -bi '.$_FILES['file']['tmp_name']);
$filetype = explode(';', $filetype, 1);
if ($filetype[0] != 'application/x-shockwave-flash; charset=binary') die($style->upload_wrong_format());
$sha256 = hash_file("sha256", $_FILES['file']['tmp_name']);
$query = $db->prepare('SELECT id FROM swf WHERE hash = :hash');
$result = $query->execute(array(':hash'=>$sha256));
if ($query->rowCount() != 0) die($style->upload_duplicate());
$query = $db->query('SELECT * FROM swf ORDER BY id DESC LIMIT 1;');
$name = $query->fetch(PDO::FETCH_ASSOC);
$new_name = 'uploads/'.($name['id']+1).'.swf';
if(move_uploaded_file($_FILES['file']['tmp_name'], $new_name)) {
$query = $db->prepare('INSERT INTO swf (uploader, upload_time, hash) VALUES (:id, NOW(), :hash);');
$query->execute(array(':id' => $_SESSION['id'], ':hash'=> $sha256));
echo $style->upload_success();
}
else
echo $style->upload_fail();
?>
I can't see why the script would do such echo...
Thank you!
EDIT:
The style_class was the first place where I looked. This class contains functions returning mainly HTML text. The whole class is auto-generated from database.
I'm copying here the upload_* from the generated file, so you can see:
class style_class{
function upload_no_parameter(){
echo "<b>All parameters must be set!</b>";
}
function upload_fail(){
echo "<b>There was an error, please try again.</b>";
}
function upload_success(){
echo "<b>Your SWF has been uploaded!</b>";
}
function upload_duplicate(){
echo "<b>File already exists!</b>";
}
function upload_wrong_format(){
echo "<b>Please upload only SWF files!</b>";
}
}
Thank you!
I'd bet die($style->upload_wrong_format()) is causing the issue. Check that function.
You've got some very nasty logic bugs in your code:
1) Assuming the file upload succeeded. Proper error handling goes like this:
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("File upload failed with error code " . $_FILES['file']['error']);
}
Checking any of the other fields in any file upload is not proper - those fields can still be present and populated even for a failed upload. The error codes are documented here: http://php.net/manual/en/features.file-upload.errors.php
2) you're using exec() and calling file to determine mimetypes. Why? PHP has the finfo library for just this purpose: http://php.net/manual/en/book.fileinfo.php it uses the same magic numbers library as file and doesn't require an exec() call to work.
3) You have a very racey error-prone method of getting an ID number for your swf:
$query = $db->query('SELECT * FROM swf ORDER BY id DESC LIMIT 1;');
$name = $query->fetch(PDO::FETCH_ASSOC);
$new_name = 'uploads/'.($name['id']+1).'.swf';
Nothing says that another script cannot execute AND complete in the time you fetch this ID number and the time you complete thigns here. A proper method is to start a transaction, insert a skeleton record into the DB, retrieve its auto_increment primary key, then update the record and do your file moves with that id. It'll be guaranteed to be unique, whereas at some point your code WILL fail and stomp on another upload.
i have been stressing for an hour at this stupid script i am trying to make it uploa an MP3
file to a folder it creates.
It is putting the information into mysql and making the folder bu when i ftp the folder is empty with no music file in there
here is the script thanks so so so much!
BTW $name is the POSTED name and full name is the posted name + ".mp3"
// BEGIN ENTERING INFORMATION TO MYSQL TABLE
$sql = mysql_query("INSERT INTO mattyc (name, date, length, size, link)
VALUES('$name','$date','$length','$size','$link')"
) or die (mysql_error());
mkdir("../music/albums/donjuma/$name", 0777);
$song = ("../music/albums/donjuma/$name/$fullname");
if (file_exists($song)) {
unlink($song);
}
$newname = "$fullname";
$newfile = rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file( $newfile, "../music/albums/donjuma/$name/"."$newname");
$success_msg = "<font color=\"#009900\">Your SONG has been updated, it may take a few minutes for the changes to show... please be patient.</font>";
echo $success_msg;
}
}
}
$newfile =
rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file(
$newfile,
"../music/albums/donjuma/$name/"."$newname");
rename() returns a bool, not a filename. So your move_uploaded_file() call is going to fail. Any file renaming should be part of your move_uploaded_file() call, don't try and do anything with your temporary file apart from move it.