PHP uploading video, goes to database but not to folder [duplicate] - php

This question already has answers here:
PHP - Failed to open stream : No such file or directory
(10 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I am using Heroku for creating my website, as part of it, there is the ability to upload videos to the site. I have got it sort of working but I am struggling to get one last part working. As I have understood for uploading videos, the name of the file is uploaded to the database whilst the actual video itself is uploaded to a folder defined by myself. I have got it working so the video name is uploaded to the database but the video is not saving to the video folder I have created.
This is the code I have:
<?php
session_start();
require_once('../../includes/config.php');
require('../../vendor/autoload.php');
if(!isset($_SESSION['loggedin'])){ //if login in session is not set
header("Location: ../../index.php");
}
if($_SESSION['role'] !="admin") {
header("Location: ../../index.php");
}
if(isset($_POST["submit"])) {
//collect form data
extract($_POST);
$allowedExts = array("ogg", "mp4", "wma");
$extension = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
if ((($_FILES["video"]["type"] == "video/mp4")
|| ($_FILES["video"]["type"] == "video/ogg")
|| ($_FILES["video"]["type"] == "video/wma")
&& ($_FILES["video"]["size"] < 16000000 )
&& in_array($extension, $allowedExts))){
if ($_FILES["video"]["error"] > 0)
{
echo "Return Code: " . $_FILES["video"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["video"]["name"] . "<br />";
echo "Type: " . $_FILES["video"]["type"] . "<br />";
echo "Size: " . ($_FILES["video"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["video"]["tmp_name"] . "<br />";
$upload = $_FILES["video"]["name"];
if (file_exists("../videos/" . $_FILES["video"]["name"]))
{
echo $_FILES["video"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["video"]["tmp_name"],
"../videos/" . $_FILES["video"]["name"]);
echo "Stored in: " . "../videos/" . $_FILES["video"]["name"];
}
}
}else{
echo "Invalid file";
}
try {
//insert into database
$stmt = $dbconn->prepare('INSERT INTO videos (videotitle,video,editedBy,duration) VALUES (:videoTitle, :video, :editedBy, :duration)') ;
$stmt->execute(array(
':videoTitle' => $videoTitle,
':video' => $upload,
':editedBy' => "admin",
':duration' => "12"
));
//redirect to videos page
header('Location: index.php');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
I have looked at the heroku logs and the errors I am getting are:
PHP Warning: move_uploaded_file(../videos/VID_20201129_223935.mp4): failed to open stream: No such file or directory in /app/users/admin/videoUpload.php on line 53
PHP Warning: move_uploaded_file(): Unable to move '/tmp/phpoLjPU4' to '../videos/VID_20201129_223935.mp4' in /app/users/admin/videoUpload.php on line 53
This is to do with the lines:
// this is line 53
move_uploaded_file($_FILES["video"]["tmp_name"],
"../videos/" . $_FILES["video"]["name"]);
I am not sure what would cause this error, is there something I am missing or could it be to do with how I have heroku set up?
As a side note, I have become aware that using extract is not the most secure way to get form data and I am looking to change this.
Thanks
Edit -
This is the form where the information is gathered
<form action='videoUpload.php' method='post' enctype="multipart/form-data">
<h2>Add Video</h2>
<p><label>Title</label><br />
<input type='text' name='videoTitle' required value='<?php if(isset($error)){ echo $_POST['videoTitle'];}?>'></p>
<p><label>Video</label><br />
<input type="file" name='video' id="video" required value='<?php if(isset($error)){ echo $_POST['video'];}?>'></p>
<p><input type='submit' name='submit' value='Submit'></p>
</form>

In view of the comments I made regarding using the full path I put the following together with the hope that it might help solve your problem ~ though it is untested.
Any fields from the form that submits to this script that is used in the extract method should really be validated and sanitised ( though the prepared statement will help protect the db anyway ) - so by declaring these fields with a suitable filter you can call filter_input or filter_input_array to assist that protection. I usually run checks on the POST array before filtering so that I can deduce if I have omitted fields or have extra - you'll see what I mean below.
In terms of processing the upload if the target folder is not found you need to know about it and act accordingly before trying to save the file or write to the db ( pointless logging an upload that failed perhaps ). chdir returns true if it succeeds in navigating to the target directory so you can fork the logic at that stage to either bailout or create the folder structure ( using mkdir )
<?php
error_reporting( E_ALL | E_STRICT );
session_start();
$errors=array();
$createpath=true;
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
$kb=1024;
$mb=pow( $kb,2 );
$maxfs=$mb * 15; # 15728640 ~ 15Mb
if( !isset( $_SESSION['loggedin'], $_SESSION['role'] ) or $_SESSION['role'] !== 'admin' ) {
exit( header( 'Location: ../../index.php' ) );
}
if( isset( $_POST['submit'], $_FILES['video'] ) ) {
require_once('../../includes/config.php');
require_once('../../vendor/autoload.php');
/*
To use `extract` in a more secure manner
*/
# create filter rules for form fields with their expected data type
$args=array(
'submit' => FILTER_SANITIZE_STRING,
'videoTitle' => array(
'filter' => FILTER_SANITIZE_STRING,
'flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH
)
);
# if there are fields that MUST be submitted
foreach( array_keys( $args ) as $field ){
if( !isset( $_POST[ $field ] ) or empty( $_POST[ $field ] ) ) $errors[]=sprintf('The field "%s" does not appear in the POST array',$field);
}
# check that no additional POST variables are present
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) ) $errors[]=sprintf('Unknown parameter supplied "%s"',$field);
}
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$name=$_FILES['video']['name'];
$type=$_FILES['video']['type'];
$size=$_FILES['video']['size'];
$error=$_FILES['video']['error'];
$tmp=$_FILES['video']['tmp_name'];
function uploaderror( $error ){
switch( $error ) {
case UPLOAD_ERR_INI_SIZE: return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE: return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL: return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE: return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR: return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE: return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION: return 'File upload stopped by extension';
default: return 'Unknown error';
}
}
$allowedExts = array('ogg', 'mp4', 'wma');
$types=array('video/mp4','video/ogg','video/wma');
$extension = pathinfo( $name, PATHINFO_EXTENSION );
if( in_array( $type, $types ) && in_array( $extension, $allowedExts ) && $size <= $maxfs ) {
if( $error !==UPLOAD_ERR_OK ) {
$errors[]=sprintf('Error uploading file: %s',uploaderror( $error ));
} else {
# get the full path to current working directory
$cwd=getcwd();
# attempt to traverse directory structure to desired location - up one level and find folder
$status=chdir('../videos/');
# If the directory does not exist...
if( !$status ) {
chdir('../');
$targetpath=sprintf( '%s/videos/', getcwd() );
# Attempt to create THIS path or exit???
if( $createpath ){
mkdir( $targetpath, 0777, true );
chdir( $targetpath );
} else exit( sprintf( '<h1>Fatal Error: Target Directory "%s" does not exist!</h1>', $targetpath ) );
}
# get the fully qualified path of the target directory
$target=getcwd();
# create the full filepath for uploaded file
$targetfile=sprintf('%s/%s',$target,$name);
# save the file
if( !file_exists( $targetfile ) ){
$status=move_uploaded_file( $tmp, $targetfile );
if( !$status )$errors[]=sprintf( 'Failed to move file to target directory: %s', $target );
}else{
$errors[]=sprintf('The file "%s" already exists!',$name);
}
}
if( empty( $dbconn ) )$errors[]='No database connection available';
if( empty( $errors ) ){
$sql='INSERT INTO `videos` ( `videotitle`, `video`, `editedBy`, `duration` ) VALUES ( :videoTitle, :video, :editedBy, :duration )';
try{
$stmt=$dbconn->prepare( $sql );
$args=array(
':videoTitle' => $videoTitle,
':video' => $name,
':editedBy' => 'admin',
':duration' => 12
);
$result=$stmt->execute( $args );
if( !$result ) $errors[]='Failed to add record';
# redirect if everything went OK
if( empty( $errors ) )exit( header( 'Location: index.php' ) );
}catch( PDOException $e ){
$errors[]=$e->getMessage();
}
}else{
$errors[]='Unwilling to commit to db due to previous errors';
}
}else{
$errors[]='File failed testing - incorrect type or too large';
}
}else{
$errors[]='Critical error';
}
# if there were errors, let the user know
foreach( $errors as $error )printf( '<div>%s</div>', $error );
}catch( Exception $e ){
exit( 'Bad foo: '.$e->getCode() );
}
}
# if page accessed by GET or similar....
http_response_code(404);
?>

Related

Wordpress file upload

I have this plugin im making and in the file upload system i have this:
$mimes = array('image/jpeg','image/jpg','image/gif','image/png','application/pdf');
if(in_array($_FILES['attach']['type'], $mimes)){
$error = 0;
}
else {
$error = 1;
}
Then, along with other error checking i have this to upload the files to a custom folder
if($error == 0) {
$folder = PLUGIN_DIR . '/uploads/';
if(is_dir($folder)) {
$file = $_FILES["attach"]["tmp_name"];
move_uploaded_file($file, $folder.date('Ymd').'_'.$name);
}
}
This works perfectly. I've tested it but, is it ok to do like this? Or is there a better way to do it?
Thanks in advance!
I think better use this codex.wordpress.org
<?php
// We will check the protection of nonce and that the user can edit this post.
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// all OK! We continue.
// These files must be connected to the front end (front end).
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress catch the download.
// Do not forget to specify the attribute name field input - 'my_image_upload'
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
echo "Error loading media file.";
} else {
echo "The media file has been successfully uploaded!";
}
} else {
echo "Verification failed. Unable to load file.";
}
?>
check whether free space availability. I had the same issue I have checked every thing and done more but the issue was with my file storage

wordpress upload file error

I have this upload file system in wordpress and everything is working fine but the file wont go into the folder. Here's what i have right now:
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
// Change your upload directory
function my_upload_dir(){
return PLUGIN_DIR . '/uploads/';
}
// Register our path override.
add_filter( 'upload_dir', 'my_upload_dir' );
// Set where to get the file from
$uploadedfile = $_FILES["attach"];
$upload_overrides = array( 'test_form' => false );
// Do the file move
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
// Set everything back to normal.
remove_filter( 'upload_dir', 'my_upload_dir' );
// Return an error if it couldn't be done
if (!$movefile || isset( $movefile['error'])) {
echo $movefile['error'];
}
its seems to be working fine (no errors) but the image wont show in the folder.
any help would be appreciated.
I think This code is working Fine.
$date=strtotime(date('Y-m-d H:i:s'));
$pro_image_name = $date.$_FILES['your Input type File Name']['name'];
$allowed = array('gif','png','jpg');
$ext = pathinfo($pro_image_name, PATHINFO_EXTENSION);
$root_path = get_template_directory();
if(!in_array($ext,$allowed) ) { ?>
<span style="font-size:22px; color:red;">Uploaded File Not Supported</span>
<?php } else {
move_uploaded_file($_FILES['updateimg']['tmp_name'],$root_path."/images/".$pro_image_name);
$image_get_path = site_url()."/wp-content/themes/prathak/images/".$pro_image_name;
update_user_meta(get_current_user_id() , 'userpic' , $image_get_path );
}
Good Luck

Uploading Image to Parse(Back4App) in PHP

Hello everyone I'm trying to upload an image to parse with PHP. i was able to add the object all the columns works perfectly except the Image Column stays undefined i checked the php.ini (url_fopen:On ;) and the utf-8 charset and many other solutions i thins its a problem of security or Privilege !! Please if you have any useful Ideas share it and Thanks in Advance !!!
Here is my code
<?php
require_once( 'autoload.php' );
// Add the "use" declarations where you'll be using the classes
use Parse\ParseObject;
use Parse\ParseUser;
use Parse\ParseException;
use Parse\ParseFile;
use Parse\ParseCloud;
use Parse\ParseClient;
use Parse\ParseQuery;
try {
$app_id = "xxxxxxxxxxxxxxxxxxxxxx" ;
$rest_key = "xxxxxxxxxxxxxxxxxxxxxx";
$master_key = "xxxxxxxxxxxxxxxxxxxxxx";
ParseClient::initialize( $app_id, $rest_key, $master_key );
ParseClient::setServerURL('https://parseapi.back4app.com', '/');
if(isset($_GET['libelle']) && (isset($_GET['prix']) ) ){
$libelle = $_GET['libelle'];
$prix = $_GET['prix'];
}
if ( isset( $_FILES['image'] ) ) {
$isFileExists = file_exists ($_FILES['image']['tmp_name'] );
$isGoodSize = ($_FILES['image']['size'] < 600000) && ($_FILES['image']['size'] > 0);
if ( $isFileExists && $isGoodSize) {
// save file to Parse
$file = ParseFile::createFromData( file_get_contents( $_FILES['image']['tmp_name'] ), $_FILES['image']['name'] );
$file->save();
//echo 'File URL: ' . $file->getURL() . '';
} else {
echo "Erreur";
}
}
$Prod = ParseObject::create("Produit");
//$Prod = new ParseObject("Produit");
$Prod->set("libelle",$libelle);
$Prod->set("prix",(float)$prix);
if ( isset( $file ) ) {
$Prod->set("image",$file);
}
try {
$Prod->save();
echo 'Object Saved with ID: <strong>' . $Prod->getObjectId() . '</strong>.<br/>';
} catch (ParseException $ex) {
echo 'Failed to create new object, with error message: ' . $ex->getMessage();
}
} catch (ParseException $ex) {
echo $ex->getMessage();
}
?>
I was checking here more about files! Just for help you, the maximum file size is 20MB. You can test with different file sizes.
At releases page on GitHub from Parse PHP SDK, you can check the version 1.2.8 that fixed a error with ParseFiles.

Passing a folder name through a url as a parameter to invoke a php function

I am trying to list the contents of a directory by passing a folder name as a URL parameter to invoke a php function. I followed some other examples provided on stackoverflow and have been able to get the php function invoked and am certain I am reaching the code inside because of the echo statements that are output.
The url seems to be encoded correctly because when I display the path info inside the php function all the paths check out.
www.mysite.com/php/genListing.php?function=genListing&folder=wp-content/uploads/myfiles
The check on is_readable() appears to be failing. I have checked the file permissions for that directory and all users have read access. Anybody have any idea of what the problem might be?
genListing.php
if ( ! empty( $_GET['function'] ) && function_exists( $_GET['function'] ) ) {
if ( $_GET['function'] == 'genListing')
{
$atts = $_POST;
genListing( $atts );
}
}
function genListing( $atts ) {
$folder = $_GET[ 'folder' ];
if ( ! empty( $_GET['title'] ) ) {
$title = $_GET['title'];
}
else
{
$title = 'Directory Listing';
}
echo "<p>Made it inside genListing(): " . $folder . "</p>";
$fullFolderPath = trailingslashit( WP_INSTANCE_HOME ) . $folder;
echo "<p> Trying: " . $fullFolderPath . "</p>";
// bad folder check
if ( empty( $folder ) || ! is_readable( $fullFolderPath ) ) {
echo "<p>The folder selected was not valid.</p>";
return 'The folder selected was not valid.';
}

PHP file neither moved nor unmoved

I can't seem to figure out why this is happening. When I run the following code:
$uref = APACHE_ROOT . UPLOAD_PATH . $applicant . "_ref_{$email}_{$year}";
if ( !move_uploaded_file( $_FILES['file']['tmp_name'], $uref ) ) {
echo "Move failed";
} elseif ( move_uploaded_file( $_FILES['ref']['tmp_name'], $uref) ) {
echo "Move succeeded";
}
Neither statement gets returned. Both paths exist; one file was successfully uploaded and this started happening after only the second upload attempt.
Any ideas why?
Thanks for any suggestions.
if ( !move_uploaded_file( $_FILES['file']['tmp_name'], $uref ) ) {
echo "Move failed";
} elseif ( move_uploaded_file( $_FILES['ref']['tmp_name'], $uref) ) {
echo "Move succeeded";
}
If your first call returns true, because the file is moved, then the second will return false, because the file is no longer there.
You're much better off just having a simple if / else - the first call can be either true or false, so you don't need to re-check.
First, is $uref = APACHE_ROOT . UPLOAD_PATH . $applicant . "_ref_{$email}_{$year}"; a directory?
If it is, then you are trying to write to a directory, which is probably going to fail if the directory already exists.
Also, only check the running once.
The first time, move_file_uploaded will be executed to check if it is negative. It's obviously true, so it goes to the second to check if it's true, and it's returning false.
Do this instead:
$uref = APACHE_ROOT . UPLOAD_PATH . $applicant . "_ref_{$email}_{$year}";
if(move_uploaded_file( $_FILES['file']['tmp_name'], $uref )){
echo "Move succeeded";
} else {
echo "Move failed";
}

Categories