There are many PHP solutions and WP plugins, they all come with additional options that I don't want/need, i.e. how the converted files are served, where they are stored, etc.
I need none of all that and am after pure simple code using GD. I don't want to use a plugin, thank you.
When should the encode happen ? At any time you know it is a good point in the hook routine, could be this https://make.wordpress.org/core/2019/11/05/use-of-the-wp_update_attachment_metadata-filter-as-upload-is-complete-hook/ but if you know better or have another solution then use that and possibly let me know why you choose another hook. I would i.e. also be happy with firing a cron job once new images are uploaded if that is better. Also I don't need to have metadata of the converted images in the WP db, fine with having the original .jpeg files and their metadata in the Media Library, the .webp files are just there to be used inside the picture element.
Where should the converted files be stored? wp-content/uploads/ default folder structure, .webp files should be next to .jpeg files all in there.
GD image engine should be used for the conversion. https://developer.wordpress.org/reference/classes/wp_image_editor_gd/ Lately I find imagick just crashes or takes ages to do anything. In WP 5.2 things still worked just fine with imagick but there must have been changes introduced that make using imagick in later versions of WP useless. I find GD to me quite stable and fast, it does not matter it creates lossy WebP versions. The methods for the GD image engine from WP do not seem to include conversion/encoding https://developer.wordpress.org/reference/classes/wp_image_editor_gd/#methods so I am also happy with any methods using in the GD module https://www.php.net/manual/en/book.image.php concerning encoding to WebP.
To get rid of all the extra unneeded image sizes and options WP introduced over time I have these functions/filters in functions.php.
function namespace_disable_image_sizes($sizes)
{
unset($sizes['thumbnail']); // disable thumbnail size
unset($sizes['medium']); // disable medium size
unset($sizes['large']); // disable large size
unset($sizes['medium_large']); // disable medium-large size
unset($sizes['1536x1536']); // disable 2x medium-large size
unset($sizes['2048x2048']); // disable 2x large size
return $sizes;
}
add_action('intermediate_image_sizes_advanced', 'namespace_disable_image_sizes');
// disable scaled image size
add_filter('big_image_size_threshold', '__return_false');
// disable rotated image size
add_filter('wp_image_maybe_exif_rotate', '__return_false');
// disable other image sizes
function namespace_disable_other_image_sizes()
{
remove_image_size('post-thumbnail'); // disable images added via set_post_thumbnail_size()
remove_image_size('another-size'); // disable any other added image sizes
}
add_action('init', 'namespace_disable_other_image_sizes');
High resolution and large dimension images are to be converted, see attached image as example, image types can be jpeg, png, etc.
The sizes in place are more or less these with possible variations.
add_image_size('4096w', 4096, 0);
add_image_size('3200w', 3200, 0);
add_image_size('2560w', 2560, 0);
add_image_size('1920w', 1920, 0);
add_image_size('1600w', 1600, 0);
add_image_size('1280w', 1280, 0);
add_image_size('1140w', 1140, 0);
add_image_size('1024w', 1024, 0);
add_image_size('960w', 960, 0);
add_image_size('800w', 800, 0);
add_image_size('768w', 768, 0);
add_image_size('640w', 640, 0);
add_image_size('425w', 425, 0);
add_image_size('320w', 320, 0);
add_image_size('240w', 240, 0);
I use the picture element with more or less the following setup, so I have the browser decide what is needed and hence don't want/need server side .htaccess rules or backend configs. https://dev.opera.com/articles/responsive-images/
<picture>
<source
sizes="(min-width: 640px) 60vw, 100vw"
srcset="opera-200.webp 200w,
opera-400.webp 400w,
opera-800.webp 800w,
opera-1200.webp 1200w,
opera-1600.webp 1600w,
opera-2000.webp 2000w"
type="image/webp">
<img
src="opera-400.jpg" alt="The Oslo Opera House"
sizes="(min-width: 640px) 60vw, 100vw"
srcset="opera-200.jpg 200w,
opera-400.jpg 400w,
opera-800.jpg 800w,
opera-1200.jpg 1200w,
opera-1600.jpg 1600w,
opera-2000.jpg 2000w">
</picture>
What have I tried?
a) https://wordpress.stackexchange.com/questions/256351/hook-after-image-is-uploaded-and-image-sizes-generated/256352
b) https://wordpress.stackexchange.com/questions/38582/hook-to-get-image-filename-when-it-is-uploaded
c) WordPress - Blur Image on Upload
d) Convert Images into WebP
e) I have read through and understood https://kinsta.com/blog/wordpress-hooks/#filters-example-2-insert-content-after-a-post - however what I am missing is a way to see/know what data I am working with, i.e.
add_filter('wp_generate_attachment_metadata', 'gd_webp_encode', 10, 3);
function gd_webp_encode($metadata, $attachment_id, $context){
ob_start();
echo $attachment_id;
echo $metadata;
ob_end_clean();
return $metadata;
}
will show me nothing, same with trying to log to console or to a file in the plugin folder. Without knowing/seeing the data and what variable names hold what data I am just doing trial and error and guessing, no coding. So given above code, how would it first of all be possible to see/know what variables hold what data at that point in time and make that readable somewhere, i.e. in a log file in the plugin folder?
Bottom line, given above setup, help me understand what variables hold what data i.e. after upload in a hook and include code where I can make a WebP version of all the sizes and the original created using the GD image engine.
Both plugins work well (create webp images in uploads directory), but I am wondering how to call the webp images with wp functions (get_the_post_thumbnail_url or wp_get_attachment_url).
In media, you cannot see webp images, so you cannot select them.
To know what data you work with inside a filter or action and to see what variable names hold what values a helper function like below can be used.
function debug( $info ) {
$message = null;
if ( is_string( $info ) || is_int( $info ) || is_float( $info ) ) {
$message = $info;
} else {
$message = var_export( $info, true );
}
if ( $fh = fopen( ABSPATH . '/gdwebpconvert.log', 'a' ) ) {
fputs( $fh, date( 'Y-m-d H:i:s' ) . " $message\n" );
fclose( $fh );
}
}
This will create a gdwebpconvert.log file in the root directory of your WordPress installation and any string, integer, float or array you put into debug($value_xyz); will be logged to that file with a date and time. On Linux you can then just go to the directory that holds the file and do tail -f gdwebpconvert.log and the latest entry to that file will be shown in the terminal.
As an alternative you can use WordPress's own debugging feature by adding these lines to wp-config.php.
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', true);
This will lead to info being output to the debug.log file, also in the root directory of your WordPress installation, though it will also add tons more data in there all the time. So I prefer the above little helper function to get just the value I currently want to see without having to search the debug.log file for what I am looking for.
As for the conversion, as soon as I could see what data I am working with I wrote a class that converts the uploaded image and all its created sizes after the upload is done to the WebP format. Go ahead an uncomment the debug() statements to follow along. Given this https://github.com/Imagick/imagick/issues/358 and the issues I described with Imagick since WordPress 5.2 this presents a simple solution to just create WebP versions of your files on the server that you can then use in any way you like without automatic .htaccess or other features added.
Feel free to do with this what you want and need. ;)
<?php
/**
* Plugin Name: GD WebP Converter
* Plugin URI: https://stackoverflow.com/a/67234000
* Description: After uploading an image it will be converted to WebP format using the GD image engine. <a target="_blank" href="https://developer.wordpress.org/reference/classes/wp_image_editor_gd/">WP GD Image Engine</a> If the file is deleted form the Media Library the created WebP conversions will also be deleted.
* Version: 1.0.0
* Requires at least: 5.5
* Requires PHP: 7.2
* Author: lowtechsun
* Author URI: https://stackoverflow.com/users/1010918/lowtechsun
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
//=================================================
// Security: Abort if this file is called directly
//=================================================
if ( ! defined( 'ABSPATH' ) ) {
die;
}
function debug( $info ) {
$message = null;
if ( is_string( $info ) || is_int( $info ) || is_float( $info ) ) {
$message = $info;
} else {
$message = var_export( $info, true );
}
if ( $fh = fopen( ABSPATH . '/gdwebpconvert.log', 'a' ) ) {
fputs( $fh, date( 'Y-m-d H:i:s' ) . " $message\n" );
fclose( $fh );
}
}
add_filter( 'wp_generate_attachment_metadata', 'gd_webp_converter', 10, 2 );
function gd_webp_converter( $metadata, $attachment_id ) {
$gd_webp_converter = new GDWebPConverter( $attachment_id );
$gd_webp_converter->check_file_exists( $attachment_id );
$gd_webp_converter->check_mime_type();
$gd_webp_converter->create_array_of_sizes_to_be_converted( $metadata );
$gd_webp_converter->convert_array_of_sizes();
return $metadata;
}
class GDWebPConverter {
private $file_path;
private $file_dirname;
private $file_ext;
private $file_name_no_ext;
private $array_of_sizes_to_be_converted = array();
private $array_of_sizes_to_be_deleted = array();
public function __construct( $attachment_id ) {
$this->file_path = get_attached_file( $attachment_id );
debug( $this->file_path );
// https://stackoverflow.com/questions/2183486/php-get-file-name-without-file-extension/19040276
$this->file_dirname = pathinfo( $this->file_path, PATHINFO_DIRNAME );
debug( $this->file_dirname );
$this->file_ext = strtolower( pathinfo( $this->file_path, PATHINFO_EXTENSION ) );
debug( $this->file_ext );
$this->file_name_no_ext = pathinfo( $this->file_path, PATHINFO_FILENAME );
debug( $this->file_name_no_ext );
}
public function check_file_exists( $attachment_id ) {
$file = get_attached_file( $attachment_id );
if ( ! file_exists( $file ) ) {
$message = 'The uploaded file does not exist on the server. Encoding not possible.';
debug( $message );
throw new Exception( 'The uploaded file does exist on the server. Encoding not possible.', 1 );
}
}
public function check_mime_type() {
// https://www.php.net/manual/en/function.finfo-file.php
$finfo = finfo_open( FILEINFO_MIME_TYPE );
$this->file_mime_type = finfo_file( $finfo, $this->file_path );
finfo_close( $finfo );
// debug( $this->file_mime_type );
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
$this->allowed_mime_type = array( 'image/jpeg', 'image/png' );
if ( ! in_array( $this->file_mime_type, $this->allowed_mime_type, true ) ) {
$message = 'MIME type of file not supported';
// debug( $message );
throw new Exception( 'MIME type of file not supported', 1 );
}
}
public function create_array_of_sizes_to_be_converted( $metadata ) {
// push original file to the array
array_push( $this->array_of_sizes_to_be_converted, $this->file_path );
// debug( $this->array_of_sizes_to_be_converted );
// push all created sizes of the file to the array
foreach ( $metadata['sizes'] as $value ) {
// debug( $value['file'] );
array_push( $this->array_of_sizes_to_be_converted, $this->file_dirname . '/' . $value['file'] );
}
// // debug( $this->array_of_sizes_to_be_converted );
}
public function convert_array_of_sizes() {
debug( $this->array_of_sizes_to_be_converted );
switch ( $this->file_ext ) {
case 'jpeg':
case 'jpg':
foreach ( $this->array_of_sizes_to_be_converted as $key => $value ) {
$image = imagecreatefromjpeg( $value );
if ( 0 === $key ) {
imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp', 80 );
} else {
$current_size = getimagesize( $value );
// debug( $current_size );
imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '-' . $current_size[0] . 'x' . $current_size[1] . '.webp', 80 );
}
imagedestroy( $image );
}
break;
case 'png':
foreach ( $this->array_of_sizes_to_be_converted as $key => $value ) {
$image = imagecreatefrompng( $value );
imagepalettetotruecolor( $image );
imagealphablending( $image, true );
imagesavealpha( $image, true );
if ( 0 === $key ) {
imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp', 80 );
} else {
$current_size = getimagesize( $value );
// debug( $current_size );
imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '-' . $current_size[0] . 'x' . $current_size[1] . '.webp', 80 );
}
imagedestroy( $image );
}
break;
// animated GIF to WebP not supported by GD - imagecreatefromgif
// case 'gif':
// foreach ( $this->array_of_sizes_to_be_converted as $key => $value ) {
// $image = imagecreatefromgif( $value );
// if ( 0 === $key ) {
// imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp', 80 );
// } else {
// $current_size = getimagesize( $value );
// // debug( $current_size );
// imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '-' . $current_size[0] . 'x' . $current_size[1] . '.webp', 80 );
// }
// imagedestroy( $image );
// }
// break;
default:
return false;
}
}
public function create_array_of_sizes_to_be_deleted( $attachment_id ) {
// debug( $attachment_id );
$this->attachment_metadata_of_file_to_be_deleted = wp_get_attachment_metadata( $attachment_id );
// debug( $this->attachment_metadata_of_file_to_be_deleted );
// push original file to the array
array_push( $this->array_of_sizes_to_be_deleted, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp' );
// debug( $this->array_of_sizes_to_be_converted );
// push all created sizes of the file to the array
foreach ( $this->attachment_metadata_of_file_to_be_deleted['sizes'] as $value ) {
// debug( $value );
$this->value_file_name_no_ext = pathinfo( $value['file'], PATHINFO_FILENAME );
// debug( $this->value_file_name_no_ext );
array_push( $this->array_of_sizes_to_be_deleted, $this->file_dirname . '/' . $this->value_file_name_no_ext . '.webp' );
}
// debug( $this->array_of_sizes_to_be_deleted );
}
public function delete_array_of_sizes() {
debug( $this->array_of_sizes_to_be_deleted );
foreach ( $this->array_of_sizes_to_be_deleted as $key => $value ) {
// debug( $value );
unlink( $value );
}
}
}
add_action( 'delete_attachment', 'delete_webp_conversions', 10 );
function delete_webp_conversions( $attachment_id ) {
$delete_webp_conversions = new GDWebPConverter( $attachment_id );
$delete_webp_conversions->create_array_of_sizes_to_be_deleted( $attachment_id );
$delete_webp_conversions->delete_array_of_sizes();
}
In the end I also added a method that, once you opt to delete a file by clicking `Delete Permanently" in the Media Library it will delete all the created WebP versions of the file. If you delete a post this will not happen as per default behavior of WordPress as you never know if you might need the file in another post.
Make sure that you default to the GD image editor if you want to make good use of this class. => https://support.pagely.com/hc/en-us/articles/115000052451
<?php
/**
* Plugin Name: Use GD For Image Processing
* Plugin URI: https://support.pagely.com/hc/en-us/articles/115000052451
* Description: Sets GD to the default image processor.
* Version: 1.0.0
* Requires at least: 5.5
* Requires PHP: 7.2
* Author: JeffMatson, Pagely
* Author URI: https://pagely.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
add_filter( 'wp_image_editors', 'pagely_default_to_gd' );
function pagely_default_to_gd() {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
Thx, Jan!
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);
?>
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
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
I have a custom page template. This template have a custom form that user can upload a file. Now, the uploaded file/s will not upload in the MySQL but in the file system/local folder (local computer).
I already have a PHP snippet, but the code is not working I'm getting an errors.
How to fix this?
Snippet:
if(isset($_POST['submit'])){
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
$resumeFile = isset($_FILE['resumeFile']['name']) ? $_FILE['resumeFile']['name']: '';
$info = pathinfo($_FILES['resumeFile']['name']);
$ext = $info['extension'];
$file_rename= $lastName.$ext;
$target = 'C://xampp/htdocs/files/'.$file_rename;
move_uploaded_file($_FILES['resumeFile']['tmp_name'], $target);
}
Errors:
Notice: Undefined index: resumeFile .... on line 130
Notice: Undefined index: extension .... on line 131
Notice: Undefined index: resumeFile .... on line 135
Try the following snippet, to upload files on different directory other than default uploads directory.
function change_my_upload_directory( $dir ) {
return array (
'path' => WP_CONTENT_DIR . '/your-custom-dir',
'url' => $dir['baseurl'] . '/wp-content/your-custom-dir',
'subdir' => '/your-custom-dir',
) + $dir;
}
if( isset( $_FILES[ "resumeFile" ] ) ) {
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
// Overrides the uploads directory location
add_filter( 'upload_dir', 'change_my_upload_directory' );
$movefile = wp_handle_upload( $_FILES[ "resumeFile" ], array( 'test_form' => false ) );
// Remove the filter, so that subsequant uploads will be dsent to default uploads directory
remove_filter( 'upload_dir', 'change_my_upload_directory' );
return $movefile;
}
return false;
wp_handle_upload will return an object which contains the following properties
$movefile[ 'file' ] // uploaded file object
$movefile[ 'url' ] // current url ( file location ) of the file
$movefile[ 'type' ] // uploaded file type
If wp_handle_upload fails it will return error object, you can check for failed upload like this
if( isset( $movefile[ 'error' ] ) ) {
// handle the error
}