image upload from url with php oop - php

i am using the code bellow to upload images to my wp directory.
I tried to modified the code so i can download images directly from the url but i didnt have any luck.
My code is bellow:
<?php
class imgUploader
{
var $exts = array( ".png", ".gif", ".png", ".jpg", ".jpeg" ); //all the extensions that will be allowed to be uploaded
var $maxSize = 9999999; //if you set to "0" (no quotes), there will be no limit
var $uploadTarget = "../wp-content/uploads/"; //make sure you have the '/' at the end
var $fileName = ""; //this will be automatically set. you do not need to worry about this
var $tmpName = ""; //this will be automatically set. you do not need to worry about this
public function startUpload()
{
$this->fileName = $_FILES['uploaded']['name'];
$this->tmpName = $_FILES['uploaded']['tmp_name'];
if( !$this->isWritable() )
{
die( "Sorry, you must CHMOD your upload target to 777!" );
}
if( !$this->checkExt() )
{
die( "Sorry, you can not upload this filetype!" );
}
if( !$this->checkSize() )
{
die( "Sorry, the file you have attempted to upload is too large!" );
}
if( $this->fileExists() )
{
die( "Sorry, this file already exists on our servers!" );
}
if( $this->uploadIt() )
{
echo "Your file has been uploaded!<br><br>Click here to view your file!";
}
else
{
echo "Sorry, your file could not be uploaded for some unknown reason!";
}
}
public function uploadIt()
{
return ( move_uploaded_file( $this->tmpName, $this->uploadTarget . time() . $this->fileName ) ? true : false );
}
public function checkSize()
{
return ( ( filesize( $this->tmpName ) > $this->maxSize ) ? false : true );
}
public function getExt()
{
return strtolower( substr( $this->fileName, strpos( $this->fileName, "." ), strlen( $this->fileName ) - 1 ) );
}
public function checkExt()
{
return ( in_array( $this->getExt(), $this->exts ) ? true : false );
}
public function isWritable()
{
return ( is_writable( $this->uploadTarget ) );
}
public function fileExists()
{
return ( file_exists( $this->uploadTarget . time() . $this->fileName ) );
}
}
$img = new imgUploader();
if( $_POST['upload_file'] )
{
$img->startUpload();
}
else
{
echo "<form method=\"post\" enctype=\"multipart/form-data\">
<p>
<label for=\"file\">Select a file to upload:</label> <input type=\"file\" name=\"uploaded\" id=\"file\"><br>
<input type=\"submit\" name=\"upload_file\" value=\"Upload!\">
<p>
</form>";
}
?>
I tried to remove the hole form and give to $filename and $temp name the image url but it doesnt work..
any idea?

Related

Pass global variable into function not working

I am trying to use allow my custom API endpoint to upload files to a custom directory based on information sent in the request body. It is coming through fine but I am not getting it to pass into the directory properly. I have tried getting the studentid from the request body and then calling that as a global in my function but it is not working.
add_filter("wcra_upload_callback", "wcra_upload_callback_handler");
function wcra_upload_callback_handler($request) {
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH.'wp-admin/includes/file.php');
}
$studentid = $request['studentid'];
function studentresultsdir($dir) {
global $studentid;
$mydir = 'https://example.com/wp-content/uploads/studentresults/';
$dir['path'] = $mydir;
$dir['url'] = $mydir;
$dir['subdir'] = $studentid;
var_dump($dir);
return $dir;
}
add_filter("upload_dir", "studentresultsdir");
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
echo __('File is valid, and was successfully uploaded.', 'textdomain')."\n";
var_dump($movefile);
} else {
echo $movefile['error'];
}
remove_filter("upload_dir", "studentresultsdir");
}
My var_dump of $dir is giving me an empty subdirectory. I think this is the cause of my "unable to create directory" error too but need to work this step out first.
Just wanted to add that I will be adding authentication checks once I get this working.
I managed to solve this particular error by moving the global variable outside of all functions.
add_filter("wcra_upload_callback", "wcra_upload_callback_handler");
$studentid = '';
function wcra_upload_callback_handler($request) {
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH.'wp-admin/includes/file.php');
}
global $studentid;
$studentid = $request['studentid'];
function studentresultsdir($dir) {
global $studentid;
$mydir = 'https://example.com/wp-content/uploads/studentresults/';
$dir['path'] = $mydir;
$dir['url'] = $mydir;
$dir['subdir'] = '/'.$studentid;
var_dump($dir);
return $dir;
}
add_filter("upload_dir", "studentresultsdir");
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
echo __('File is valid, and was successfully uploaded.', 'textdomain')."\n";
var_dump($movefile);
} else {
echo $movefile['error'];
}
remove_filter("upload_dir", "studentresultsdir");
}

How to get the file name and file size for the attachment of my custom post type

I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .
Here is my Meta Box code
function add_custom_meta_boxes() {
// Define the custom attachment for posts
add_meta_box(
'wp_custom_attachment',
'Custom Attachment',
'wp_custom_attachment',
'circular',
'side'
);
} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_custom_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your PDF here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';
echo $html;
} // end wp_custom_attachment
function save_custom_meta_data($id) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $id;
} // end if
if('circular' == $_POST['post_type']) {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} else {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} // end if
/* - end security verification - */
// Make sure the file array isn't empty
if(!empty($_FILES['wp_custom_attachment']['name'])) {
// Setup the array of supported file types. In this case, it's just PDF.
$supported_types = array('application/pdf');
// Get the file type of the upload
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
// Check if the type is supported. If not, throw an error.
if(in_array($uploaded_type, $supported_types)) {
// Use the WordPress API to upload the file
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
} // end if/else
} else {
wp_die("The file type that you've uploaded is not a PDF.");
} // end if/else
} // end if
} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');
function update_edit_form() {
echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
do out put the link of that file
<?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
Download PDF Here
First need to get the file url the we can get the size and name . here wp_custom_attachment is the custom field id.
// retrieve file of the custom field
$file = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
//get the url
$url = $file['url'];
//Replace url to directory path
$path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );
if ( is_file( $path ) ){
$filesize = size_format( filesize( $path ) );
$filename = basename($path);
}
echo '<p>Name: ' . $filename . '</p>';
echo '<p>Size: ' . $filesize . '</p>';
If you can get the attachment ID number ($attachment_id below) you should be able to do something like this to get the name/size:
$attachment_id = 'YOUR_PDF_ID';
$attahment_file = get_attached_file( $attachment_id );
function getSize($file) {
$bytes = filesize($file);
$s = array('b', 'Kb', 'Mb', 'Gb');
$e = floor(log($bytes)/log(1024));
return sprintf( '%.2f ' . $s[$e], ( $bytes/pow( 1024, floor($e) ) ) );
}
echo '<p>Name: ' . basename( $attahment_file ) . '</p>';
echo '<p>Size: ' . getSize( $attahment_file ) . '</p>';
I found the "getSize" function on another post here. It was more accurate than using the native PHP "filesize" function in terms of matching the size shown in the WP media library meta.

Upload files to user folder

I'm trying to create a new folder within the upload folder so that a user can upload file to there own folder.
Can I do this using PHP or do I need to a column "LONGBLOB" in MYSQL?
I've read that it's not good practice to store images in you database
<?php
header('Content-Type: application/json');
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
if(!empty($_FILES["file"])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
}else{
$failed[] = array(
'name' => $name);
}
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
}
?>
Assuming you have the user's username or id in a session variable then that could be used as the basis for the new folder into which he/she would upload files.
Obiously that same username,id would have to be used when they wish to download the file. By storing a hash and the filepath you can generate links that do not reveal filename, folder path, owner etc as the db could check the ash and return the file and path when needed.
The following is an untested example of generating the user's own folder and using that in the upload process - hope it gives you some ideas / guidance.
<?php
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
/*
generate a suitable name for the new folder,
remove characters which might be troublesome
*/
$userdir = str_replace(
array("'",'"','-'),
array('','','_'),
$_SESSION['username']
);
/*
new path into which the files are saved
It might be better to have the files
stored outside of the document root.
*/
$savepath = 'uploads/' . $userdir;
/* create the folder if it does not exist */
if( !file_exists( $savepath ) ) {
mkdir( $savepath );
chown( $savepath, $username );
chmod( $savepath, 0644 );
}
if( !empty( $_FILES["file"] ) ) {
foreach( $_FILES['file']['name'] as $key => $name ) {
if( $_FILES['file']['error'][$key] === 0 ) {
$temp = $_FILES['file']['tmp_name'][$key];
/*
is there anything to be gained by hashing the filename?
the hash would be the same for filenames with the same
name anyway.
If the file is large, calculating the hash of the file could
take some time...
*/
$ext = explode('.', $name);
$ext = strtolower( end( $ext ) );
$file = md5_file( $temp ) . time() . '.' . $ext;
/* generate a random hash to use in downloads */
$hash=uniqid( md5( date(DATE_COOKIE) ) );
/* here probably - store reference in db? Assign permissions based upon owner etc */
$sql='insert into `table` (`filename`,`username`,`uid`,`datetime`,`hash`) values (?,?,?,?,?);';
/* bind params and execute - not shown */
if ( in_array( $ext, $allowed ) === true && move_uploaded_file( $temp, "{$savepath}/{$file}") === true ) {
$succeeded[] = array( 'name' => $name, 'file' => $file );
}else{
$failed[] = array( 'name' => $name );
}
}
}
}
if (!empty($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
} else {
header( 'HTTP/1.1 404 Not Found', true, 404 );
}
?>

Php function calling, Undefined function error

Earlier I have a form that ask user to upload a picture and I have this function:
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
}
Basically it moves the uploaded picture to images file. Then I am calling this function in an if statement:
if (fileUploaded () == true) {
if ($fileResult) {
/*checking the size of file*/
}
}
else {
$fileName = "default.jpg";
}
After when I try to upload and submit it gives the error in the below:
Fatal error: Call to undefined function fileUploaded()
What should be the problem?
Thanks.
You don't return a default value in your function. Maybe it's the problem :
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
return false;
}
//functions.php
function fileUpload($path) {
if(!isset($_FILES['picture'])) return false;
$fileName = $_FILES['picture']['name'];
$fileTmpLoc = $_FILES['picture']['tmp_name'];
if(move_uploaded_file ($fileTmpLoc, $path)) return $fileName;
return false;
}
//main.php
include('functions.php');
$fileName = fileUpload('/images/');
if($fileName === false) {
$fileName = 'default.jpg';
}
//do the rest here
Something similar to the above code. Since your function is in a different file, you need to include it (or require it)

Trying to upload multiple files in PHP

I've been struggling with this for a while now and hoping someone can point me in the right direction. I have a script that works for uploading a single image. I'm now trying to amed it so that I can update more than 1 file at once. 2 in the example below. I understand that name needs to be an array and I loop through them however I only seem to be encountering errors. I've read and tried various different things.
I either was able to upload one file but not the second, upload no files or a blank white screen.
Below is what I'm currently working with after having various edits.
<?php
$upload_dir= 'training/trainingDocuments';
$numUploads = 2;
$msg = 'Please select files for uploading';
$errors = array();
if(isset($_FILES['myTrainingFile']['tmp_name']))
{
for($i=0; $i < count($_FILES['myTrainingFile']['tmp_name']);$i++)
{
$fileName = $_FILES['myTrainingFile']['name'][$i];
$tempName = $_FILES['myTrainingFile']['tmp_name'][$i];
$blacklist = array('exe','php','jsp','js','bat','asp','aspx','com','dmg');
$a = explode('.', $fileName);
$fileExt = strtolower(end($a)); unset($a);
$fileSize = $_FILES['myTrainingFile']['size'];
if(in_array($fileExt, $blacklist) === true){
$errors[] = "File type not allowed";
}
//$newPath = $general->fileNewPath($path, $fileName);
$newPath = "training/trainingDocuments/" . $_FILES['myTrainingFile']['name'][$i];
$moveFileResult = move_uploaded_file($tempName, $newPath);
if($moveFileResult != true){
$errors[] = 'Upload Failed - MOVE';
}
$comments = htmlentities(trim($_POST['comments']));
$category = htmlentities(trim($_POST['category']));
//insert into db
$training->uploadDocument($fileName, $category, $comments);
if(!is_uploaded_file($_FILES['myTrainingFile']['name'][$i]))
{
$errors[] = 'Uploading '.$_FILES['myTrainingFile']['name'][$i] . 'failed -.-';
}
}
}
?>
Thanks for any help!
Try this code, i added a function named convert_files, so you can handle your uploads in a better way
Code:
<?php
$upload_dir = "training/trainingDocuments";
$numUploads = 2;
$msg = "Please select file(s) for uploading";
$errors = array();
// how many files you want to upload
$maxFiles = 3;
if ( $files = convert_files( $_FILES["myTrainingFile"] ) ) {
foreach( $files as $i => $file ) {
$fileName = $file["name"];
$tempName = $file["tmp_name"];
$fileSize = $file["size"];
// get file extension, and do strtolower
$fileExt = strtolower( pathinfo( $fileName, PATHINFO_EXTENSION ) );
// invalid file types
$blacklist = array( 'exe','php','jsp','js','bat','asp','aspx','com','dmg' );
// new path to upload current file
$newPath = "training/trainingDocuments/".$fileName;
// Check whether its a valid file or invalid file
if ( in_array( $fileExt, $blacklist ) ) {
// invalid file type, add error
$errors[$i] = "File type not allowed";
}
if ( !is_uploaded_file( $tempName ) ) {
// its'' not an uploaded file, add error
$errors[$i] = "Uploading ".$fileName." failed -.-";
}
if ( file_exists( $newPath ) ) {
// file already exists in your directory, add error
$errors[$i] = "File ".$fileName." already exists";
// if you dont want to add error, (adding an error will not upload file)
// just comment above line, and uncomment below line
/*
// get the filename without extension
$name = pathinfo( $fileName, PATHINFO_FILENAME );
//create new file name
$fileName = $name."_".uniqid().".".$fileExt;
//update upload path
$newPath = "training/trainingDocuments/".$fileName;
*/
}
// make sure $errors[$i] contains any errors
if ( isset( $errors[$i] ) ) {
// errors occured, so continue to next file
continue;
}
if ( !move_uploaded_file( $tempName, $newPath ) ) {
$errors[$i] = "Upload Failed - MOVE"; // failed to move file
}
$comments = htmlentities( trim( $_POST['comments'] ) );
$category = htmlentities( trim( $_POST['category'] ) );
// Upload document
$training->uploadDocument( $fileName, $category, $comments );
// check maximum allowed files limit exceeded
if ( ( $i + 1 ) == $maxFiles ) {
// limit exceeded, break the execution
break;
}
}
}
?>
Function:
<?php
function convert_files( $files ) {
if ( is_array( $files ) && !empty( $files["name"] ) ) {
if ( is_array( $files["name"] ) ) {
$merged = array();
foreach( $files["name"] as $i => $name ) {
$merged[] = array(
"name" => $name,
"type" => $files["type"][$i],
"size" => $files["size"][$i],
"error" => $files["error"][$i],
"tmp_name" => $files["tmp_name"][$i]
);
}
return $merged;
}
return array( $files );
}
return false;
}
?>

Categories