I am trying to use a PHP file to upload files from an Android app to a web server.
This the PHP file:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = 'usuarios/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://'.$server_ip.'/danyra/administrar/application/admin/'.$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'];
//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
line 45 --> move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
$sql = "INSERT INTO `images` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['url'] = $file_url;
$response['name'] = $name;
}
//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(id) as id FROM images";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['id']==null)
return 1;
else
return ++$result['id'];
}
This file is taken from a tutorial.
This is the scenario:
The PHP file is at:
http://myserver.com/danyra/android_login_api/upload.php
The folder where I want to store the uploaded images is at:
http://myserver.com/danyra/administrar/application/admin/usuarios
I am using POSTMAN to check the script, and I am always receiving this error:
Warning: move_uploaded_file(usuarios/18.png): failed to open stream: No such file or directory in /home2/kokls/public_html/myserver.com/danyra/android_login_api/upload.php on line 45
Warning: move_uploaded_file(): Unable to move '/tmp/phpMciKUa' to 'usuarios/18.png' in /home2/kokls/public_html/myserver.com/danyra/android_login_api/upload.php on line 45
{"error":false,"url":"http:\/\/XXX.XXX.246.130\/danyra\/administrar\/application\/admin\/usuarios\/18.png","name":"fsd"}
I have tried a lot of options changing paths, but with no success.
Any help is welcome.
I think your current path is incorrect. You should be using a relative path.
Try this path
$upload_path = $_SERVER['DOCUMENT_ROOT'].'/danyra/administrar/application/admin/usuarios/';
Related
I am coding a site that users can upload images to view in a carousel and i made it to uploading a file
but i can't open it so first i thought the file was corrupt but when i open the properties i found out that the file was not corrupt by his Size so i used :-
chmod($path, octdec(0755));
but the file still not opening
the hole code :-
<?
$account = 'account';
$price = '10.5';
require_once 'Config.php';
$dbCon = "mysql:host=$host;dbname=$db_name";
$conn = new PDO($dbCon, $username, $password);
$msg ='';
$name = $_POST['name'];
echo $name;
if(isset($_POST['upload'])){
$image = $_FILES['image']['name'];
$path = 'upload/' .$image;
$query = $conn->prepare("INSERT INTO special (imageurl) VALUES ('$path')");
$query->execute();
if($query){
move_uploaded_file($_FILES['image']['tmp_name'],$path);
chmod($path, octdec(0755));
echo $path;
$msg = "Done";
}else{
$msg = "Error Some thing went Wrong!";
}
}
?>
BTW : i'm using Appserv 8.6.0 running on PHP 5.6.30
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'm trying to upload an image using PHP to MySQL. In the query i'm trying to save the image and the directory of the image in the DB, but I get empty directory in the DB, plus no image in the folder. Any help would be greatly appreciated!
<?php
// include db connect class
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/android_connect/db_connect.php');
$db = new DB_CONNECT();
//Setting up images directory
$target = "./images";
$target = $target . basename( $_FILES['photo']['name']);
$photo=($_FILES['photo']['name']);
//inserting data order
$order = "INSERT INTO scb
(photo, directory)
VALUES
( '$_POST[$target]',
'({$_FILES['photo']['name']})')";
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 an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo "Thank you for submitting!";
} else{
echo "Sorry, something went wrong! Please try again!";
}
?>
Well first mysql_query is outdated use PDO instead (you'll have to check if this feature is enabled on your server by using phpinfo());
Try this
<?php
//Connect to sql db
try {
$user = "username";
$pass = "password";
$db = new PDO('mysql:host=yourhost;dbname=yourdb', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//Setting up images directory
$target = "./images/"; //you forgot the last slash
$target = $target . basename($_FILES['photo']['name']);
$photo = $_FILES['photo']['name'];
//inserting data order
$stmt = $db->prepare("INSERT INTO scb (photo, directory) VALUES (:photo, :directory)");
$stmt->bindParam(':photo', $_POST[$target]);
$stmt->bindParam(':directory', $_FILES['photo']['name']);
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 an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//declare in the order variable
if($stmt->execute()){
echo "Thank you for submitting!";
} else{
echo "Sorry, something went wrong! Please try again!";
}
?>
Have you checked for any errors or warnings in the web server log files? Do you get any sensible output if you write:
print_r($_FILES);
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.