Im trying to create a script which add a random no. in the uploaded file and then upload it to the server
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a _ on the end, so it is ready of the file extension to be appended.
$ran2 = $ran."_";
//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=$ran2.$_FILES['uploaded']['name'];
//escape User Input to help prevent SQL Injection
$name= mysql_real_escape_string($name);
$email= mysql_real_escape_string($email);
$phone= mysql_real_escape_string($phone);
$pic= mysql_real_escape_string($pic);
// Connects to your Database
mysql_connect("example.com", "user", "password") or die(mysql_error()) ;
mysql_select_db("database") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `table` VALUES ('$name', '$email', '$phone', '$pic')") ;
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "images/";
//This combines the directory, the random file name, and the extension
$target = $target . $pic;
//Writes the photo to the server
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
//Tells you if its all ok
echo "file uploaded in ".$target;
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
though i think the problem is in move_uploaded_file or $pic=$ran2.$_FILES['uploaded']['name']. Please help me correct it.
use copy function instead of move_uploaded_file to copy & rename uploaded file.
copy($_FILES['uploaded']['tmp_name'], $target);
Related
Hey guys I am having issues with my php file which is supposed to allow a user to post a status along with a picture which is uploaded to a server and its path along with the username of the user is added to the db.
DB Colomns:
postID (A.I)
username
status
imagepostpath
timestamp (added automatically inserting a new entry)
extra info: I have changed the code from one of my already working ones, but when I attempt to test the PHP file with Postman my error is "[]".
I'm not too familiar with PHP so if you see that the mistake that I'm making is simple, please help me understand it :)
Here is my code:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = '000002/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://'.$server_ip.'/Users/Images/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['name']) and isset($_FILES['image']['name'])){
//connecting to the database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//getting name from the request
$name = $_POST['name'];
$status = $_POST['status'];
$timestamp = date('Y-m-d H:i:s');
//getting file info from the request
$fileinfo = pathinfo($_FILES['image']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_url . getFileName() . '.' . $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName() . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
$sql = "INSERT INTO `flare`.`tbl_user_feed` (`postID`, `username`, `status`, `imagepostpath`, `timestamp`) VALUES (NULL, '$name', '$status', '$file_url');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['name'] = $name;
$response['imagepostpath'] = $file_url;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//displaying the response
echo json_encode($response);
//closing the connection
mysqli_close($con);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
}
/*
We are generating the file name
so this method will return a file name for the image to be upload
*/
function getFileName(){
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
$sql = "SELECT max(postID) as postID FROM tbl_user_feed";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['postID']==null)
return 1;
else
return ++$result['postID'];
}
?>
Change these lines:
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
Your file path is always the same so old files are being overwritten by new...randomize it with md5()
$unix = time();
$file_path = $upload_path . getFileName() . md5($unix) . '.'. $extension;
then alter your query slightly
$sql = "INSERT INTO `flare`.`tbl_user_feed` (`postID`, `username`, `status`, `imagepostpath`, `timestamp`) VALUES (NULL, '$name', '$status', '$file_url', '$unix')";// remove the semicolon before last double quote and add value for 5th column
I am working on a school project that let users upload video files to a server. Server will compress the video using ffmpeg and store the file in upload folder. Other users will be able to stream the uploaded videos.
My question is how do i retrieve the video that ffmpeg generated and store the link in the database?
i am using this code but it only retrieve path of the original video.
$filePath = dirname(__FILE__);
partial code of Upload.php
$target_dir = "upload/"; //where you want to upload the files to
$target_file = $target_dir.basename($_FILES['file']['name']);
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
$newFileName = $target_dir.sha1(pathinfo(basename($_FILES['file']['name']), PATHINFO_FILENAME)).'-'.time().'.'.$fileType;
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
$unique_id = rand(1000000,9999999);
shell_exec("C:\\ffmpeg\\bin\\ffmpeg.exe -i ".$newFileName." -vcodec libx264 -crf 20 \"upload\\{$newFileName}\" > logfile.txt 2>&1");
/// save information into database
$username = "root";
$password = "";
$hostname = "localhost";
$dbname = "test_database";
//connect to the database
$dbc = mysqli_connect($hostname, $username, $password, $dbname) or die ("could not connect to the database");
//execute the SQL query and return records
$result = mysqli_query($dbc, "INSERT INTO `viewvideo` (`vID`, 'video_id`, `video_link`) VALUES ('', '".$unique_id."', '".$newFileName."')");
if(!$result){echo mysqli_error($dbc); }
echo $result;
/*
declare in the order variable
$result = mysqli_query($dbc, $sql); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
*/
//close the connection
mysqli_close($dbc);
output
Remember to move the uploaded file to a directory of your choice. A way to prevent files overwriting each other is creating a new name for it. Do this when the upload is a success.
Properly uploading & adding the video to the database
$target_dir = "video/"; //where you want to upload the files to
$target_file = $target_dir.basename($_FILES['file']['name']);
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
$newFileName = $target_dir.sha1(pathinfo(basename($_FILES['file']['name']), PATHINFO_FILENAME)).'-'.time().'.'.$fileType;
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
After that you'll have to create a table & insert two core things; a unique/token generated ID for the video and the $newFileName path.
You can either use a function which generates a token/id which includes alpha-numeric characters or something simple as this
$unique_id = rand(1000000,9999999);
Lets consider you have a table videos with 3 columns; vID, video_id & video_link
vID should be an auto incrementing INT. video_id would be a INT and the video_link a TEXT type.
After that it's SQL.
$result = mysqli_query($db_connection, "INSERT INTO `videos` (`vID`, video_id`, `video_link`) VALUES ('', '".$unique_id."', '".$newFileName."'");
if(!$result){echo mysqli_error($db_connection); }
Retrieving it would be something like this. Be sure to add this on another page. Let's consider stream.php as the page's name for streaming the video.
if(isset($_GET['id'])){
$id = trim($_GET['id']);
//check if it exists
$result = mysqli_query($db_connection , "SELECT `video_id`, `video_link` FROM `videos` WHERE `video_id`='".$id."'");
$count = mysqli_num_rows($result);
//does it exist?
if($count>0){
//exists, so fetch it in an associative array
$video_arr = mysqli_fetch_assoc($result);
//this way you can use the column names to call out its values.
//If you want the link to the video to embed it;
echo "Video Link: ".$video_arr['video_link'];
}else{
//does not exist
}
}
And finally, creating a link to it: http://your-website.com/stream.php?id=video id here
I have a form that uploads a file with other information to a database and displays it in a chart. Right now the chart only displays the file name and doesen't link it. If the file was called test1.pdf, how would I make it so on the chart it still says chart1.pdf but links it to the directory that the file is on?
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jjlliinn_test", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['name']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['name']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
//Tells you if its all ok
echo "";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES
('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}
?>
Assuming all your uploads are stored in the client doc folder and you have run the query to get the recordset from the transactions table...
link text
Another point, looking at the code, sending raw $_POST values direct to the db is asking for sql injection trouble. Have a look at either htmlentities with ENT_QUOTES set or the input filters available with php.
I have a submission system set up and I'd like to have it so no duplicate entries can be submitted. If one is submitted, the ORIGINAL record and file upload is kept (not overwritten). Also, if it exists I'd like the form to display an error to the user. Here's my upload.php (referred to in the HTML form).
upload.php
<?php
//This is the directory where images will be saved
$extension = explode(".", $_FILES['upload']['name']);
$extension = $extension[count($extension)-1];
$target = "uploads/";
$target = $target . $_POST['snumber'] . "." . $extension;
//This gets all the other information from the form and prevents SQL injection
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$upload=($_FILES['upload']['name']);
$snumber=$_POST['snumber'];
$grade=$_POST['grade'];
$email=$_POST['email'];
// Connects to your Database
mysql_connect("localhost", "db_user", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `Table` VALUES ('$fname', '$lname', '$snumber', '$grade', '$email', '$target')") ;
//Writes the upload to the server
if(move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
//Tells you if its all ok
echo "Your submission ". basename( $_FILES['uploadedfile']['name']). " was successful and we have received your submission. Your result will be sent to $email ";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
How would I go about doing this?
EDIT: Combined suggestions from below, here's updated code however now I'm getting a Parse error: syntax error, unexpected T_ECHO in /path/to/upload.php on line 32
New upload.php
<?php
//This is the directory where images will be saved
$extension = explode(".", $_FILES['upload']['name']);
$extension = $extension[count($extension)-1];
$target = "uploads/";
$target = $target . $_POST['snumber'] . "." . $extension;
//This gets all the other information from the form and prevents SQL injection
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$upload=($_FILES['upload']['name']);
$snumber=$_POST['snumber'];
$grade=$_POST['grade'];
$email=$_POST['email'];
//Checks if submission already exists
if(file_exists($target))
{
echo "This submission already exists. Please check that you have entered all values correctly. If this is an error please contact support";
}
else
{
//Now that file doesn't exist, move it.
move_uploaded_file($_FILES['upload']['tmp_name'], $target);
//MYSQL CONNECTION
mysql_connect("localhost", "db_user", "password") or die(mysql_error()) ;
mysql_select_db("db_name") or die(mysql_error()) ;
//MYSQL Entry
mysql_query("INSERT INTO Table (fname, lname, snumber, grade, email, target) VALUES ('".mysql_real_escape_string($fname)."', '".mysql_real_escape_string($lname)."', '".mysql_real_escape_string($snumber)."', '".mysql_real_escape_string($grade)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($target)."')")
echo "Your submission was successful and we have received your portfolio. Your marks will be sent out to $email.";
}
?>
Looks like you're storing the target in your database, so you can either check the database to see if that file already exists or you can use php's file_exists() function.
DB you obviously run the query before that insert statement and make your conditional based off the results.
Otherwise,
if(file_exists($target))
{
echo 'error';
}
else
{
move_uploaded_file($_FILES['upload']['tmp_name'], $target);
// do success things here
}
file exists may require the full path. If it doesn't work right away see if prepending $_SERVER['DOCUMENT_ROOT'] helps.
I have solved this issue by applying an ajax query before submitting the form and the file
var param = "action=testfile&dirpath=" + dirpath + "&file=" + filename;
$.ajax({
type: "GET",
url: 'combi/testfile.php',
data: param,
success: function(data) {
test data .... if OK submit.
}
In testfile.php you test for the file and echo out the data
if($_GET['action'] == 'testfile'){
$msg = '';
$basedirpath = $_GET['dirpath'] . "/";
if(file_exists($basedirpath . $_GET['file'])) {
$msg = 'exists';
}
echo $msg;
}
$msg is returned in the data in the ajax call.
i am little bit problem in Image upload in a database directory.image upload my avatar folder and can't show my page becouse problem is that in database id, username table show my data but imagelocation table can't show my directory.please any one told me that, what is the problem in my code and correct it specify line
upload.php
<?php
include("connecton.php");
$_SESSION['username']="kyle";
$username = $_SESSION['username'];
if($_POST['submit'])
{
//get file attribute
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if($name)
{
//start upload process
$location = "avatars/$name";
move_uploaded_file($tmp_name,$location);
$query = mysql_query("UPDATE users SET imagelocation='$location' WHERE username='$username'");
die("Your avatar has been uploaded! <a href='view.php'>HOme</a>");
}
else
die("Please select a file");
}
echo "Welcome, ".$username."!<p>";
echo "Upload Your Image:
<form action='upload.php' method='POST' enctype='multipart/form-data'>
File: <input type='file' name='myfile'> <input type='submit' name='submit' value='upload!'>
</form>
";
?>
view.php
<?php
include("connecton.php");
$username = $_SESSION['username'];
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($query)==0)
die ("User not found");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
echo "<img src='$location' width='100' height='100'>";
}
?>
a) You do not check if the upload succeeded. At least do something like:
if ($_FILES['myfile']['error'] === UPLOAD_ERR_OK) {
... upload went ok
}
b) You're using the original user's filename to store it on your server, and you do not sanitize the filename. THere is NOTHING to prevent a malicious user from setting a filename such as ../../../../../../../../../some/critical/system/file, which your script will then happily overwrite.
c) You do not check of the move_uploaded_file() succeeded:
if (!move_uploaded_file(...)) {
die("Move failed!")
}
d) You do not check if the database query succeeded:
$stmt = mysql_query(...)
if ($stmt === FALSE) {
die("MySQL query failed: " . mysql_error());
}
e) You've not sanitized the $filename, so again a malicious user can subvert your query and directly attack your database with SQL injection attacks.
f) You're doing a SELECT * FROM... to get the image's location. Are you sure your table contains an 'imagelocation' row? YOU didn't check if the insert query succeeded using the same row, so maybe you've got a typo and it's really "imglocation" instead.
First php statement of both of upload.php and view.php should be this:
session_start();