How to add simple image upload functionality to WP plugin - php

I want to add simple image upload functionality to my WP plugin. So the simple form with upload button. I dont want to use standard thickbox included in WP for this.
When you press the button file selection dialog will appear, you select file from your drive and it'll be added to the input box.
Then when you press "save" button for plugin options it will send with form and handled on server side.
I wonder if there is ready to use WP functionality for the server part.
As I want to save the upload image path also to DB options table.
EDIT: added PHP tag as wordpress is a PHP language

You're in some luck-I'm currently working on a mod that would allow image uploads for MarketPress. Here's my skeleton, poorly indented script. This should help get you started methinks?
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10240" />
Send this file: <input name="userfile" type="file" />
Send this file: <input name="userfile2" type="file" />
<input type="submit" value="Send File" />
</form>
<?php
if ($_POST['MAX_FILE_SIZE'] == '10240' ){
$uploaddir = 'public_html/uploads';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$validfiletype;
if ( preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['userfile']['name']) )
$validfiletype = 0;
elseif( preg_match('/\\.(jpg|jpeg|gif|png|pdf|psd)$/i', $_FILES['userfile']['name']) )
$validfiletype = 1;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "File upload unsuccessful.";
}}
?>

Related

How to create directory and save image in it using php

I have a code where I am selecting an image and then entering the name of the directory I want to create to save that image. After this, once a button is clicked the directory should be created in the given path and file should be saved in it.
Below is the code I am using:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file"/>
<input type="text" name="idtest" value=<?php echo $idtest; ?> >
<input type="submit" value="Send File" multiple/>
</form>
upload.php
<?php
$uploaddir = 'G:/dataset/' . $idtest;
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']) ;
echo $uploadfile;
?>
Here in the above code I have not include the create directory part which I still have to work on. Now ideally the variable idtest should be appended with uploaddir variable so whenever I am printing the value of uploadfile the last directory should be the one which I entered in the text box. But its not working. Can anyone please throw some light on why its not working. Thanks
Give this upload script a try. Based on your comments, it seems the first issue is the directory name entered in the form not being added to the full uploadfile path. You will need to grab idtest from the $_POST variable first. I would also recommend using move_uploaded_file to move the uploaded file.
upload.php
<?php
$uploaddir = 'G:/dataset/' . $_POST['idtest'];
// check if directory exists
if(!is_dir($uploaddir)){
mkdir($uploaddir);
}
$uploadfile = $uploaddir ."/". basename($_FILES['userfile']['name']) ;
echo $uploadfile;
move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile);
?>
Please ensure proper form validation and file name checks for security reasons, but that is beyond the scope of this answer. As the other commenters have mentioned, ensure file system permissions are set to allow writing to G:/dataset/.

Problems with a php form upload

I am trying to upload a file via a form and a php file. I have used the same method many times throughout my website with no problems, however this time I just can not get it to work. On my form I have this....
<span class="purple"><strong>Upload Your Image</strong></span>
<input name="userfile" type="file" id="userfile" class="textbox">
<br /><br />
<label>
<input name="submit" type="submit" class="createbutton" id="submit1" value="ADD TO BASKET">
</label>
In my php file I have this...
//upload image first
$uploaddir = '../images/';
$uploadfile = $uploaddir. $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
$status = 1;//uploaded
$data["printfile"] = $_FILES['userfile']['name'];
} else {
$status = 0;//cant upload
echo "Upload Failed!\n";
$err = "";
}
Every time it just gives me the Upload Failed error message. Any ideas?
Ah right, I really feel like a fool now. I somehow managed to miss enctype="multipart/form-data" on my form tag. Thanks so much for your help, works perfectly now.

uploading sessions with php not outputing

I want to view data stored in an uploading session but all I get is 'Null', am I going about this the wrong way?
session_start();
if(isset($_POST['submit'])){
$target = "test/";
$target = $target . basename('test') ;
$file = ($_FILES["uploaded"]["name"]);
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){echo "done";}else echo "error";
}
and the html:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test" />
<input type="file" name="uploaded" />
<input type="submit" name='submit' />
</form>
You're trying to get upload progress status when upload is already done.
If you want to make it working, then you can for example send your form to iframe and during the upload ask server, using ajax, what is the status.
I would suggest to use it rather as a fallback for older browsers cause currently browsers are supporting ajax upload and you can display upload progress without making additional requests to server and creating some strange hidden iframes ;)

Image uploading via PHP returning empty array

I am unable to successfully upload an image/file to my server. The php is as follows:
//This is the directory where images will be saved
$uploadDir = "./";
$uploadFile = $uploadDir . basename( $_FILES['photo']['name']);
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadFile)){
echo "The file has been uploaded successfully.";
} else {
print_r($_FILES);
}
I chose the directory at which this script lives, to ensure the functionality before I upload to the final directory. I want to upload photo's, and will check for file extensions later - but for now I at least need the upload functionality to work.
I get an empty array returned.
The form is as follows:
<form id="imageUploadForm" name="imageForm" enctype="multipart/form-data" action="imageController.php">
<label for="photo" class="blogLabel">Upload an Image</label>
<input type="file" name="photo" id="imageUpload">
<input type="submit" name="submit" id="imageSubmit" class="btn btn-primary" value="Upload">
</form>
You forgot the most important thing about a form -- the method!
If there is no method set it defaults to get.
You want post!
Add method="post" to your form.

Upload to a PHP Server, using Ajax ( XMLHttp POST)

Right now i'm using the below method to Upload a file to PHP
<form enctype="multipart/form-data" action="http://sserver.com/fileupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="hidden" name="filename" value="file_uploaded.gif" />
<input type="hidden" name="username" value="foobar"/>
Please choose a file:
<input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
I read the $_POST and $_FILE in php to complete upload like this.
$target = $_SERVER['DOCUMENT_ROOT']."/test/upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
echo $target;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
My questions is , can i change the above said code (HTML) to an Ajax XMLHttpRequest without changes in PHP.
You cannot send files to the server via AJAX alone. This is because Javascript (when run in a browser) does not have access to the host's file system.
There are ways to make AJAX-style upload boxes using iframes, where the whole page is not reloaded during an upload, but this is not a simple task in itself. jQuery provides a couple of libraries to make this easier.
EDIT As ThiefMaster rightly points out HTML5 provides mechanisms for doing this more neatly.

Categories