The following is my php script for you to upload video files (max 100MB) to my server.
Problem is, it uploads one mp4 file without any problems. But when I try uploading others it gives these errors.
When I try uploading "T.J. Hooker (1982) - Season 1 OPENING.mp4" which is 2.57MB, I get this error:
array(1) { ["id_verification_video_file"]=> array(5) { ["name"]=>
string(41) "T.J. Hooker (1982) - Season 1 OPENING.mp4" ["type"]=>
string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(1) ["size"]=>
int(0) } } Array ( [id_verification_video_file] => Array ( [name] => T.J.
Hooker (1982) - Season 1 OPENING.mp4 [type] => [tmp_name] => [error] => 1
[size] => 0 ) )
Q1. What does this error mean ?
When I try uploading another file "Taekwondo vs Jeet Kune Do.mp4" which is 9.32MB, I get the following error:
"array(0) { } Upload your video file".
Q2. Why am I getting line 17 triggered when I am trying to upload a video (mp4) file ?
Line 17:
if(!isset($_FILES["id_verification_video_file"]))
{
echo "Upload your video file";
exit;
}
Full Script:
<?php
$conn = mysqli_connect("localhost","livefoll_user","livefollow_2019*","livefoll_live
follow");
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
var_dump($_FILES);
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]))
{
echo "Upload your video file";
exit;
}
elseif (!$_FILES["id_verification_video_file"]["error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"] ["ERROR"]; print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
$user = 'livefoll_user';
//Feed Id Verification Video File Upload Directory path.
$directory_path = 'uploads/videos/id_verifications/';
//Make Directory under $user in 'uploads/videos/id_verifications' Folder.
$directory_path_and_user_dir = "uploads/videos/id_verifications/$user";
if(!is_dir($directory_path_and_user_dir))
{
$user = 'livefoll_user';
$mode = 0755;
mkdir($directory_path_and_user_dir,$mode, TRUE);
}
//Grab Uploading File details.
$Errors = Array(); //
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$directory_path_and_user_dir_and_user_file = "$directory_path_and_user_dir/$file_name";
if(file_exists($directory_path_and_user_dir_and_user_file)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE ALREADY EXISTS. INSTEAD SHOWING A BLANK WHITE PAGE. -> I changed it with 'echo'. It was not giving error because you were just storing the error into the Errors array without throwing the error.
{
echo "Error: You have already uploaded a video file to verify your ID! No need to upload and do it again!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("mp4" => "video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*100; //Allowed limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*100; //Allowed limit: 100MB.
$max_file_size_allowed_in_megabytes = 100; //Allowed limit: 100MB.
$max_file_size_allowed = "$max_file_size_allowed_in_bytes";
//Verify File Extension.
if(!array_key_exists($file_extension, $allowed_file_extensions))
{
echo "Error: Select a valid video file format. Select an Mp4, Wav, etc. files.";
exit();
}
//Verify MIME Type of the File.
elseif(!in_array($file_type, $allowed_file_extensions))
{
$Errors[] = "Error: There was a problem uploading your file $file_name! Make sure your file is a video file. You may try again."; //IS THIS LINE CORRECT ? -> yes but won't print if you don't use throwerror or echo ... echo "error: there was a problem... etc..."
exit();
}
//Verify File Size. Allowed Max Limit: 100MB.
elseif($file_size>$max_file_size_allowed)
{
$Errors[] = "Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes.";
exit();
}
$move_to = $directory_path_and_user_dir."/".$file_name;
//Move uploaded File to newly created directory on the server.
if(!move_uploaded_file($file_tmp, $move_to))
{
//user = 'livefoll_user'; //Not necessary
$mode = 0755; //Not necessary
//Notify user their Id Verification Video File uploading failed.
echo "Your Video File \"$file_name\" has failed to be uploaded! You may try some other time.";
exit();
}
else
{
//Notify user their Id Verification Video File was uploaded successfully.
die("Your Video File \"$file_name\" has been uploaded successfully!");
}
}
}
}
?>
<?php //SWITCH FOLLOWING UPLOADING WEB FORM TO HTML5 DESIGN WITH CAPTCHA
AND HIDDEN FIELD/S. FOIL BOTS FROM UPLOADING FILES. MUST BE SQL INJECTION
AND HACKING PROOF.?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification
Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
Q4. How to solve these issues ? I mean, if the script code is not buggy and manages to upload one mp4 file then it should be able to upload other mp4 files too without showing errors.
Problem solved. The .ini file was restricting the file size.
Related
How do I save a remote file to local storage in Typo3 v10.
Having the following code, no files are getting saved in fileadmin storage
private function saveFileFromUri($fileUrl)
{
$urlParts = parse_url($fileUrl);
$pathParts = pathinfo($urlParts['path']);
$fileName = $pathParts['basename'];
$file = GeneralUtility::getUrl($fileUrl);
$temporaryFile = GeneralUtility::tempnam('temp/' . $fileName);
$storage = $this->defaultStorage->createFolder($pathParts['dirname']);
if ($file === false) {
$error = sprintf(
'File %s could not be fetched.',
$fileUrl
);
if (isset($report['message'])) {
$error .= ' ' . sprintf(
'Reason: %s (code: %s)',
$report['message'],
$report['error'] ?? 0
);
}
throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
$error,
1613555057
);
}
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($file);
GeneralUtility::writeFileToTypo3tempDir(
$temporaryFile,
$file
);
$fileObject = $storage->addFile(
$temporaryFile,
$storage,
$fileName
);
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($fileObject);
}
What is the right way to save remote files in typo3 and create a fileObject?
TYPO3 has an API to get or add files via the File Abstraction Layer (FAL).
This example adds a new file in the root folder of the default storage:
$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
$storage = $storageRepository->getDefaultStorage();
$newFile = $storage->addFile(
'/tmp/temporary_file_name.ext',
$storage->getRootLevelFolder(),
'final_file_name.ext'
);
Please refer to the documentation for details.
I want to upload only jpg, jpeg and png type images. That's why I want to check extension of uploading images. All files which extension is updated like .exe file is updated as .jpg or .png file then it allow to upload but I want to prevent it and upload only original images.
How can I do it in Cakephp 3
My Controller is
if(h($this->request->data['image']['name']) != '')
{
$ext = substr(strtolower(strrchr($this->request->data['image']['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
if (in_array($ext, $arr_ext))
{
$extension = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
if($extension=='jpg' || $extension=='jpeg' || $extension=='png')
{
if ($this->request->data['image']['size'] < '26214400')
{
$randno = rand(0,100);
$filenameArr = explode('.' , h($this->request->data['image']['name']));
$namefile = $filenameArr[0].$randno;
$extfile = $filenameArr[1];
$filename = WWW_ROOT .'uploads/users/'.$namefile.'.'.$extfile;
move_uploaded_file($this->request->data['image']['tmp_name'], $filename);
$upload = $namefile.'.'.$extfile;
$newData['image'] = $upload;
}
}
else
{
$this->Flash->error(__('Please upload only jpg or jpeg or png type image '));
return $this->redirect(['action' => 'edit', $id]);
}
}
else
{
$this->Flash->error(__('Please only upload images (jpeg, png, jpg).'));
return $this->redirect(['action' => 'edit', $id]);
}
}
But It's only executing else condition even when i put correct extension.
trying to download a csv file, during downloading the page is opened in new tab and showing the error as FileNotFoundException in File.php line 37: The file "72" does not exist. Ccan anyone please help me?
Laravel controller:
public function fileExport(Request $request, Response $response)
{
$employee = Employee::all()->toArray();
$fileName = 'Employee.csv';
$headers = array(header('Content-Type: application/csv', 'Content-Disposition: attachment; filename="'.$fileName.'"'));
$f = fopen('php://output', 'w');
foreach ($employee as $line)
{
$data = fputcsv($f, $line);
}
return response()->download($data,$headers);
}
Laravel router:
Route::get('fileExport', 'EmployeeController#fileExport');
Angularjs controller:
$scope.exportFile = function(){
$window.open(rootUrl+'fileExport');
}
<button class="btn btn-default btn-xs btn-detail" ng-click="exportFile()">Export</button>
Exception shows that file is not found and might not be generated.
First of all check file exists and paths are correct?
And if file does not exists then make it simple as below and create the file correctly on desired path and then you can move on:
$f = fopen($fileName, 'w');
When I use the code below to download a file it works fine in IE, Firefox, but with Chrome you can see that the layout and view is sent back to the browser in the console.The status is set to cancel and the entire line is highlighted in red. The file is downloaded OK.
After the exit; there are various header opions I have tried, but to no avail
if ($request->isPost()) {
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
$file_fullpath = "C:/eclipse-php/workspace/Dartfire/uploads/data/logo.jpg";
$mtype = '';
// magic_mime module installed?
if (function_exists('mime_content_type')) {
$mtype = mime_content_type($file_fullpath);
}
// fileinfo module installed?
else if (function_exists('finfo_file')) {
$finfo = finfo_open(FILEINFO_MIME); // return mime type
$mtype = finfo_file($finfo, $file_fullpath);
finfo_close($finfo);
}
$size = filesize($file_fullpath);
header('Content-Type: image/jpg');
header('Content-Disposition: attachment; filename="logo.jpg"');
readfile($file_fullpath);
exit;
//header("Content-type: application/octet-stream");
/*
$this->getResponse()
->setHeader('Content-Description', 'File Transfer', true)
->setHeader('Content-Type', $mtype, true) // change to application/pdf
->setHeader('Content-Disposition', "attachment; filename={$document->getFilename()}", true)
->setHeader('Content-length', $size, true)
->setHeader('Content-Transfer-Encoding', 'binary', true)
->setHeader("Content-type", "application/octet-stream")
->setHeader('Cache-control', 'private')
->appendBody(readfile($file_fullpath));
//->sendHeaders();
//$this->getResponse()->sendResponse();
//Zend_Wildfire_Channel_HttpHeaders::getInstance()->flush();
}
You'd have to place any header() calls before any output is sent to the browser. So, in your case this would need to be done before the readline() call.
when uploading an image to the server using cakephp
$this->Model->Behaviors->attach('ImageUpload', Configure::read('photo.files'));
photo uploaded successfully, and the database fields also
but shows following error instead of returning to index page.
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 104]
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 107]
Warning (2): Cannot modify header information - headers already sent by (output started at E:\umoorthy_105act10\projects\dev1base\core\cake\basics.php:111) [CORE\cake\libs\controller\controller.php, line 614]
wat to do?
Cake has already wrote where to look for a problem
Configure::read('photo.files')
do following to check if everything is ok
pr(Configure::read('photo.files'))
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative echo "<pre>"; print_r($formdata); exit;
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}